[
  {
    "path": ".gitattributes",
    "content": "# Ensure batch files are crlf\n*.bat text eol=crlf\n"
  },
  {
    "path": ".gitignore",
    "content": ".cache\n.coverage\n*.pyc\n__pycache__\n*~\n*.tar.gz\n*.patch\n.pytest_cache\n.tox\ntags\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "repos:\n- repo: git@github.com:pre-commit/pre-commit-hooks.git\n  rev: v1.4.0\n  hooks:\n  - id: autopep8-wrapper\n    language_version: python2\n    args:\n    - --in-place\n    - --aggressive\n    - --aggressive\n    - --ignore=E731\n    - --max-line-length=131\n  - id: check-added-large-files\n    language_version: python2\n  - id: check-ast\n    language_version: python2\n  - id: check-case-conflict\n    language_version: python2\n  - id: check-docstring-first\n    language_version: python2\n  - id: debug-statements\n    language_version: python2\n  - id: double-quote-string-fixer\n    language_version: python2\n  - id: end-of-file-fixer\n    language_version: python2\n    exclude_types: [batch, lua]\n  - id: fix-encoding-pragma\n    language_version: python2\n  - id: flake8\n    language_version: python2\n    args:\n    - --max-complexity=10\n    - --max-line-length=131\n    - --ignore=E402,E731\n    - --exclude=bin/autojump_argparse.py\n  - id: name-tests-test\n    language_version: python2\n  - id: requirements-txt-fixer\n    language_version: python2\n  - id: trailing-whitespace\n    language_version: python2\n- repo: git@github.com:asottile/reorder_python_imports.git\n  rev: v1.1.1\n  hooks:\n  - id: reorder-python-imports\n  language_version: python2\n- repo: git@github.com:asottile/add-trailing-comma\n  rev: v0.7.0\n  hooks:\n  - id: add-trailing-comma\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: python\n\npython: 2.7\n\nenv:\n  - TOX_ENV=py26\n  - TOX_ENV=py27\n  - TOX_ENV=py32\n  - TOX_ENV=py33\n  - TOX_ENV=py34\n  - TOX_ENV=flake8\n\ninstall:\n  - pip install tox\n\nscript:\n  - tox -e $TOX_ENV\n"
  },
  {
    "path": "AUTHORS",
    "content": "The primary authors are:\n\n    Joel Schaerer\n    William Ting\n\nHere is an inevitably incomplete list of much appreciated contributors -- people\nwho have submitted patches, reported bugs, maintained packages, and in general\nmade autojump that much better (in no particular order):\n\n    Tanguy Ortolo\n    Thibault North\n    Olivier Mehani\n    Fabien Bourgeois\n    Binh Nguyen\n    Neeraj Verma\n    Evan Shelhamer\n    xiannaitong\n    Simon Marache-Francisco\n    Pierre Gueth\n    Tom Parker\n    Liyang Chang\n    Jez Ng\n    jjk-jacky\n    Daniel Hahler\n    Jui-Shan Liang\n    Pierre Gueth\n    Alexander Bolodurin\n"
  },
  {
    "path": "CHANGES.md",
    "content": "## Summary of release changes, see commit history for more details:\n## https://github.com/wting/autojump/commits/master/\n\n### Release v22.4.0:\n- minor zsh performance improvement\n\n### Release v22.3.0:\n- use colors only if stdout is a terminal\n- updated RedHat docs\n- misc bug fixes for fish and Clink versions\n\n### Release v22.2.2:\n\n#### Backwards Incompatible\n\n- install.sh -> install.py\n    - `--auto` option removed\n    - `--local` option removed, defaults to local user install\n    - `--global` option renamed to `--system`\n    - install.py modifies autojump.sh accordingly for custom installations\n    - it is recommended that maintainers use install.py with `--destdir` and\n      `--prefix` accordingly. Two stage installations requires manually updating\n      autojump.sh.\n- uninstall.sh -> uninstall.py\n    - automatically removes user and system installations\n    - now removes custom installations cleanly when passed appropriate\n      `--destdir` and/or `--prefix` options.\n    - new `--userdata` option to remove autojump database\n- all user environmental options removed:\n    - AUTOJUMP_DATA_DIR\n    - AUTOJUMP_IGNORE_CASE\n    - AUTOJUMP_KEEP_SYMLINKS\n- misc bug fixes\n\n#### Features and Bug Fixes\n\n- fish shell support added\n- defaults to smartcasing\n    - If any uppercase characters are detected, then search is case sensitive.\n      Otherwise searches default to case insensitive.\n- defaults to symlinks\n    - symlinks are not resolved to real path and thus results in duplicate\n      database entries but ensuring that short paths will be used\n- autojump now uses ~/Library/autojump for storing data on OS X instead of\n  incorrectly using Linux's $XDG_DATA_HOME. Existing data should automatically\n  be migrated to the new location.\n- Past behavior jumped to the highest weight database entry when not passed any\n  arguments. The new behavior is to stay in the current directory.\n\n\n### Release v21.6.8:\n\n- fix --increase and --decrease options\n- heavy refactoring\n- remove unused unit tests\n\n### Release v21.5.8:\n\n- fix security bug: http://www.openwall.com/lists/oss-security/2013/04/25/14\n- minor documentation updates, optimization performances, bug fixes\n\n### Release v21.5.1:\n\n- add options to manually increase or decrease weight of the current directory\n  with --increase or --decrease\n- add `_j` back, necessary for zsh tab completion\n\n### Release v21.4.2:\n\n- add options to open file explorer windows with `jo`, `jco` which maps to jump\n  open, jump child open.\n- remove `_j`\n\n### Release v21.3.0:\n\n- `jumpapplet` removed.\n- performance improvements when using network mounts (e.g. sshfs)\n\n### Release v21.2.0:\n\n- Add `jc` command (jump child). Jumps to a subdirectory of the current working\n  directory.\n\n### Release v21.1.0:\n\n- install.sh is rewritten to add support for --path and --destdir options,\n  making it easier for package maintainers to install autojump specifically into\n  certain locations. Thanks to jjk-jacky for his contributions.\n\n### Release v21.0.0:\n\n- Switch to semantic versioning (http://semver.org/): major.minor.micro\n- Migration code for v17 or older users has been removed.\n\n    During testing, it was apparent that the migration code wasn't working to\n    begin with. The major distros (Debian, RedHat) have already moved to v18+\n    for LTS. Rolling release distros and Homebrew / Macports are regularly kept\n    up to date.\n\n    Users upgrading from v17 or older will start with a new database.\n\n- Approximate matching introduced. Matching priority is now:\n\n    1. exact match\n    2. case insensitive match\n    3. approximate match\n\n- The `j` function now accepts autojump arguments (e.g. --help, --stat).\n\n    As a result, the `jumpstat` alias is now removed. The preferred method is `j\n    --stat` or `j -s`. Consequently, autojump cannot jump to directories\n    beginning with a hyphen '-'.\n\n- Always use case insensitive search with AUTOJUMP_IGNORE_CASE=1\n\n    As mentioned earlier, normal priority is to prefer exact match and then\n    check for case insensitive match. For users who prefer case insensitivity\n    can now modify the program behavior.\n\n- Prevent database decay with AUTOJUMP_KEEP_ALL_ENTRIES=1\n\n    The database is regularly trimmed for performance reasons. However users can\n    prevent database maintenance with the above environmental variable.\n\n- ZSH tab completion fixed.\n\n    ZSH behavior now matches Bash behavior. However it requires the `compinit`\n    module to be loaded. Add the following line to ~/.zshrc:\n\n    autoload -U compinit; compinit\n\n    To use type:\n\n    j<space><tab><tab>\n\n    A menu showing the top database entries will be displayed. Type in any\n    number followed by <tab> to complete the entry.\n\n- Database entry weight growth changed form linear to logarithmic scale.\n\n    A combination of low total weight ceiling and linear growth resulted in a\n    few, commonly used directories to be responsible for 50%+ of the total\n    database weight. This caused unnecessary trimming of long tail entries.\n\n    Switching to logarithmic growth combined with regular decay meant that\n    commonly used directories still climbed database ranking appropriately with\n    a more even weight distribution.\n\n- Vendorize argparse so now Python v2.6+ is supported (from v2.7).\n- Unit testing suite added.\n- Miscellaneous refactoring, bug fixes, documentation updates.\n\n### Release v20.0.0:\n\n- Python versions supported is now v2.7+ and v3.2+ due to rewrite using\n  argparse.\n\n- Man page and --help has been overhauled to provide better documentation and\n  usage scenarios.\n\n- Installation scripts now act dependent on current environmental settings.\n\n    If run as root, will do a global install. Installation script also detects\n    which version to install (bash or zsh) dependent on $SHELL.  Both of these\n    behaviors can be overrode using --local/--global or --bash/--zsh arguments.\n\n- Uninstallation script added, will remove both global and local installations\n  but ignores database.\n\n- Allow symlink database entries with AUTOJUMP_KEEP_SYMLINKS=1\n\n    Normally symlinks are resolved to full path to prevent duplicate database\n    entries. However users who prefer symlink paths can modify behavior with the\n    above environmental variable.\n\n- This ChangeLog added to better help package maintainers keep track of changes\n  between releases.\n\n- Miscellaneous bug fixes.\n\n### Release v19.0.0:\n\n- prototype `cp` and `mv` directory tab completion\n- Debian post-installation instructions\n- minor Mac OS X fixes\n\n### Release v18.0.0:\n\n- add automated version numbering\n- performance tweaks to reduce filesystem checks\n- add local installation option\n- unicode fixes\n- ugly fixes for Python 3\n- migrate to new database format\n"
  },
  {
    "path": "LICENSE",
    "content": "autojump is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nautojump is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nfull GNU General Public License below for more details.\n\nautojump is a small tool that maintains a database of your most\nused directories, and finds the best match to help you jump to\nfrequently used places.\n\n                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "Makefile",
    "content": "VERSION = $(shell grep -oE \"[0-9]+\\.[0-9]+\\.[0-9]+\" bin/autojump)\nTAGNAME = release-v$(VERSION)\n\n.PHONY: install\ninstall:\n\t./install.py\n\n.PHONY: uninstall\nuninstall:\n\t./uninstall.py\n\n.PHONY: docs\ndocs:\n\t@echo \"% autojump(1) ${TAGNAME}\" >docs/manpage_header.md\n\t@echo \"%\" >>docs/manpage_header.md\n\t@echo \"% $(shell \\date +%Y-%m-%d)\" >>docs/manpage_header.md\n\tpandoc -s -w man docs/manpage_header.md docs/header.md docs/body.md -o docs/autojump.1\n\tpandoc -s -w markdown docs/header.md docs/install.md docs/body.md -o README.md\n\n.PHONY: lint\nlint: pre-commit\n\t@tox -e pre-commit -- run --all-files\n\n.PHONY: pre-commit\npre-commit:\n\t@tox -e pre-commit -- install -f --install-hooks\n\n.PHONY: release\nrelease: docs\n\t# Check for tag existence\n\t# git describe release-$(VERSION) 2>&1 >/dev/null || exit 1\n\n\t# Modify autojump with version\n\t./tools/git-version.sh $(TAGNAME)\n\n\t# Commit the version change\n\tgit commit -m \"version numbering\" ./bin/autojump\n\n\t# Create tag\n\tgit tag -a $(TAGNAME)\n\n\t# Create tagged archive\n\tgit archive --format=tar --prefix autojump_v$(VERSION)/ $(TAGNAME) | gzip > autojump_v$(VERSION).tar.gz\n\tsha1sum autojump_v$(VERSION).tar.gz\n\n.PHONY: tar\ntar:\n\t# Create tagged archive\n\tgit archive --format=tar --prefix autojump_v$(VERSION)/ $(TAGNAME) | gzip > autojump_v$(VERSION).tar.gz\n\tsha1sum autojump_v$(VERSION).tar.gz\n\n.PHONY: test\ntest: pre-commit\n\t@tox\n\n.PHONY: test-xfail\ntest-xfail: pre-commit\n\t@tox -- --runxfail\n\n.PHONY: test-fast\ntest-fast: pre-commit\n\t@tox -e py27\n\n.PHONY: clean\nclean:\n\t@find . -type f -iname '*.py[co]' -delete\n\t@find . -type d -iname '__pycache__' -delete\n\t@rm -fr .tox\n"
  },
  {
    "path": "README.md",
    "content": "NAME\n----\n\nautojump - a faster way to navigate your filesystem\n\nDESCRIPTION\n-----------\n\nautojump is a faster way to navigate your filesystem. It works by\nmaintaining a database of the directories you use the most from the\ncommand line.\n\n*Directories must be visited first before they can be jumped to.*\n\nUSAGE\n-----\n\n`j` is a convenience wrapper function around `autojump`. Any option that\ncan be used with `autojump` can be used with `j` and vice versa.\n\n-   Jump To A Directory That Contains `foo`:\n\n        j foo\n\n-   Jump To A Directory That Contains `foo`, Preferring Child Directories:\n\n    You can prioritize child directories over matches in the databases via\n\n        jc foo\n\n-   Open File Manager To Directories (instead of jumping):\n\n    Instead of jumping to a directory, you can open a file explorer\n    window (Mac Finder, Windows Explorer, GNOME Nautilus, etc.) to the\n    directory instead.\n\n        jo music\n\n    Opening a file manager to a child directory is also supported:\n\n        jco images\n\n-   Using Multiple Arguments:\n\n    Let's assume the following database:\n\n        30   /home/user/mail/inbox\n        10   /home/user/work/inbox\n\n    `j in` would jump into /home/user/mail/inbox as the higher\n    weighted entry. However you can pass multiple arguments to autojump\n    to prefer a different entry. In the above example, `j w in` would\n    then change directory to /home/user/work/inbox.\n\nFor more options refer to help:\n\n    autojump --help\n\nINSTALLATION\n------------\n\n### REQUIREMENTS\n\n-   Python v2.6+ or Python v3.3+\n-   Supported shells\n    -   bash - first class support\n    -   zsh - first class support\n    -   fish - community supported\n    -   tcsh - community supported\n    -   clink - community supported\n-   Supported platforms\n    -   Linux - first class support\n    -   OS X - first class support\n    -   Windows - community supported\n    -   BSD - community supported\n-   Supported installation methods\n    -   source code - first class support\n    -   Debian and derivatives - first class support\n    -   ArchLinux / Gentoo / openSUSE / RedHat and derivatives -\n        community supported\n    -   Homebrew / MacPorts - community supported\n\nDue to limited time and resources, only \"first class support\" items will\nbe maintained by the primary committers. All \"community supported\" items\nwill be updated based on pull requests submitted by the general public.\n\nPlease continue opening issues and providing feedback for community\nsupported items since consolidating information helps other users\ntroubleshoot and submit enhancements and fixes.\n\n### MANUAL\n\nGrab a copy of autojump:\n\n    git clone https://github.com/wting/autojump.git\n\nRun the installation script and follow on screen instructions.\n\n    cd autojump\n    ./install.py or ./uninstall.py\n\n### AUTOMATIC\n\n#### Linux\n\nautojump is included in the following distro repositories, please use\nrelevant package management utilities to install (e.g. apt-get, yum,\npacman, etc):\n\n-   Debian, Ubuntu, Linux Mint\n\n    All Debian-derived distros require manual activation for policy\n    reasons, please see `/usr/share/doc/autojump/README.Debian`.\n\n-   RedHat, Fedora, CentOS\n\n    Install `autojump-zsh` for zsh, `autojump-fish` for fish, etc.\n\n-   ArchLinux\n-   Gentoo\n-   Frugalware\n-   Slackware\n\n#### OS X\n\nHomebrew is the recommended installation method for Mac OS X:\n\n    brew install autojump\n\nMacPorts is also available:\n\n    port install autojump\n\nWindows\n-------\n\nWindows support is enabled by [clink](https://mridgers.github.io/clink/)\nwhich should be installed prior to installing autojump.\n\nKNOWN ISSUES\n------------\n\n-   autojump does not support directories that begin with `-`.\n\n-   For bash users, autojump keeps track of directories by modifying\n    `$PROMPT_COMMAND`. Do not overwrite `$PROMPT_COMMAND`:\n\n        export PROMPT_COMMAND=\"history -a\"\n\n    Instead append to the end of the existing \\$PROMPT\\_COMMAND:\n\n        export PROMPT_COMMAND=\"${PROMPT_COMMAND:+$PROMPT_COMMAND ;} history -a\"\n\nREPORTING BUGS\n--------------\n\nFor any questions or issues please visit:\n\n    https://github.com/wting/autojump/issues\n\nAUTHORS\n-------\n\nautojump was originally written by Joël Schaerer, and currently\nmaintained by William Ting. More contributors can be found in `AUTHORS`.\n\nCOPYRIGHT\n---------\n\nCopyright © 2016 Free Software Foundation, Inc. License GPLv3+: GNU GPL\nversion 3 or later <http://gnu.org/licenses/gpl.html>. This is free\nsoftware: you are free to change and redistribute it. There is NO\nWARRANTY, to the extent permitted by law.\n"
  },
  {
    "path": "bin/_j",
    "content": "#compdef j\ncur=${words[2, -1]}\n\nautojump --complete ${=cur[*]} | while read i; do\n    compadd -U \"$i\";\ndone\n"
  },
  {
    "path": "bin/autojump",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n  Copyright © 2008-2012 Joel Schaerer\n  Copyright © 2012-2016 William Ting\n\n  * This program is free software; you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation; either version 3, or (at your option)\n  any later version.\n\n  * This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  * You should have received a copy of the GNU General Public License\n  along with this program; if not, write to the Free Software Foundation, Inc.,\n  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\"\"\"\nfrom __future__ import print_function\n\nimport os\nimport sys\nfrom itertools import chain\nfrom math import sqrt\nfrom operator import attrgetter\nfrom operator import itemgetter\n\nif sys.version_info[0] == 3:\n    ifilter = filter\n    imap = map\n    os.getcwdu = os.getcwd\nelse:\n    from itertools import ifilter\n    from itertools import imap\n\n# Vendorized argparse for Python 2.6 support\nfrom autojump_argparse import ArgumentParser\n\n# autojump is not a standard python package but rather installed as a mixed\n# shell + Python app with no outside dependencies (except Python). As a\n# consequence we use relative imports and depend on file prefixes to prevent\n# module conflicts.\nfrom autojump_data import dictify\nfrom autojump_data import entriefy\nfrom autojump_data import Entry\nfrom autojump_data import load\nfrom autojump_data import save\nfrom autojump_match import match_anywhere\nfrom autojump_match import match_consecutive\nfrom autojump_match import match_fuzzy\nfrom autojump_utils import first\nfrom autojump_utils import get_pwd\nfrom autojump_utils import get_tab_entry_info\nfrom autojump_utils import has_uppercase\nfrom autojump_utils import is_autojump_sourced\nfrom autojump_utils import is_osx\nfrom autojump_utils import is_windows\nfrom autojump_utils import last\nfrom autojump_utils import print_entry\nfrom autojump_utils import print_local\nfrom autojump_utils import print_tab_menu\nfrom autojump_utils import sanitize\nfrom autojump_utils import take\nfrom autojump_utils import unico\n\nVERSION = '22.5.3'\nFUZZY_MATCH_THRESHOLD = 0.6\nTAB_ENTRIES_COUNT = 9\nTAB_SEPARATOR = '__'\n\n\ndef set_defaults():\n    config = {}\n\n    if is_osx():\n        data_home = os.path.join(os.path.expanduser('~'), 'Library')\n    elif is_windows():\n        data_home = os.getenv('APPDATA')\n    else:\n        data_home = os.getenv(\n            'XDG_DATA_HOME',\n            os.path.join(\n                os.path.expanduser('~'),\n                '.local',\n                'share',\n            ),\n        )\n    config['data_path'] = os.path.join(data_home, 'autojump', 'autojump.txt')\n    config['backup_path'] = os.path.join(data_home, 'autojump', 'autojump.txt.bak')\n\n    return config\n\n\ndef parse_arguments():\n    parser = ArgumentParser(\n        description='Automatically jump to directory passed as an argument.',\n        epilog='Please see autojump(1) man pages for full documentation.',\n    )\n    parser.add_argument(\n        'directory', metavar='DIRECTORY', nargs='*', default='',\n        help='directory to jump to',\n    )\n    parser.add_argument(\n        '-a', '--add', metavar='DIRECTORY',\n        help='add path',\n    )\n    parser.add_argument(\n        '-i', '--increase', metavar='WEIGHT', nargs='?', type=int,\n        const=10, default=False,\n        help='increase current directory weight',\n    )\n    parser.add_argument(\n        '-d', '--decrease', metavar='WEIGHT', nargs='?', type=int,\n        const=15, default=False,\n        help='decrease current directory weight',\n    )\n    parser.add_argument(\n        '--complete', action='store_true', default=False,\n        help='used for tab completion',\n    )\n    parser.add_argument(\n        '--purge', action='store_true', default=False,\n        help='remove non-existent paths from database',\n    )\n    parser.add_argument(\n        '-s', '--stat', action='store_true', default=False,\n        help='show database entries and their key weights',\n    )\n    parser.add_argument(\n        '-v', '--version', action='version', version='%(prog)s v' +\n        VERSION, help='show version information',\n    )\n\n    return parser.parse_args()\n\n\ndef add_path(data, path, weight=10):\n    \"\"\"\n    Add a new path or increment an existing one.\n\n    os.path.realpath() is not used because it's preferable to use symlinks\n    with resulting duplicate entries in the database than a single canonical\n    path.\n    \"\"\"\n    path = unico(path).rstrip(os.sep)\n    if path == os.path.expanduser('~'):\n        return data, Entry(path, 0)\n\n    data[path] = sqrt((data.get(path, 0) ** 2) + (weight ** 2))\n\n    return data, Entry(path, data[path])\n\n\ndef decrease_path(data, path, weight=15):\n    \"\"\"Decrease or zero out a path.\"\"\"\n    path = unico(path).rstrip(os.sep)\n    data[path] = max(0, data.get(path, 0) - weight)\n    return data, Entry(path, data[path])\n\n\ndef detect_smartcase(needles):\n    \"\"\"\n    If any needles contain an uppercase letter then use case sensitive\n    searching. Otherwise use case insensitive searching.\n    \"\"\"\n    return not any(imap(has_uppercase, needles))\n\n\ndef find_matches(entries, needles, check_entries=True):\n    \"\"\"Return an iterator to matching entries.\"\"\"\n    # TODO(wting|2014-02-24): replace assertion with unit test\n    assert isinstance(needles, list), 'Needles must be a list.'\n    ignore_case = detect_smartcase(needles)\n\n    try:\n        pwd = os.getcwdu()\n    except OSError:\n        pwd = None\n\n    # using closure to prevent constantly hitting hdd\n    def is_cwd(entry):\n        return os.path.realpath(entry.path) == pwd\n\n    if check_entries:\n        path_exists = lambda entry: os.path.exists(entry.path)\n    else:\n        path_exists = lambda _: True\n\n    data = sorted(\n        entries,\n        key=attrgetter('weight', 'path'),\n        reverse=True,\n    )\n\n    return ifilter(\n        lambda entry: not is_cwd(entry) and path_exists(entry),\n        chain(\n            match_consecutive(needles, data, ignore_case),\n            match_fuzzy(needles, data, ignore_case),\n            match_anywhere(needles, data, ignore_case),\n        ),\n    )\n\n\ndef handle_tab_completion(needle, entries):\n    tab_needle, tab_index, tab_path = get_tab_entry_info(needle, TAB_SEPARATOR)\n\n    if tab_path:\n        print_local(tab_path)\n    elif tab_index:\n        get_ith_path = lambda i, iterable: last(take(i, iterable)).path\n        print_local(get_ith_path(\n            tab_index,\n            find_matches(entries, [tab_needle], check_entries=False),\n        ))\n    elif tab_needle:\n        # found partial tab completion entry\n        print_tab_menu(\n            tab_needle,\n            take(\n                TAB_ENTRIES_COUNT, find_matches(\n                    entries,\n                    [tab_needle],\n                    check_entries=False,\n                ),\n            ),\n            TAB_SEPARATOR,\n        )\n    else:\n        print_tab_menu(\n            needle,\n            take(\n                TAB_ENTRIES_COUNT, find_matches(\n                    entries,\n                    [needle],\n                    check_entries=False,\n                ),\n            ),\n            TAB_SEPARATOR,\n        )\n\n\ndef purge_missing_paths(entries):\n    \"\"\"Remove non-existent paths from a list of entries.\"\"\"\n    exists = lambda entry: os.path.exists(entry.path)\n    return ifilter(exists, entries)\n\n\ndef print_stats(data, data_path):\n    for path, weight in sorted(data.items(), key=itemgetter(1)):\n        print_entry(Entry(path, weight))\n\n    print('________________________________________\\n')\n    print('%d:\\t total weight' % sum(data.values()))\n    print('%d:\\t number of entries' % len(data))\n\n    try:\n        print_local(\n            '%.2f:\\t current directory weight' % data.get(os.getcwdu(), 0),\n        )\n    except OSError:\n        # current directory no longer exists\n        pass\n\n    print('\\ndata:\\t %s' % data_path)\n\n\ndef main(args):  # noqa\n    if not is_autojump_sourced() and not is_windows():\n        print(\"Please source the correct autojump file in your shell's\")\n        print('startup file. For more information, please reinstall autojump')\n        print('and read the post installation instructions.')\n        return 1\n\n    config = set_defaults()\n\n    # all arguments are mutually exclusive\n    if args.add:\n        save(config, first(add_path(load(config), args.add)))\n    elif args.complete:\n        handle_tab_completion(\n            needle=first(chain(sanitize(args.directory), [''])),\n            entries=entriefy(load(config)),\n        )\n    elif args.decrease:\n        data, entry = decrease_path(load(config), get_pwd(), args.decrease)\n        save(config, data)\n        print_entry(entry)\n    elif args.increase:\n        data, entry = add_path(load(config), get_pwd(), args.increase)\n        save(config, data)\n        print_entry(entry)\n    elif args.purge:\n        old_data = load(config)\n        new_data = dictify(purge_missing_paths(entriefy(old_data)))\n        save(config, new_data)\n        print('Purged %d entries.' % (len(old_data) - len(new_data)))\n    elif args.stat:\n        print_stats(load(config), config['data_path'])\n    elif not args.directory:\n        # Return best match.\n        entries = entriefy(load(config))\n        print_local(first(chain(\n            imap(attrgetter('path'), find_matches(entries, [''])),\n            # always return a path to calling shell functions\n            ['.'],\n        )))\n    else:\n        entries = entriefy(load(config))\n        needles = sanitize(args.directory)\n        tab_needle, tab_index, tab_path = \\\n            get_tab_entry_info(first(needles), TAB_SEPARATOR)\n\n        # Handle `j foo__`, assuming first index.\n        if not tab_path and not tab_index \\\n                and tab_needle and needles[0] == tab_needle + TAB_SEPARATOR:\n            tab_index = 1\n\n        if tab_path:\n            print_local(tab_path)\n        elif tab_index:\n            get_ith_path = lambda i, iterable: last(take(i, iterable)).path\n            print_local(\n                get_ith_path(\n                    tab_index,\n                    find_matches(entries, [tab_needle]),\n                ),\n            )\n        else:\n            print_local(first(chain(\n                imap(attrgetter('path'), find_matches(entries, needles)),\n                # always return a path to calling shell functions\n                ['.'],\n            )))\n\n    return 0\n\n\nif __name__ == '__main__':\n    sys.exit(main(parse_arguments()))\n"
  },
  {
    "path": "bin/autojump.bash",
    "content": "export AUTOJUMP_SOURCED=1\n\n# set user installation paths\nif [[ -d ~/.autojump/ ]]; then\n    export PATH=~/.autojump/bin:\"${PATH}\"\nfi\n\n\n# set error file location\nif [[ \"$(uname)\" == \"Darwin\" ]]; then\n    export AUTOJUMP_ERROR_PATH=~/Library/autojump/errors.log\nelif [[ -n \"${XDG_DATA_HOME}\" ]]; then\n    export AUTOJUMP_ERROR_PATH=\"${XDG_DATA_HOME}/autojump/errors.log\"\nelse\n    export AUTOJUMP_ERROR_PATH=~/.local/share/autojump/errors.log\nfi\n\nif [[ ! -d \"$(dirname ${AUTOJUMP_ERROR_PATH})\" ]]; then\n    mkdir -p \"$(dirname ${AUTOJUMP_ERROR_PATH})\"\nfi\n\n\n# enable tab completion\n_autojump() {\n        local cur\n        cur=${COMP_WORDS[*]:1}\n        comps=$(autojump --complete $cur)\n        while read i; do\n            COMPREPLY=(\"${COMPREPLY[@]}\" \"${i}\")\n        done <<EOF\n        $comps\nEOF\n}\ncomplete -F _autojump j\n\n\n# change pwd hook\nautojump_add_to_database() {\n    if [[ -f \"${AUTOJUMP_ERROR_PATH}\" ]]; then\n        (autojump --add \"$(pwd)\" >/dev/null 2>>${AUTOJUMP_ERROR_PATH} &) &>/dev/null\n    else\n        (autojump --add \"$(pwd)\" >/dev/null &) &>/dev/null\n    fi\n}\n\ncase $PROMPT_COMMAND in\n    *autojump*)\n        ;;\n    *)\n        PROMPT_COMMAND=\"${PROMPT_COMMAND:+$(echo \"${PROMPT_COMMAND}\" | awk '{gsub(/; *$/,\"\")}1') ; }autojump_add_to_database\"\n        ;;\nesac\n\n\n# default autojump command\nj() {\n    if [[ ${1} == -* ]] && [[ ${1} != \"--\" ]]; then\n        autojump ${@}\n        return\n    fi\n\n    output=\"$(autojump ${@})\"\n    if [[ -d \"${output}\" ]]; then\n        if [ -t 1 ]; then  # if stdout is a terminal, use colors\n                echo -e \"\\\\033[31m${output}\\\\033[0m\"\n        else\n                echo -e \"${output}\"\n        fi\n        cd \"${output}\"\n    else\n        echo \"autojump: directory '${@}' not found\"\n        echo \"\\n${output}\\n\"\n        echo \"Try \\`autojump --help\\` for more information.\"\n        false\n    fi\n}\n\n\n# jump to child directory (subdirectory of current path)\njc() {\n    if [[ ${1} == -* ]] && [[ ${1} != \"--\" ]]; then\n        autojump ${@}\n        return\n    else\n        j $(pwd) ${@}\n    fi\n}\n\n\n# open autojump results in file browser\njo() {\n    if [[ ${1} == -* ]] && [[ ${1} != \"--\" ]]; then\n        autojump ${@}\n        return\n    fi\n\n    output=\"$(autojump ${@})\"\n    if [[ -d \"${output}\" ]]; then\n        case ${OSTYPE} in\n            linux*)\n                xdg-open \"${output}\"\n                ;;\n            darwin*)\n                open \"${output}\"\n                ;;\n            cygwin)\n                cygstart \"\" $(cygpath -w -a ${output})\n                ;;\n            *)\n                echo \"Unknown operating system: ${OSTYPE}.\" 1>&2\n                ;;\n        esac\n    else\n        echo \"autojump: directory '${@}' not found\"\n        echo \"\\n${output}\\n\"\n        echo \"Try \\`autojump --help\\` for more information.\"\n        false\n    fi\n}\n\n\n# open autojump results (child directory) in file browser\njco() {\n    if [[ ${1} == -* ]] && [[ ${1} != \"--\" ]]; then\n        autojump ${@}\n        return\n    else\n        jo $(pwd) ${@}\n    fi\n}\n"
  },
  {
    "path": "bin/autojump.bat",
    "content": "@echo off\r\npython \"%~dp0\\autojump\" %*\r\n"
  },
  {
    "path": "bin/autojump.fish",
    "content": "set -gx AUTOJUMP_SOURCED 1\n\n# set user installation path\nif test -d ~/.autojump\n    set -x PATH ~/.autojump/bin $PATH\nend\n\n# Set ostype, if not set\nif not set -q OSTYPE\n    set -gx OSTYPE (bash -c 'echo ${OSTYPE}')\nend\n\n\n# enable tab completion\ncomplete -x -c j -a '(autojump --complete (commandline -t))'\n\n\n# set error file location\nif test (uname) = \"Darwin\"\n    set -gx AUTOJUMP_ERROR_PATH ~/Library/autojump/errors.log\nelse if test -d \"$XDG_DATA_HOME\"\n    set -gx AUTOJUMP_ERROR_PATH $XDG_DATA_HOME/autojump/errors.log\nelse\n    set -gx AUTOJUMP_ERROR_PATH ~/.local/share/autojump/errors.log\nend\n\nif test ! -d (dirname $AUTOJUMP_ERROR_PATH)\n    mkdir -p (dirname $AUTOJUMP_ERROR_PATH)\nend\n\n\n# change pwd hook\nfunction __aj_add --on-variable PWD\n    status --is-command-substitution; and return\n    autojump --add (pwd) >/dev/null 2>>$AUTOJUMP_ERROR_PATH &\nend\n\n\n# misc helper functions\nfunction __aj_err\n    # TODO(ting|#247): set error file location\n    echo -e $argv 1>&2; false\nend\n\n# default autojump command\nfunction j\n    switch \"$argv\"\n        case '-*' '--*'\n            autojump $argv\n        case '*'\n            set -l output (autojump $argv)\n            # Check for . and attempt a regular cd\n            if [ $output = \".\" ]\n                cd $argv\n            else\n                if test -d \"$output\"\n                    set_color red\n                    echo $output\n                    set_color normal\n                    cd $output\n                else\n                    __aj_err \"autojump: directory '\"$argv\"' not found\"\n                    __aj_err \"\\n$output\\n\"\n                    __aj_err \"Try `autojump --help` for more information.\"\n                end\n            end\n    end\nend\n\n\n# jump to child directory (subdirectory of current path)\nfunction jc\n    switch \"$argv\"\n        case '-*'\n            j $argv\n        case '*'\n            j (pwd) $argv\n    end\nend\n\n\n# open autojump results in file browser\nfunction jo\n    set -l output (autojump $argv)\n    if test -d \"$output\"\n        switch $OSTYPE\n            case 'linux*'\n                xdg-open (autojump $argv)\n            case 'darwin*'\n                open (autojump $argv)\n            case cygwin\n                cygstart \"\" (cygpath -w -a (pwd))\n            case '*'\n                __aj_err \"Unknown operating system: \\\"$OSTYPE\\\"\"\n        end\n    else\n        __aj_err \"autojump: directory '\"$argv\"' not found\"\n        __aj_err \"\\n$output\\n\"\n        __aj_err \"Try `autojump --help` for more information.\"\n    end\nend\n\n\n# open autojump results (child directory) in file browser\nfunction jco\n    switch \"$argv\"\n        case '-*'\n            j $argv\n        case '*'\n            jo (pwd) $argv\n    end\nend\n"
  },
  {
    "path": "bin/autojump.lua",
    "content": "local AUTOJUMP_DIR = debug.getinfo(1, \"S\").source:match[[^@?(.*[\\/])[^\\/]-$]] .. \"..\\\\AutoJump\"\nlocal AUTOJUMP_BIN_DIR = AUTOJUMP_DIR .. \"\\\\bin\"\nlocal AUTOJUMP_BIN = (AUTOJUMP_BIN_DIR or clink.get_env(\"LOCALAPPDATA\") .. \"\\\\autojump\\\\bin\") .. \"\\\\autojump\"\n\nfunction autojump_add_to_database()\n  os.execute(\"python \" .. \"\\\"\" .. AUTOJUMP_BIN .. \"\\\"\" .. \" --add \" .. \"\\\"\" .. clink.get_cwd() .. \"\\\"\" .. \" 2> \" .. clink.get_env(\"TEMP\") .. \"\\\\autojump_error.txt\")\nend\n\nclink.prompt.register_filter(autojump_add_to_database, 99)\n\nfunction autojump_completion(word)\n  for line in io.popen(\"python \" .. \"\\\"\" .. AUTOJUMP_BIN .. \"\\\"\" ..  \" --complete \" .. word):lines() do\n    clink.add_match(line)\n  end\n  return {}\nend\n\nlocal autojump_parser = clink.arg.new_parser()\nautojump_parser:set_arguments({ autojump_completion })\n\nclink.arg.register_parser(\"j\", autojump_parser)\n"
  },
  {
    "path": "bin/autojump.sh",
    "content": "# the login $SHELL isn't always the one used\n# NOTE: problems might occur if /bin/sh is symlinked to /bin/bash\nif [ -n \"${BASH}\" ]; then\n    shell=\"bash\"\nelif [ -n \"${ZSH_NAME}\" ]; then\n    shell=\"zsh\"\nelif [ -n \"${__fish_datadir}\" ]; then\n    shell=\"fish\"\nelif [ -n \"${version}\" ]; then\n    shell=\"tcsh\"\nelse\n    shell=$(echo ${SHELL} | awk -F/ '{ print $NF }')\nfi\n\n# prevent circular loop for sh shells\nif [ \"${shell}\" = \"sh\" ]; then\n    return 0\n\n# check local install\nelif [ -s ~/.autojump/share/autojump/autojump.${shell} ]; then\n    source ~/.autojump/share/autojump/autojump.${shell}\n\n# check global install\nelif [ -s /usr/local/share/autojump/autojump.${shell} ]; then\n    source /usr/local/share/autojump/autojump.${shell}\nfi\n"
  },
  {
    "path": "bin/autojump.tcsh",
    "content": "# set user installation paths\nif (-d ~/.autojump/bin) then\n    set path = (~/.autojump/bin path)\nendif\n\n# prepend autojump to cwdcmd (run after every change of working directory)\nif (`alias cwdcmd` !~ *autojump*) then\n    alias cwdcmd 'autojump --add $cwd >/dev/null;' `alias cwdcmd`\nendif\n\n#default autojump command\nalias j 'cd `autojump -- \\!:1`'\n"
  },
  {
    "path": "bin/autojump.zsh",
    "content": "export AUTOJUMP_SOURCED=1\n\n# set user installation paths\nif [[ -d ~/.autojump/bin ]]; then\n    path=(~/.autojump/bin ${path})\nfi\nif [[ -d ~/.autojump/functions ]]; then\n    fpath=(~/.autojump/functions ${fpath})\nfi\n\n\n# set homebrew installation paths\nif command -v brew &>/dev/null; then\n  local brew_prefix=${BREW_PREFIX:-$(brew --prefix)}\n  if [[ -d \"${brew_prefix}/share/zsh/site-functions\" ]]; then\n    fpath=(\"${brew_prefix}/share/zsh/site-functions\" ${fpath})\n  fi\nfi\n\n\n# set error file location\nif [[ \"$(uname)\" == \"Darwin\" ]]; then\n    export AUTOJUMP_ERROR_PATH=~/Library/autojump/errors.log\nelif [[ -n \"${XDG_DATA_HOME}\" ]]; then\n    export AUTOJUMP_ERROR_PATH=\"${XDG_DATA_HOME}/autojump/errors.log\"\nelse\n    export AUTOJUMP_ERROR_PATH=~/.local/share/autojump/errors.log\nfi\n\nif [[ ! -d ${AUTOJUMP_ERROR_PATH:h} ]]; then\n    mkdir -p ${AUTOJUMP_ERROR_PATH:h}\nfi\n\n\n# change pwd hook\nautojump_chpwd() {\n    if [[ -f \"${AUTOJUMP_ERROR_PATH}\" ]]; then\n        autojump --add \"$(pwd)\" >/dev/null 2>>${AUTOJUMP_ERROR_PATH} &!\n    else\n        autojump --add \"$(pwd)\" >/dev/null &!\n    fi\n}\n\ntypeset -gaU chpwd_functions\nchpwd_functions+=autojump_chpwd\n\n\n# default autojump command\nj() {\n    if [[ ${1} == -* ]] && [[ ${1} != \"--\" ]]; then\n        autojump ${@}\n        return\n    fi\n\n    setopt localoptions noautonamedirs\n    local output=\"$(autojump ${@})\"\n    if [[ -d \"${output}\" ]]; then\n        if [ -t 1 ]; then  # if stdout is a terminal, use colors\n                echo -e \"\\\\033[31m${output}\\\\033[0m\"\n        else\n                echo -e \"${output}\"\n        fi\n        cd \"${output}\"\n    else\n        echo \"autojump: directory '${@}' not found\"\n        echo \"\\n${output}\\n\"\n        echo \"Try \\`autojump --help\\` for more information.\"\n        false\n    fi\n}\n\n\n# jump to child directory (subdirectory of current path)\njc() {\n    if [[ ${1} == -* ]] && [[ ${1} != \"--\" ]]; then\n        autojump ${@}\n        return\n    else\n        j $(pwd) ${@}\n    fi\n}\n\n\n# open autojump results in file browser\njo() {\n    if [[ ${1} == -* ]] && [[ ${1} != \"--\" ]]; then\n        autojump ${@}\n        return\n    fi\n\n    setopt localoptions noautonamedirs\n    local output=\"$(autojump ${@})\"\n    if [[ -d \"${output}\" ]]; then\n        case ${OSTYPE} in\n            linux*)\n                xdg-open \"${output}\"\n                ;;\n            darwin*)\n                open \"${output}\"\n                ;;\n            cygwin)\n                cygstart \"\" $(cygpath -w -a ${output})\n                ;;\n            *)\n                echo \"Unknown operating system: ${OSTYPE}\" 1>&2\n                ;;\n        esac\n    else\n        echo \"autojump: directory '${@}' not found\"\n        echo \"\\n${output}\\n\"\n        echo \"Try \\`autojump --help\\` for more information.\"\n        false\n    fi\n}\n\n\n# open autojump results (child directory) in file browser\njco() {\n    if [[ ${1} == -* ]] && [[ ${1} != \"--\" ]]; then\n        autojump ${@}\n        return\n    else\n        jo $(pwd) ${@}\n    fi\n}\n"
  },
  {
    "path": "bin/autojump_argparse.py",
    "content": "# -*- coding: utf-8 -*-\n# Author: Steven J. Bethard <steven.bethard@gmail.com>.\n# flake8: noqa\n\"\"\"Command-line parsing library\n\nThis module is an optparse-inspired command-line parsing library that:\n\n    - handles both optional and positional arguments\n    - produces highly informative usage messages\n    - supports parsers that dispatch to sub-parsers\n\nThe following is a simple usage example that sums integers from the\ncommand-line and writes the result to a file::\n\n    parser = argparse.ArgumentParser(\n        description='sum the integers at the command line')\n    parser.add_argument(\n        'integers', metavar='int', nargs='+', type=int,\n        help='an integer to be summed')\n    parser.add_argument(\n        '--log', default=sys.stdout, type=argparse.FileType('w'),\n        help='the file where the sum should be written')\n    args = parser.parse_args()\n    args.log.write('%s' % sum(args.integers))\n    args.log.close()\n\nThe module contains the following public classes:\n\n    - ArgumentParser -- The main entry point for command-line parsing. As the\n        example above shows, the add_argument() method is used to populate\n        the parser with actions for optional and positional arguments. Then\n        the parse_args() method is invoked to convert the args at the\n        command-line into an object with attributes.\n\n    - ArgumentError -- The exception raised by ArgumentParser objects when\n        there are errors with the parser's actions. Errors raised while\n        parsing the command-line are caught by ArgumentParser and emitted\n        as command-line messages.\n\n    - FileType -- A factory for defining types of files to be created. As the\n        example above shows, instances of FileType are typically passed as\n        the type= argument of add_argument() calls.\n\n    - Action -- The base class for parser actions. Typically actions are\n        selected by passing strings like 'store_true' or 'append_const' to\n        the action= argument of add_argument(). However, for greater\n        customization of ArgumentParser actions, subclasses of Action may\n        be defined and passed as the action= argument.\n\n    - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,\n        ArgumentDefaultsHelpFormatter -- Formatter classes which\n        may be passed as the formatter_class= argument to the\n        ArgumentParser constructor. HelpFormatter is the default,\n        RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser\n        not to change the formatting for help text, and\n        ArgumentDefaultsHelpFormatter adds information about argument defaults\n        to the help.\n\nAll other classes in this module are considered implementation details.\n(Also note that HelpFormatter and RawDescriptionHelpFormatter are only\nconsidered public as object names -- the API of the formatter objects is\nstill considered an implementation detail.)\n\"\"\"\n\n__version__ = '1.2.1'\n__all__ = [\n    'ArgumentParser',\n    'ArgumentError',\n    'ArgumentTypeError',\n    'FileType',\n    'HelpFormatter',\n    'ArgumentDefaultsHelpFormatter',\n    'RawDescriptionHelpFormatter',\n    'RawTextHelpFormatter',\n    'Namespace',\n    'Action',\n    'ONE_OR_MORE',\n    'OPTIONAL',\n    'PARSER',\n    'REMAINDER',\n    'SUPPRESS',\n    'ZERO_OR_MORE',\n]\n\n\nimport copy as _copy\nimport os as _os\nimport re as _re\nimport sys as _sys\nimport textwrap as _textwrap\n\nfrom gettext import gettext as _\n\ntry:\n    set\nexcept NameError:\n    # for python < 2.4 compatibility (sets module is there since 2.3):\n    from sets import Set as set\n\ntry:\n    basestring\nexcept NameError:\n    basestring = str\n\ntry:\n    sorted\nexcept NameError:\n    # for python < 2.4 compatibility:\n    def sorted(iterable, reverse=False):\n        result = sorted(iterable)\n        if reverse:\n            result.reverse()\n        return result\n\n\ndef _callable(obj):\n    return hasattr(obj, '__call__') or hasattr(obj, '__bases__')\n\n\nSUPPRESS = '==SUPPRESS=='\n\nOPTIONAL = '?'\nZERO_OR_MORE = '*'\nONE_OR_MORE = '+'\nPARSER = 'A...'\nREMAINDER = '...'\n_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'\n\n# =============================\n# Utility functions and classes\n# =============================\n\n\nclass _AttributeHolder(object):\n\n    \"\"\"Abstract base class that provides __repr__.\n\n    The __repr__ method returns a string in the format::\n        ClassName(attr=name, attr=name, ...)\n    The attributes are determined either by a class-level attribute,\n    '_kwarg_names', or by inspecting the instance __dict__.\n    \"\"\"\n\n    def __repr__(self):\n        type_name = type(self).__name__\n        arg_strings = []\n        for arg in self._get_args():\n            arg_strings.append(repr(arg))\n        for name, value in self._get_kwargs():\n            arg_strings.append('%s=%r' % (name, value))\n        return '%s(%s)' % (type_name, ', '.join(arg_strings))\n\n    def _get_kwargs(self):\n        return sorted(self.__dict__.items())\n\n    def _get_args(self):\n        return []\n\n\ndef _ensure_value(namespace, name, value):\n    if getattr(namespace, name, None) is None:\n        setattr(namespace, name, value)\n    return getattr(namespace, name)\n\n\n# ===============\n# Formatting Help\n# ===============\n\nclass HelpFormatter(object):\n\n    \"\"\"Formatter for generating usage messages and argument help strings.\n\n    Only the name of this class is considered a public API. All the methods\n    provided by the class are considered an implementation detail.\n    \"\"\"\n\n    def __init__(\n        self,\n        prog,\n        indent_increment=2,\n        max_help_position=24,\n        width=None,\n    ):\n\n        # default setting for width\n        if width is None:\n            try:\n                width = int(_os.environ['COLUMNS'])\n            except (KeyError, ValueError):\n                width = 80\n            width -= 2\n\n        self._prog = prog\n        self._indent_increment = indent_increment\n        self._max_help_position = max_help_position\n        self._width = width\n\n        self._current_indent = 0\n        self._level = 0\n        self._action_max_length = 0\n\n        self._root_section = self._Section(self, None)\n        self._current_section = self._root_section\n\n        self._whitespace_matcher = _re.compile(r'\\s+')\n        self._long_break_matcher = _re.compile(r'\\n\\n\\n+')\n\n    # ===============================\n    # Section and indentation methods\n    # ===============================\n    def _indent(self):\n        self._current_indent += self._indent_increment\n        self._level += 1\n\n    def _dedent(self):\n        self._current_indent -= self._indent_increment\n        assert self._current_indent >= 0, 'Indent decreased below 0.'\n        self._level -= 1\n\n    class _Section(object):\n\n        def __init__(self, formatter, parent, heading=None):\n            self.formatter = formatter\n            self.parent = parent\n            self.heading = heading\n            self.items = []\n\n        def format_help(self):\n            # format the indented section\n            if self.parent is not None:\n                self.formatter._indent()\n            join = self.formatter._join_parts\n            for func, args in self.items:\n                func(*args)\n            item_help = join([func(*args) for func, args in self.items])\n            if self.parent is not None:\n                self.formatter._dedent()\n\n            # return nothing if the section was empty\n            if not item_help:\n                return ''\n\n            # add the heading if the section was non-empty\n            if self.heading is not SUPPRESS and self.heading is not None:\n                current_indent = self.formatter._current_indent\n                heading = '%*s%s:\\n' % (current_indent, '', self.heading)\n            else:\n                heading = ''\n\n            # join the section-initial newline, the heading and the help\n            return join(['\\n', heading, item_help, '\\n'])\n\n    def _add_item(self, func, args):\n        self._current_section.items.append((func, args))\n\n    # ========================\n    # Message building methods\n    # ========================\n    def start_section(self, heading):\n        self._indent()\n        section = self._Section(self, self._current_section, heading)\n        self._add_item(section.format_help, [])\n        self._current_section = section\n\n    def end_section(self):\n        self._current_section = self._current_section.parent\n        self._dedent()\n\n    def add_text(self, text):\n        if text is not SUPPRESS and text is not None:\n            self._add_item(self._format_text, [text])\n\n    def add_usage(self, usage, actions, groups, prefix=None):\n        if usage is not SUPPRESS:\n            args = usage, actions, groups, prefix\n            self._add_item(self._format_usage, args)\n\n    def add_argument(self, action):\n        if action.help is not SUPPRESS:\n\n            # find all invocations\n            get_invocation = self._format_action_invocation\n            invocations = [get_invocation(action)]\n            for subaction in self._iter_indented_subactions(action):\n                invocations.append(get_invocation(subaction))\n\n            # update the maximum item length\n            invocation_length = max([len(s) for s in invocations])\n            action_length = invocation_length + self._current_indent\n            self._action_max_length = max(\n                self._action_max_length,\n                action_length,\n            )\n\n            # add the item to the list\n            self._add_item(self._format_action, [action])\n\n    def add_arguments(self, actions):\n        for action in actions:\n            self.add_argument(action)\n\n    # =======================\n    # Help-formatting methods\n    # =======================\n    def format_help(self):\n        help = self._root_section.format_help()\n        if help:\n            help = self._long_break_matcher.sub('\\n\\n', help)\n            help = help.strip('\\n') + '\\n'\n        return help\n\n    def _join_parts(self, part_strings):\n        return ''.join([\n            part\n            for part in part_strings\n            if part and part is not SUPPRESS\n        ])\n\n    def _format_usage(self, usage, actions, groups, prefix):\n        if prefix is None:\n            prefix = _('usage: ')\n\n        # if usage is specified, use that\n        if usage is not None:\n            usage = usage % dict(prog=self._prog)\n\n        # if no optionals or positionals are available, usage is just prog\n        elif usage is None and not actions:\n            usage = '%(prog)s' % dict(prog=self._prog)\n\n        # if optionals and positionals are available, calculate usage\n        elif usage is None:\n            prog = '%(prog)s' % dict(prog=self._prog)\n\n            # split optionals from positionals\n            optionals = []\n            positionals = []\n            for action in actions:\n                if action.option_strings:\n                    optionals.append(action)\n                else:\n                    positionals.append(action)\n\n            # build full usage string\n            format = self._format_actions_usage\n            action_usage = format(optionals + positionals, groups)\n            usage = ' '.join([s for s in [prog, action_usage] if s])\n\n            # wrap the usage parts if it's too long\n            text_width = self._width - self._current_indent\n            if len(prefix) + len(usage) > text_width:\n\n                # break usage into wrappable parts\n                part_regexp = r'\\(.*?\\)+|\\[.*?\\]+|\\S+'\n                opt_usage = format(optionals, groups)\n                pos_usage = format(positionals, groups)\n                opt_parts = _re.findall(part_regexp, opt_usage)\n                pos_parts = _re.findall(part_regexp, pos_usage)\n                assert ' '.join(opt_parts) == opt_usage\n                assert ' '.join(pos_parts) == pos_usage\n\n                # helper for wrapping lines\n                def get_lines(parts, indent, prefix=None):\n                    lines = []\n                    line = []\n                    if prefix is not None:\n                        line_len = len(prefix) - 1\n                    else:\n                        line_len = len(indent) - 1\n                    for part in parts:\n                        if line_len + 1 + len(part) > text_width:\n                            lines.append(indent + ' '.join(line))\n                            line = []\n                            line_len = len(indent) - 1\n                        line.append(part)\n                        line_len += len(part) + 1\n                    if line:\n                        lines.append(indent + ' '.join(line))\n                    if prefix is not None:\n                        lines[0] = lines[0][len(indent):]\n                    return lines\n\n                # if prog is short, follow it with optionals or positionals\n                if len(prefix) + len(prog) <= 0.75 * text_width:\n                    indent = ' ' * (len(prefix) + len(prog) + 1)\n                    if opt_parts:\n                        lines = get_lines([prog] + opt_parts, indent, prefix)\n                        lines.extend(get_lines(pos_parts, indent))\n                    elif pos_parts:\n                        lines = get_lines([prog] + pos_parts, indent, prefix)\n                    else:\n                        lines = [prog]\n\n                # if prog is long, put it on its own line\n                else:\n                    indent = ' ' * len(prefix)\n                    parts = opt_parts + pos_parts\n                    lines = get_lines(parts, indent)\n                    if len(lines) > 1:\n                        lines = []\n                        lines.extend(get_lines(opt_parts, indent))\n                        lines.extend(get_lines(pos_parts, indent))\n                    lines = [prog] + lines\n\n                # join lines into usage\n                usage = '\\n'.join(lines)\n\n        # prefix with 'usage:'\n        return '%s%s\\n\\n' % (prefix, usage)\n\n    def _format_actions_usage(self, actions, groups):\n        # find group indices and identify actions in groups\n        group_actions = set()\n        inserts = {}\n        for group in groups:\n            try:\n                start = actions.index(group._group_actions[0])\n            except ValueError:\n                continue\n            else:\n                end = start + len(group._group_actions)\n                if actions[start:end] == group._group_actions:\n                    for action in group._group_actions:\n                        group_actions.add(action)\n                    if not group.required:\n                        if start in inserts:\n                            inserts[start] += ' ['\n                        else:\n                            inserts[start] = '['\n                        inserts[end] = ']'\n                    else:\n                        if start in inserts:\n                            inserts[start] += ' ('\n                        else:\n                            inserts[start] = '('\n                        inserts[end] = ')'\n                    for i in range(start + 1, end):\n                        inserts[i] = '|'\n\n        # collect all actions format strings\n        parts = []\n        for i, action in enumerate(actions):\n\n            # suppressed arguments are marked with None\n            # remove | separators for suppressed arguments\n            if action.help is SUPPRESS:\n                parts.append(None)\n                if inserts.get(i) == '|':\n                    inserts.pop(i)\n                elif inserts.get(i + 1) == '|':\n                    inserts.pop(i + 1)\n\n            # produce all arg strings\n            elif not action.option_strings:\n                part = self._format_args(action, action.dest)\n\n                # if it's in a group, strip the outer []\n                if action in group_actions:\n                    if part[0] == '[' and part[-1] == ']':\n                        part = part[1:-1]\n\n                # add the action string to the list\n                parts.append(part)\n\n            # produce the first way to invoke the option in brackets\n            else:\n                option_string = action.option_strings[0]\n\n                # if the Optional doesn't take a value, format is:\n                #    -s or --long\n                if action.nargs == 0:\n                    part = '%s' % option_string\n\n                # if the Optional takes a value, format is:\n                #    -s ARGS or --long ARGS\n                else:\n                    default = action.dest.upper()\n                    args_string = self._format_args(action, default)\n                    part = '%s %s' % (option_string, args_string)\n\n                # make it look optional if it's not required or in a group\n                if not action.required and action not in group_actions:\n                    part = '[%s]' % part\n\n                # add the action string to the list\n                parts.append(part)\n\n        # insert things at the necessary indices\n        for i in sorted(inserts, reverse=True):\n            parts[i:i] = [inserts[i]]\n\n        # join all the action items with spaces\n        text = ' '.join([item for item in parts if item is not None])\n\n        # clean up separators for mutually exclusive groups\n        open = r'[\\[(]'\n        close = r'[\\])]'\n        text = _re.sub(r'(%s) ' % open, r'\\1', text)\n        text = _re.sub(r' (%s)' % close, r'\\1', text)\n        text = _re.sub(r'%s *%s' % (open, close), r'', text)\n        text = _re.sub(r'\\(([^|]*)\\)', r'\\1', text)\n        text = text.strip()\n\n        # return the text\n        return text\n\n    def _format_text(self, text):\n        if '%(prog)' in text:\n            text = text % dict(prog=self._prog)\n        text_width = self._width - self._current_indent\n        indent = ' ' * self._current_indent\n        return self._fill_text(text, text_width, indent) + '\\n\\n'\n\n    def _format_action(self, action):\n        # determine the required width and the entry label\n        help_position = min(\n            self._action_max_length + 2,\n            self._max_help_position,\n        )\n        help_width = self._width - help_position\n        action_width = help_position - self._current_indent - 2\n        action_header = self._format_action_invocation(action)\n\n        # ho nelp; start on same line and add a final newline\n        if not action.help:\n            tup = self._current_indent, '', action_header\n            action_header = '%*s%s\\n' % tup\n\n        # short action name; start on the same line and pad two spaces\n        elif len(action_header) <= action_width:\n            tup = self._current_indent, '', action_width, action_header\n            action_header = '%*s%-*s  ' % tup\n            indent_first = 0\n\n        # long action name; start on the next line\n        else:\n            tup = self._current_indent, '', action_header\n            action_header = '%*s%s\\n' % tup\n            indent_first = help_position\n\n        # collect the pieces of the action help\n        parts = [action_header]\n\n        # if there was help for the action, add lines of help text\n        if action.help:\n            help_text = self._expand_help(action)\n            help_lines = self._split_lines(help_text, help_width)\n            parts.append('%*s%s\\n' % (indent_first, '', help_lines[0]))\n            for line in help_lines[1:]:\n                parts.append('%*s%s\\n' % (help_position, '', line))\n\n        # or add a newline if the description doesn't end with one\n        elif not action_header.endswith('\\n'):\n            parts.append('\\n')\n\n        # if there are any sub-actions, add their help as well\n        for subaction in self._iter_indented_subactions(action):\n            parts.append(self._format_action(subaction))\n\n        # return a single string\n        return self._join_parts(parts)\n\n    def _format_action_invocation(self, action):\n        if not action.option_strings:\n            metavar, = self._metavar_formatter(action, action.dest)(1)\n            return metavar\n\n        else:\n            parts = []\n\n            # if the Optional doesn't take a value, format is:\n            #    -s, --long\n            if action.nargs == 0:\n                parts.extend(action.option_strings)\n\n            # if the Optional takes a value, format is:\n            #    -s ARGS, --long ARGS\n            else:\n                default = action.dest.upper()\n                args_string = self._format_args(action, default)\n                for option_string in action.option_strings:\n                    parts.append('%s %s' % (option_string, args_string))\n\n            return ', '.join(parts)\n\n    def _metavar_formatter(self, action, default_metavar):\n        if action.metavar is not None:\n            result = action.metavar\n        elif action.choices is not None:\n            choice_strs = [str(choice) for choice in action.choices]\n            result = '{%s}' % ','.join(choice_strs)\n        else:\n            result = default_metavar\n\n        def format(tuple_size):\n            if isinstance(result, tuple):\n                return result\n            else:\n                return (result, ) * tuple_size\n        return format\n\n    def _format_args(self, action, default_metavar):\n        get_metavar = self._metavar_formatter(action, default_metavar)\n        if action.nargs is None:\n            result = '%s' % get_metavar(1)\n        elif action.nargs == OPTIONAL:\n            result = '[%s]' % get_metavar(1)\n        elif action.nargs == ZERO_OR_MORE:\n            result = '[%s [%s ...]]' % get_metavar(2)\n        elif action.nargs == ONE_OR_MORE:\n            result = '%s [%s ...]' % get_metavar(2)\n        elif action.nargs == REMAINDER:\n            result = '...'\n        elif action.nargs == PARSER:\n            result = '%s ...' % get_metavar(1)\n        else:\n            formats = ['%s' for _ in range(action.nargs)]\n            result = ' '.join(formats) % get_metavar(action.nargs)\n        return result\n\n    def _expand_help(self, action):\n        params = dict(vars(action), prog=self._prog)\n        for name in list(params):\n            if params[name] is SUPPRESS:\n                del params[name]\n        for name in list(params):\n            if hasattr(params[name], '__name__'):\n                params[name] = params[name].__name__\n        if params.get('choices') is not None:\n            choices_str = ', '.join([str(c) for c in params['choices']])\n            params['choices'] = choices_str\n        return self._get_help_string(action) % params\n\n    def _iter_indented_subactions(self, action):\n        try:\n            get_subactions = action._get_subactions\n        except AttributeError:\n            pass\n        else:\n            self._indent()\n            for subaction in get_subactions():\n                yield subaction\n            self._dedent()\n\n    def _split_lines(self, text, width):\n        text = self._whitespace_matcher.sub(' ', text).strip()\n        return _textwrap.wrap(text, width)\n\n    def _fill_text(self, text, width, indent):\n        text = self._whitespace_matcher.sub(' ', text).strip()\n        return _textwrap.fill(\n            text, width, initial_indent=indent,\n            subsequent_indent=indent,\n        )\n\n    def _get_help_string(self, action):\n        return action.help\n\n\nclass RawDescriptionHelpFormatter(HelpFormatter):\n\n    \"\"\"Help message formatter which retains any formatting in descriptions.\n\n    Only the name of this class is considered a public API. All the methods\n    provided by the class are considered an implementation detail.\n    \"\"\"\n\n    def _fill_text(self, text, width, indent):\n        return ''.join([indent + line for line in text.splitlines(True)])\n\n\nclass RawTextHelpFormatter(RawDescriptionHelpFormatter):\n\n    \"\"\"Help message formatter which retains formatting of all help text.\n\n    Only the name of this class is considered a public API. All the methods\n    provided by the class are considered an implementation detail.\n    \"\"\"\n\n    def _split_lines(self, text, width):\n        return text.splitlines()\n\n\nclass ArgumentDefaultsHelpFormatter(HelpFormatter):\n\n    \"\"\"Help message formatter which adds default values to argument help.\n\n    Only the name of this class is considered a public API. All the methods\n    provided by the class are considered an implementation detail.\n    \"\"\"\n\n    def _get_help_string(self, action):\n        help = action.help\n        if '%(default)' not in action.help:\n            if action.default is not SUPPRESS:\n                defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]\n                if action.option_strings or action.nargs in defaulting_nargs:\n                    help += ' (default: %(default)s)'\n        return help\n\n\n# =====================\n# Options and Arguments\n# =====================\n\ndef _get_action_name(argument):\n    if argument is None:\n        return None\n    elif argument.option_strings:\n        return '/'.join(argument.option_strings)\n    elif argument.metavar not in (None, SUPPRESS):\n        return argument.metavar\n    elif argument.dest not in (None, SUPPRESS):\n        return argument.dest\n    else:\n        return None\n\n\nclass ArgumentError(Exception):\n\n    \"\"\"An error from creating or using an argument (optional or positional).\n\n    The string value of this exception is the message, augmented with\n    information about the argument that caused it.\n    \"\"\"\n\n    def __init__(self, argument, message):\n        self.argument_name = _get_action_name(argument)\n        self.message = message\n\n    def __str__(self):\n        if self.argument_name is None:\n            format = '%(message)s'\n        else:\n            format = 'argument %(argument_name)s: %(message)s'\n        return format % dict(\n            message=self.message,\n            argument_name=self.argument_name,\n        )\n\n\nclass ArgumentTypeError(Exception):\n\n    \"\"\"An error from trying to convert a command line string to a type.\"\"\"\n    pass\n\n\n# ==============\n# Action classes\n# ==============\n\nclass Action(_AttributeHolder):\n\n    \"\"\"Information about how to convert command line strings to Python objects.\n\n    Action objects are used by an ArgumentParser to represent the information\n    needed to parse a single argument from one or more strings from the\n    command line. The keyword arguments to the Action constructor are also\n    all attributes of Action instances.\n\n    Keyword Arguments:\n\n        - option_strings -- A list of command-line option strings which\n            should be associated with this action.\n\n        - dest -- The name of the attribute to hold the created object(s)\n\n        - nargs -- The number of command-line arguments that should be\n            consumed. By default, one argument will be consumed and a single\n            value will be produced.  Other values include:\n                - N (an integer) consumes N arguments (and produces a list)\n                - '?' consumes zero or one arguments\n                - '*' consumes zero or more arguments (and produces a list)\n                - '+' consumes one or more arguments (and produces a list)\n            Note that the difference between the default and nargs=1 is that\n            with the default, a single value will be produced, while with\n            nargs=1, a list containing a single value will be produced.\n\n        - const -- The value to be produced if the option is specified and the\n            option uses an action that takes no values.\n\n        - default -- The value to be produced if the option is not specified.\n\n        - type -- The type which the command-line arguments should be converted\n            to, should be one of 'string', 'int', 'float', 'complex' or a\n            callable object that accepts a single string argument. If None,\n            'string' is assumed.\n\n        - choices -- A container of values that should be allowed. If not None,\n            after a command-line argument has been converted to the appropriate\n            type, an exception will be raised if it is not a member of this\n            collection.\n\n        - required -- True if the action must always be specified at the\n            command line. This is only meaningful for optional command-line\n            arguments.\n\n        - help -- The help string describing the argument.\n\n        - metavar -- The name to be used for the option's argument with the\n            help string. If None, the 'dest' value will be used as the name.\n    \"\"\"\n\n    def __init__(\n        self,\n        option_strings,\n        dest,\n        nargs=None,\n        const=None,\n        default=None,\n        type=None,\n        choices=None,\n        required=False,\n        help=None,\n        metavar=None,\n    ):\n        self.option_strings = option_strings\n        self.dest = dest\n        self.nargs = nargs\n        self.const = const\n        self.default = default\n        self.type = type\n        self.choices = choices\n        self.required = required\n        self.help = help\n        self.metavar = metavar\n\n    def _get_kwargs(self):\n        names = [\n            'option_strings',\n            'dest',\n            'nargs',\n            'const',\n            'default',\n            'type',\n            'choices',\n            'help',\n            'metavar',\n        ]\n        return [(name, getattr(self, name)) for name in names]\n\n    def __call__(self, parser, namespace, values, option_string=None):\n        raise NotImplementedError(_('.__call__() not defined'))\n\n\nclass _StoreAction(Action):\n\n    def __init__(\n        self,\n        option_strings,\n        dest,\n        nargs=None,\n        const=None,\n        default=None,\n        type=None,\n        choices=None,\n        required=False,\n        help=None,\n        metavar=None,\n    ):\n        if nargs == 0:\n            raise ValueError(\n                'nargs for store actions must be > 0; if you '\n                'have nothing to store, actions such as store '\n                'true or store const may be more appropriate',\n            )\n        if const is not None and nargs != OPTIONAL:\n            raise ValueError('nargs must be %r to supply const' % OPTIONAL)\n        super(_StoreAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            nargs=nargs,\n            const=const,\n            default=default,\n            type=type,\n            choices=choices,\n            required=required,\n            help=help,\n            metavar=metavar,\n        )\n\n    def __call__(self, parser, namespace, values, option_string=None):\n        setattr(namespace, self.dest, values)\n\n\nclass _StoreConstAction(Action):\n\n    def __init__(\n        self,\n        option_strings,\n        dest,\n        const,\n        default=None,\n        required=False,\n        help=None,\n        metavar=None,\n    ):\n        super(_StoreConstAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            nargs=0,\n            const=const,\n            default=default,\n            required=required,\n            help=help,\n        )\n\n    def __call__(self, parser, namespace, values, option_string=None):\n        setattr(namespace, self.dest, self.const)\n\n\nclass _StoreTrueAction(_StoreConstAction):\n\n    def __init__(\n        self,\n        option_strings,\n        dest,\n        default=False,\n        required=False,\n        help=None,\n    ):\n        super(_StoreTrueAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            const=True,\n            default=default,\n            required=required,\n            help=help,\n        )\n\n\nclass _StoreFalseAction(_StoreConstAction):\n\n    def __init__(\n        self,\n        option_strings,\n        dest,\n        default=True,\n        required=False,\n        help=None,\n    ):\n        super(_StoreFalseAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            const=False,\n            default=default,\n            required=required,\n            help=help,\n        )\n\n\nclass _AppendAction(Action):\n\n    def __init__(\n        self,\n        option_strings,\n        dest,\n        nargs=None,\n        const=None,\n        default=None,\n        type=None,\n        choices=None,\n        required=False,\n        help=None,\n        metavar=None,\n    ):\n        if nargs == 0:\n            raise ValueError(\n                'nargs for append actions must be > 0; if arg '\n                'strings are not supplying the value to append, '\n                'the append const action may be more appropriate',\n            )\n        if const is not None and nargs != OPTIONAL:\n            raise ValueError('nargs must be %r to supply const' % OPTIONAL)\n        super(_AppendAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            nargs=nargs,\n            const=const,\n            default=default,\n            type=type,\n            choices=choices,\n            required=required,\n            help=help,\n            metavar=metavar,\n        )\n\n    def __call__(self, parser, namespace, values, option_string=None):\n        items = _copy.copy(_ensure_value(namespace, self.dest, []))\n        items.append(values)\n        setattr(namespace, self.dest, items)\n\n\nclass _AppendConstAction(Action):\n\n    def __init__(\n        self,\n        option_strings,\n        dest,\n        const,\n        default=None,\n        required=False,\n        help=None,\n        metavar=None,\n    ):\n        super(_AppendConstAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            nargs=0,\n            const=const,\n            default=default,\n            required=required,\n            help=help,\n            metavar=metavar,\n        )\n\n    def __call__(self, parser, namespace, values, option_string=None):\n        items = _copy.copy(_ensure_value(namespace, self.dest, []))\n        items.append(self.const)\n        setattr(namespace, self.dest, items)\n\n\nclass _CountAction(Action):\n\n    def __init__(\n        self,\n        option_strings,\n        dest,\n        default=None,\n        required=False,\n        help=None,\n    ):\n        super(_CountAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            nargs=0,\n            default=default,\n            required=required,\n            help=help,\n        )\n\n    def __call__(self, parser, namespace, values, option_string=None):\n        new_count = _ensure_value(namespace, self.dest, 0) + 1\n        setattr(namespace, self.dest, new_count)\n\n\nclass _HelpAction(Action):\n\n    def __init__(\n        self,\n        option_strings,\n        dest=SUPPRESS,\n        default=SUPPRESS,\n        help=None,\n    ):\n        super(_HelpAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            default=default,\n            nargs=0,\n            help=help,\n        )\n\n    def __call__(self, parser, namespace, values, option_string=None):\n        parser.print_help()\n        parser.exit()\n\n\nclass _VersionAction(Action):\n\n    def __init__(\n        self,\n        option_strings,\n        version=None,\n        dest=SUPPRESS,\n        default=SUPPRESS,\n        help=\"show program's version number and exit\",\n    ):\n        super(_VersionAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            default=default,\n            nargs=0,\n            help=help,\n        )\n        self.version = version\n\n    def __call__(self, parser, namespace, values, option_string=None):\n        version = self.version\n        if version is None:\n            version = parser.version\n        formatter = parser._get_formatter()\n        formatter.add_text(version)\n        parser.exit(message=formatter.format_help())\n\n\nclass _SubParsersAction(Action):\n\n    class _ChoicesPseudoAction(Action):\n\n        def __init__(self, name, help):\n            sup = super(_SubParsersAction._ChoicesPseudoAction, self)\n            sup.__init__(option_strings=[], dest=name, help=help)\n\n    def __init__(\n        self,\n        option_strings,\n        prog,\n        parser_class,\n        dest=SUPPRESS,\n        help=None,\n        metavar=None,\n    ):\n\n        self._prog_prefix = prog\n        self._parser_class = parser_class\n        self._name_parser_map = {}\n        self._choices_actions = []\n\n        super(_SubParsersAction, self).__init__(\n            option_strings=option_strings,\n            dest=dest,\n            nargs=PARSER,\n            choices=self._name_parser_map,\n            help=help,\n            metavar=metavar,\n        )\n\n    def add_parser(self, name, **kwargs):\n        # set prog from the existing prefix\n        if kwargs.get('prog') is None:\n            kwargs['prog'] = '%s %s' % (self._prog_prefix, name)\n\n        # create a pseudo-action to hold the choice help\n        if 'help' in kwargs:\n            help = kwargs.pop('help')\n            choice_action = self._ChoicesPseudoAction(name, help)\n            self._choices_actions.append(choice_action)\n\n        # create the parser and add it to the map\n        parser = self._parser_class(**kwargs)\n        self._name_parser_map[name] = parser\n        return parser\n\n    def _get_subactions(self):\n        return self._choices_actions\n\n    def __call__(self, parser, namespace, values, option_string=None):\n        parser_name = values[0]\n        arg_strings = values[1:]\n\n        # set the parser name if requested\n        if self.dest is not SUPPRESS:\n            setattr(namespace, self.dest, parser_name)\n\n        # select the parser\n        try:\n            parser = self._name_parser_map[parser_name]\n        except KeyError:\n            tup = parser_name, ', '.join(self._name_parser_map)\n            msg = _('unknown parser %r (choices: %s)' % tup)\n            raise ArgumentError(self, msg)\n\n        # parse all the remaining options into the namespace\n        # store any unrecognized options on the object, so that the top\n        # level parser can decide what to do with them\n        namespace, arg_strings = parser.parse_known_args(\n            arg_strings, namespace,\n        )\n        if arg_strings:\n            vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])\n            getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)\n\n\n# ==============\n# Type classes\n# ==============\n\nclass FileType(object):\n\n    \"\"\"Factory for creating file object types\n\n    Instances of FileType are typically passed as type= arguments to the\n    ArgumentParser add_argument() method.\n\n    Keyword Arguments:\n        - mode -- A string indicating how the file is to be opened. Accepts the\n            same values as the builtin open() function.\n        - bufsize -- The file's desired buffer size. Accepts the same values as\n            the builtin open() function.\n    \"\"\"\n\n    def __init__(self, mode='r', bufsize=None):\n        self._mode = mode\n        self._bufsize = bufsize\n\n    def __call__(self, string):\n        # the special argument \"-\" means sys.std{in,out}\n        if string == '-':\n            if 'r' in self._mode:\n                return _sys.stdin\n            elif 'w' in self._mode:\n                return _sys.stdout\n            else:\n                msg = _('argument \"-\" with mode %r' % self._mode)\n                raise ValueError(msg)\n\n        # all other arguments are used as file names\n        if self._bufsize:\n            return open(string, self._mode, self._bufsize)\n        else:\n            return open(string, self._mode)\n\n    def __repr__(self):\n        args = [self._mode, self._bufsize]\n        args_str = ', '.join([repr(arg) for arg in args if arg is not None])\n        return '%s(%s)' % (type(self).__name__, args_str)\n\n# ===========================\n# Optional and Positional Parsing\n# ===========================\n\n\nclass Namespace(_AttributeHolder):\n\n    \"\"\"Simple object for storing attributes.\n\n    Implements equality by attribute names and values, and provides a simple\n    string representation.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        for name in kwargs:\n            setattr(self, name, kwargs[name])\n\n    __hash__ = None\n\n    def __eq__(self, other):\n        return vars(self) == vars(other)\n\n    def __ne__(self, other):\n        return not (self == other)\n\n    def __contains__(self, key):\n        return key in self.__dict__\n\n\nclass _ActionsContainer(object):\n\n    def __init__(\n        self,\n        description,\n        prefix_chars,\n        argument_default,\n        conflict_handler,\n    ):\n        super(_ActionsContainer, self).__init__()\n\n        self.description = description\n        self.argument_default = argument_default\n        self.prefix_chars = prefix_chars\n        self.conflict_handler = conflict_handler\n\n        # set up registries\n        self._registries = {}\n\n        # register actions\n        self.register('action', None, _StoreAction)\n        self.register('action', 'store', _StoreAction)\n        self.register('action', 'store_const', _StoreConstAction)\n        self.register('action', 'store_true', _StoreTrueAction)\n        self.register('action', 'store_false', _StoreFalseAction)\n        self.register('action', 'append', _AppendAction)\n        self.register('action', 'append_const', _AppendConstAction)\n        self.register('action', 'count', _CountAction)\n        self.register('action', 'help', _HelpAction)\n        self.register('action', 'version', _VersionAction)\n        self.register('action', 'parsers', _SubParsersAction)\n\n        # raise an exception if the conflict handler is invalid\n        self._get_handler()\n\n        # action storage\n        self._actions = []\n        self._option_string_actions = {}\n\n        # groups\n        self._action_groups = []\n        self._mutually_exclusive_groups = []\n\n        # defaults storage\n        self._defaults = {}\n\n        # determines whether an \"option\" looks like a negative number\n        self._negative_number_matcher = _re.compile(r'^-\\d+$|^-\\d*\\.\\d+$')\n\n        # whether or not there are any optionals that look like negative\n        # numbers -- uses a list so it can be shared and edited\n        self._has_negative_number_optionals = []\n\n    # ====================\n    # Registration methods\n    # ====================\n    def register(self, registry_name, value, object):\n        registry = self._registries.setdefault(registry_name, {})\n        registry[value] = object\n\n    def _registry_get(self, registry_name, value, default=None):\n        return self._registries[registry_name].get(value, default)\n\n    # ==================================\n    # Namespace default accessor methods\n    # ==================================\n    def set_defaults(self, **kwargs):\n        self._defaults.update(kwargs)\n\n        # if these defaults match any existing arguments, replace\n        # the previous default on the object with the new one\n        for action in self._actions:\n            if action.dest in kwargs:\n                action.default = kwargs[action.dest]\n\n    def get_default(self, dest):\n        for action in self._actions:\n            if action.dest == dest and action.default is not None:\n                return action.default\n        return self._defaults.get(dest, None)\n\n    # =======================\n    # Adding argument actions\n    # =======================\n    def add_argument(self, *args, **kwargs):\n        \"\"\"\n        add_argument(dest, ..., name=value, ...)\n        add_argument(option_string, option_string, ..., name=value, ...)\n        \"\"\"\n\n        # if no positional args are supplied or only one is supplied and\n        # it doesn't look like an option string, parse a positional\n        # argument\n        chars = self.prefix_chars\n        if not args or len(args) == 1 and args[0][0] not in chars:\n            if args and 'dest' in kwargs:\n                raise ValueError('dest supplied twice for positional argument')\n            kwargs = self._get_positional_kwargs(*args, **kwargs)\n\n        # otherwise, we're adding an optional argument\n        else:\n            kwargs = self._get_optional_kwargs(*args, **kwargs)\n\n        # if no default was supplied, use the parser-level default\n        if 'default' not in kwargs:\n            dest = kwargs['dest']\n            if dest in self._defaults:\n                kwargs['default'] = self._defaults[dest]\n            elif self.argument_default is not None:\n                kwargs['default'] = self.argument_default\n\n        # create the action object, and add it to the parser\n        action_class = self._pop_action_class(kwargs)\n        if not _callable(action_class):\n            raise ValueError('unknown action \"%s\"' % action_class)\n        action = action_class(**kwargs)\n\n        # raise an error if the action type is not callable\n        type_func = self._registry_get('type', action.type, action.type)\n        if not _callable(type_func):\n            raise ValueError('%r is not callable' % type_func)\n\n        return self._add_action(action)\n\n    def add_argument_group(self, *args, **kwargs):\n        group = _ArgumentGroup(self, *args, **kwargs)\n        self._action_groups.append(group)\n        return group\n\n    def add_mutually_exclusive_group(self, **kwargs):\n        group = _MutuallyExclusiveGroup(self, **kwargs)\n        self._mutually_exclusive_groups.append(group)\n        return group\n\n    def _add_action(self, action):\n        # resolve any conflicts\n        self._check_conflict(action)\n\n        # add to actions list\n        self._actions.append(action)\n        action.container = self\n\n        # index the action by any option strings it has\n        for option_string in action.option_strings:\n            self._option_string_actions[option_string] = action\n\n        # set the flag if any option strings look like negative numbers\n        for option_string in action.option_strings:\n            if self._negative_number_matcher.match(option_string):\n                if not self._has_negative_number_optionals:\n                    self._has_negative_number_optionals.append(True)\n\n        # return the created action\n        return action\n\n    def _remove_action(self, action):\n        self._actions.remove(action)\n\n    def _add_container_actions(self, container):\n        # collect groups by titles\n        title_group_map = {}\n        for group in self._action_groups:\n            if group.title in title_group_map:\n                msg = _('cannot merge actions - two groups are named %r')\n                raise ValueError(msg % (group.title))\n            title_group_map[group.title] = group\n\n        # map each action to its group\n        group_map = {}\n        for group in container._action_groups:\n\n            # if a group with the title exists, use that, otherwise\n            # create a new group matching the container's group\n            if group.title not in title_group_map:\n                title_group_map[group.title] = self.add_argument_group(\n                    title=group.title,\n                    description=group.description,\n                    conflict_handler=group.conflict_handler,\n                )\n\n            # map the actions to their new group\n            for action in group._group_actions:\n                group_map[action] = title_group_map[group.title]\n\n        # add container's mutually exclusive groups\n        # NOTE: if add_mutually_exclusive_group ever gains title= and\n        # description= then this code will need to be expanded as above\n        for group in container._mutually_exclusive_groups:\n            mutex_group = self.add_mutually_exclusive_group(\n                required=group.required,\n            )\n\n            # map the actions to their new mutex group\n            for action in group._group_actions:\n                group_map[action] = mutex_group\n\n        # add all actions to this container or their group\n        for action in container._actions:\n            group_map.get(action, self)._add_action(action)\n\n    def _get_positional_kwargs(self, dest, **kwargs):\n        # make sure required is not specified\n        if 'required' in kwargs:\n            msg = _(\"'required' is an invalid argument for positionals\")\n            raise TypeError(msg)\n\n        # mark positional arguments as required if at least one is\n        # always required\n        if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:\n            kwargs['required'] = True\n        if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:\n            kwargs['required'] = True\n\n        # return the keyword arguments with no option strings\n        return dict(kwargs, dest=dest, option_strings=[])\n\n    def _get_optional_kwargs(self, *args, **kwargs):\n        # determine short and long option strings\n        option_strings = []\n        long_option_strings = []\n        for option_string in args:\n            # error on strings that don't start with an appropriate prefix\n            if not option_string[0] in self.prefix_chars:\n                msg = _(\n                    'invalid option string %r: '\n                    'must start with a character %r',\n                )\n                tup = option_string, self.prefix_chars\n                raise ValueError(msg % tup)\n\n            # strings starting with two prefix characters are long options\n            option_strings.append(option_string)\n            if option_string[0] in self.prefix_chars:\n                if len(option_string) > 1:\n                    if option_string[1] in self.prefix_chars:\n                        long_option_strings.append(option_string)\n\n        # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'\n        dest = kwargs.pop('dest', None)\n        if dest is None:\n            if long_option_strings:\n                dest_option_string = long_option_strings[0]\n            else:\n                dest_option_string = option_strings[0]\n            dest = dest_option_string.lstrip(self.prefix_chars)\n            if not dest:\n                msg = _('dest= is required for options like %r')\n                raise ValueError(msg % option_string)\n            dest = dest.replace('-', '_')\n\n        # return the updated keyword arguments\n        return dict(kwargs, dest=dest, option_strings=option_strings)\n\n    def _pop_action_class(self, kwargs, default=None):\n        action = kwargs.pop('action', default)\n        return self._registry_get('action', action, action)\n\n    def _get_handler(self):\n        # determine function from conflict handler string\n        handler_func_name = '_handle_conflict_%s' % self.conflict_handler\n        try:\n            return getattr(self, handler_func_name)\n        except AttributeError:\n            msg = _('invalid conflict_resolution value: %r')\n            raise ValueError(msg % self.conflict_handler)\n\n    def _check_conflict(self, action):\n\n        # find all options that conflict with this option\n        confl_optionals = []\n        for option_string in action.option_strings:\n            if option_string in self._option_string_actions:\n                confl_optional = self._option_string_actions[option_string]\n                confl_optionals.append((option_string, confl_optional))\n\n        # resolve any conflicts\n        if confl_optionals:\n            conflict_handler = self._get_handler()\n            conflict_handler(action, confl_optionals)\n\n    def _handle_conflict_error(self, action, conflicting_actions):\n        message = _('conflicting option string(s): %s')\n        conflict_string = ', '.join([\n            option_string\n            for option_string, action\n            in conflicting_actions\n        ])\n        raise ArgumentError(action, message % conflict_string)\n\n    def _handle_conflict_resolve(self, action, conflicting_actions):\n\n        # remove all conflicting options\n        for option_string, action in conflicting_actions:\n\n            # remove the conflicting option\n            action.option_strings.remove(option_string)\n            self._option_string_actions.pop(option_string, None)\n\n            # if the option now has no option string, remove it from the\n            # container holding it\n            if not action.option_strings:\n                action.container._remove_action(action)\n\n\nclass _ArgumentGroup(_ActionsContainer):\n\n    def __init__(self, container, title=None, description=None, **kwargs):\n        # add any missing keyword arguments by checking the container\n        update = kwargs.setdefault\n        update('conflict_handler', container.conflict_handler)\n        update('prefix_chars', container.prefix_chars)\n        update('argument_default', container.argument_default)\n        super_init = super(_ArgumentGroup, self).__init__\n        super_init(description=description, **kwargs)\n\n        # group attributes\n        self.title = title\n        self._group_actions = []\n\n        # share most attributes with the container\n        self._registries = container._registries\n        self._actions = container._actions\n        self._option_string_actions = container._option_string_actions\n        self._defaults = container._defaults\n        self._has_negative_number_optionals = \\\n            container._has_negative_number_optionals\n\n    def _add_action(self, action):\n        action = super(_ArgumentGroup, self)._add_action(action)\n        self._group_actions.append(action)\n        return action\n\n    def _remove_action(self, action):\n        super(_ArgumentGroup, self)._remove_action(action)\n        self._group_actions.remove(action)\n\n\nclass _MutuallyExclusiveGroup(_ArgumentGroup):\n\n    def __init__(self, container, required=False):\n        super(_MutuallyExclusiveGroup, self).__init__(container)\n        self.required = required\n        self._container = container\n\n    def _add_action(self, action):\n        if action.required:\n            msg = _('mutually exclusive arguments must be optional')\n            raise ValueError(msg)\n        action = self._container._add_action(action)\n        self._group_actions.append(action)\n        return action\n\n    def _remove_action(self, action):\n        self._container._remove_action(action)\n        self._group_actions.remove(action)\n\n\nclass ArgumentParser(_AttributeHolder, _ActionsContainer):\n\n    \"\"\"Object for parsing command line strings into Python objects.\n\n    Keyword Arguments:\n        - prog -- The name of the program (default: sys.argv[0])\n        - usage -- A usage message (default: auto-generated from arguments)\n        - description -- A description of what the program does\n        - epilog -- Text following the argument descriptions\n        - parents -- Parsers whose arguments should be copied into this one\n        - formatter_class -- HelpFormatter class for printing help messages\n        - prefix_chars -- Characters that prefix optional arguments\n        - fromfile_prefix_chars -- Characters that prefix files containing\n            additional arguments\n        - argument_default -- The default value for all arguments\n        - conflict_handler -- String indicating how to handle conflicts\n        - add_help -- Add a -h/-help option\n    \"\"\"\n\n    def __init__(\n        self,\n        prog=None,\n        usage=None,\n        description=None,\n        epilog=None,\n        version=None,\n        parents=[],\n        formatter_class=HelpFormatter,\n        prefix_chars='-',\n        fromfile_prefix_chars=None,\n        argument_default=None,\n        conflict_handler='error',\n        add_help=True,\n    ):\n\n        if version is not None:\n            import warnings\n            warnings.warn(\n                \"\"\"The \"version\" argument to ArgumentParser is deprecated. \"\"\"\n                \"\"\"Please use \"\"\"\n                \"\"\"\"add_argument(..., action='version', version=\"N\", ...)\" \"\"\"\n                \"\"\"instead\"\"\", DeprecationWarning,\n            )\n\n        superinit = super(ArgumentParser, self).__init__\n        superinit(\n            description=description,\n            prefix_chars=prefix_chars,\n            argument_default=argument_default,\n            conflict_handler=conflict_handler,\n        )\n\n        # default setting for prog\n        if prog is None:\n            prog = _os.path.basename(_sys.argv[0])\n\n        self.prog = prog\n        self.usage = usage\n        self.epilog = epilog\n        self.version = version\n        self.formatter_class = formatter_class\n        self.fromfile_prefix_chars = fromfile_prefix_chars\n        self.add_help = add_help\n\n        add_group = self.add_argument_group\n        self._positionals = add_group(_('positional arguments'))\n        self._optionals = add_group(_('optional arguments'))\n        self._subparsers = None\n\n        # register types\n        def identity(string):\n            return string\n        self.register('type', None, identity)\n\n        # add help and version arguments if necessary\n        # (using explicit default to override global argument_default)\n        if '-' in prefix_chars:\n            default_prefix = '-'\n        else:\n            default_prefix = prefix_chars[0]\n        if self.add_help:\n            self.add_argument(\n                default_prefix + 'h', default_prefix * 2 + 'help',\n                action='help', default=SUPPRESS,\n                help=_('show this help message and exit'),\n            )\n        if self.version:\n            self.add_argument(\n                default_prefix + 'v', default_prefix * 2 + 'version',\n                action='version', default=SUPPRESS,\n                version=self.version,\n                help=_(\"show program's version number and exit\"),\n            )\n\n        # add parent arguments and defaults\n        for parent in parents:\n            self._add_container_actions(parent)\n            try:\n                defaults = parent._defaults\n            except AttributeError:\n                pass\n            else:\n                self._defaults.update(defaults)\n\n    # =======================\n    # Pretty __repr__ methods\n    # =======================\n    def _get_kwargs(self):\n        names = [\n            'prog',\n            'usage',\n            'description',\n            'version',\n            'formatter_class',\n            'conflict_handler',\n            'add_help',\n        ]\n        return [(name, getattr(self, name)) for name in names]\n\n    # ==================================\n    # Optional/Positional adding methods\n    # ==================================\n    def add_subparsers(self, **kwargs):\n        if self._subparsers is not None:\n            self.error(_('cannot have multiple subparser arguments'))\n\n        # add the parser class to the arguments if it's not present\n        kwargs.setdefault('parser_class', type(self))\n\n        if 'title' in kwargs or 'description' in kwargs:\n            title = _(kwargs.pop('title', 'subcommands'))\n            description = _(kwargs.pop('description', None))\n            self._subparsers = self.add_argument_group(title, description)\n        else:\n            self._subparsers = self._positionals\n\n        # prog defaults to the usage message of this parser, skipping\n        # optional arguments and with no \"usage:\" prefix\n        if kwargs.get('prog') is None:\n            formatter = self._get_formatter()\n            positionals = self._get_positional_actions()\n            groups = self._mutually_exclusive_groups\n            formatter.add_usage(self.usage, positionals, groups, '')\n            kwargs['prog'] = formatter.format_help().strip()\n\n        # create the parsers action and add it to the positionals list\n        parsers_class = self._pop_action_class(kwargs, 'parsers')\n        action = parsers_class(option_strings=[], **kwargs)\n        self._subparsers._add_action(action)\n\n        # return the created parsers action\n        return action\n\n    def _add_action(self, action):\n        if action.option_strings:\n            self._optionals._add_action(action)\n        else:\n            self._positionals._add_action(action)\n        return action\n\n    def _get_optional_actions(self):\n        return [\n            action\n            for action in self._actions\n            if action.option_strings\n        ]\n\n    def _get_positional_actions(self):\n        return [\n            action\n            for action in self._actions\n            if not action.option_strings\n        ]\n\n    # =====================================\n    # Command line argument parsing methods\n    # =====================================\n    def parse_args(self, args=None, namespace=None):\n        args, argv = self.parse_known_args(args, namespace)\n        if argv:\n            msg = _('unrecognized arguments: %s')\n            self.error(msg % ' '.join(argv))\n        return args\n\n    def parse_known_args(self, args=None, namespace=None):\n        # args default to the system args\n        if args is None:\n            args = _sys.argv[1:]\n\n        # default Namespace built from parser defaults\n        if namespace is None:\n            namespace = Namespace()\n\n        # add any action defaults that aren't present\n        for action in self._actions:\n            if action.dest is not SUPPRESS:\n                if not hasattr(namespace, action.dest):\n                    if action.default is not SUPPRESS:\n                        default = action.default\n                        if isinstance(action.default, basestring):\n                            default = self._get_value(action, default)\n                        setattr(namespace, action.dest, default)\n\n        # add any parser defaults that aren't present\n        for dest in self._defaults:\n            if not hasattr(namespace, dest):\n                setattr(namespace, dest, self._defaults[dest])\n\n        # parse the arguments and exit if there are any errors\n        try:\n            namespace, args = self._parse_known_args(args, namespace)\n            if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):\n                args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))\n                delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)\n            return namespace, args\n        except ArgumentError:\n            err = _sys.exc_info()[1]\n            self.error(str(err))\n\n    def _parse_known_args(self, arg_strings, namespace):\n        # replace arg strings that are file references\n        if self.fromfile_prefix_chars is not None:\n            arg_strings = self._read_args_from_files(arg_strings)\n\n        # map all mutually exclusive arguments to the other arguments\n        # they can't occur with\n        action_conflicts = {}\n        for mutex_group in self._mutually_exclusive_groups:\n            group_actions = mutex_group._group_actions\n            for i, mutex_action in enumerate(mutex_group._group_actions):\n                conflicts = action_conflicts.setdefault(mutex_action, [])\n                conflicts.extend(group_actions[:i])\n                conflicts.extend(group_actions[i + 1:])\n\n        # find all option indices, and determine the arg_string_pattern\n        # which has an 'O' if there is an option at an index,\n        # an 'A' if there is an argument, or a '-' if there is a '--'\n        option_string_indices = {}\n        arg_string_pattern_parts = []\n        arg_strings_iter = iter(arg_strings)\n        for i, arg_string in enumerate(arg_strings_iter):\n\n            # all args after -- are non-options\n            if arg_string == '--':\n                arg_string_pattern_parts.append('-')\n                for arg_string in arg_strings_iter:\n                    arg_string_pattern_parts.append('A')\n\n            # otherwise, add the arg to the arg strings\n            # and note the index if it was an option\n            else:\n                option_tuple = self._parse_optional(arg_string)\n                if option_tuple is None:\n                    pattern = 'A'\n                else:\n                    option_string_indices[i] = option_tuple\n                    pattern = 'O'\n                arg_string_pattern_parts.append(pattern)\n\n        # join the pieces together to form the pattern\n        arg_strings_pattern = ''.join(arg_string_pattern_parts)\n\n        # converts arg strings to the appropriate and then takes the action\n        seen_actions = set()\n        seen_non_default_actions = set()\n\n        def take_action(action, argument_strings, option_string=None):\n            seen_actions.add(action)\n            argument_values = self._get_values(action, argument_strings)\n\n            # error if this argument is not allowed with other previously\n            # seen arguments, assuming that actions that use the default\n            # value don't really count as \"present\"\n            if argument_values is not action.default:\n                seen_non_default_actions.add(action)\n                for conflict_action in action_conflicts.get(action, []):\n                    if conflict_action in seen_non_default_actions:\n                        msg = _('not allowed with argument %s')\n                        action_name = _get_action_name(conflict_action)\n                        raise ArgumentError(action, msg % action_name)\n\n            # take the action if we didn't receive a SUPPRESS value\n            # (e.g. from a default)\n            if argument_values is not SUPPRESS:\n                action(self, namespace, argument_values, option_string)\n\n        # function to convert arg_strings into an optional action\n        def consume_optional(start_index):\n\n            # get the optional identified at this index\n            option_tuple = option_string_indices[start_index]\n            action, option_string, explicit_arg = option_tuple\n\n            # identify additional optionals in the same arg string\n            # (e.g. -xyz is the same as -x -y -z if no args are required)\n            match_argument = self._match_argument\n            action_tuples = []\n            while True:\n\n                # if we found no optional action, skip it\n                if action is None:\n                    extras.append(arg_strings[start_index])\n                    return start_index + 1\n\n                # if there is an explicit argument, try to match the\n                # optional's string arguments to only this\n                if explicit_arg is not None:\n                    arg_count = match_argument(action, 'A')\n\n                    # if the action is a single-dash option and takes no\n                    # arguments, try to parse more single-dash options out\n                    # of the tail of the option string\n                    chars = self.prefix_chars\n                    if arg_count == 0 and option_string[1] not in chars:\n                        action_tuples.append((action, [], option_string))\n                        char = option_string[0]\n                        option_string = char + explicit_arg[0]\n                        new_explicit_arg = explicit_arg[1:] or None\n                        optionals_map = self._option_string_actions\n                        if option_string in optionals_map:\n                            action = optionals_map[option_string]\n                            explicit_arg = new_explicit_arg\n                        else:\n                            msg = _('ignored explicit argument %r')\n                            raise ArgumentError(action, msg % explicit_arg)\n\n                    # if the action expect exactly one argument, we've\n                    # successfully matched the option; exit the loop\n                    elif arg_count == 1:\n                        stop = start_index + 1\n                        args = [explicit_arg]\n                        action_tuples.append((action, args, option_string))\n                        break\n\n                    # error if a double-dash option did not use the\n                    # explicit argument\n                    else:\n                        msg = _('ignored explicit argument %r')\n                        raise ArgumentError(action, msg % explicit_arg)\n\n                # if there is no explicit argument, try to match the\n                # optional's string arguments with the following strings\n                # if successful, exit the loop\n                else:\n                    start = start_index + 1\n                    selected_patterns = arg_strings_pattern[start:]\n                    arg_count = match_argument(action, selected_patterns)\n                    stop = start + arg_count\n                    args = arg_strings[start:stop]\n                    action_tuples.append((action, args, option_string))\n                    break\n\n            # add the Optional to the list and return the index at which\n            # the Optional's string args stopped\n            assert action_tuples\n            for action, args, option_string in action_tuples:\n                take_action(action, args, option_string)\n            return stop\n\n        # the list of Positionals left to be parsed; this is modified\n        # by consume_positionals()\n        positionals = self._get_positional_actions()\n\n        # function to convert arg_strings into positional actions\n        def consume_positionals(start_index):\n            # match as many Positionals as possible\n            match_partial = self._match_arguments_partial\n            selected_pattern = arg_strings_pattern[start_index:]\n            arg_counts = match_partial(positionals, selected_pattern)\n\n            # slice off the appropriate arg strings for each Positional\n            # and add the Positional and its args to the list\n            for action, arg_count in zip(positionals, arg_counts):\n                args = arg_strings[start_index: start_index + arg_count]\n                start_index += arg_count\n                take_action(action, args)\n\n            # slice off the Positionals that we just parsed and return the\n            # index at which the Positionals' string args stopped\n            positionals[:] = positionals[len(arg_counts):]\n            return start_index\n\n        # consume Positionals and Optionals alternately, until we have\n        # passed the last option string\n        extras = []\n        start_index = 0\n        if option_string_indices:\n            max_option_string_index = max(option_string_indices)\n        else:\n            max_option_string_index = -1\n        while start_index <= max_option_string_index:\n\n            # consume any Positionals preceding the next option\n            next_option_string_index = min([\n                index\n                for index in option_string_indices\n                if index >= start_index\n            ])\n            if start_index != next_option_string_index:\n                positionals_end_index = consume_positionals(start_index)\n\n                # only try to parse the next optional if we didn't consume\n                # the option string during the positionals parsing\n                if positionals_end_index > start_index:\n                    start_index = positionals_end_index\n                    continue\n                else:\n                    start_index = positionals_end_index\n\n            # if we consumed all the positionals we could and we're not\n            # at the index of an option string, there were extra arguments\n            if start_index not in option_string_indices:\n                strings = arg_strings[start_index:next_option_string_index]\n                extras.extend(strings)\n                start_index = next_option_string_index\n\n            # consume the next optional and any arguments for it\n            start_index = consume_optional(start_index)\n\n        # consume any positionals following the last Optional\n        stop_index = consume_positionals(start_index)\n\n        # if we didn't consume all the argument strings, there were extras\n        extras.extend(arg_strings[stop_index:])\n\n        # if we didn't use all the Positional objects, there were too few\n        # arg strings supplied.\n        if positionals:\n            self.error(_('too few arguments'))\n\n        # make sure all required actions were present\n        for action in self._actions:\n            if action.required:\n                if action not in seen_actions:\n                    name = _get_action_name(action)\n                    self.error(_('argument %s is required') % name)\n\n        # make sure all required groups had one option present\n        for group in self._mutually_exclusive_groups:\n            if group.required:\n                for action in group._group_actions:\n                    if action in seen_non_default_actions:\n                        break\n\n                # if no actions were used, report the error\n                else:\n                    names = [\n                        _get_action_name(action)\n                        for action in group._group_actions\n                        if action.help is not SUPPRESS\n                    ]\n                    msg = _('one of the arguments %s is required')\n                    self.error(msg % ' '.join(names))\n\n        # return the updated namespace and the extra arguments\n        return namespace, extras\n\n    def _read_args_from_files(self, arg_strings):\n        # expand arguments referencing files\n        new_arg_strings = []\n        for arg_string in arg_strings:\n\n            # for regular arguments, just add them back into the list\n            if arg_string[0] not in self.fromfile_prefix_chars:\n                new_arg_strings.append(arg_string)\n\n            # replace arguments referencing files with the file content\n            else:\n                try:\n                    args_file = open(arg_string[1:])\n                    try:\n                        arg_strings = []\n                        for arg_line in args_file.read().splitlines():\n                            for arg in self.convert_arg_line_to_args(arg_line):\n                                arg_strings.append(arg)\n                        arg_strings = self._read_args_from_files(arg_strings)\n                        new_arg_strings.extend(arg_strings)\n                    finally:\n                        args_file.close()\n                except IOError:\n                    err = _sys.exc_info()[1]\n                    self.error(str(err))\n\n        # return the modified argument list\n        return new_arg_strings\n\n    def convert_arg_line_to_args(self, arg_line):\n        return [arg_line]\n\n    def _match_argument(self, action, arg_strings_pattern):\n        # match the pattern for this action to the arg strings\n        nargs_pattern = self._get_nargs_pattern(action)\n        match = _re.match(nargs_pattern, arg_strings_pattern)\n\n        # raise an exception if we weren't able to find a match\n        if match is None:\n            nargs_errors = {\n                None: _('expected one argument'),\n                OPTIONAL: _('expected at most one argument'),\n                ONE_OR_MORE: _('expected at least one argument'),\n            }\n            default = _('expected %s argument(s)') % action.nargs\n            msg = nargs_errors.get(action.nargs, default)\n            raise ArgumentError(action, msg)\n\n        # return the number of arguments matched\n        return len(match.group(1))\n\n    def _match_arguments_partial(self, actions, arg_strings_pattern):\n        # progressively shorten the actions list by slicing off the\n        # final actions until we find a match\n        result = []\n        for i in range(len(actions), 0, -1):\n            actions_slice = actions[:i]\n            pattern = ''.join([\n                self._get_nargs_pattern(action)\n                for action in actions_slice\n            ])\n            match = _re.match(pattern, arg_strings_pattern)\n            if match is not None:\n                result.extend([len(string) for string in match.groups()])\n                break\n\n        # return the list of arg string counts\n        return result\n\n    def _parse_optional(self, arg_string):\n        # if it's an empty string, it was meant to be a positional\n        if not arg_string:\n            return None\n\n        # if it doesn't start with a prefix, it was meant to be positional\n        if not arg_string[0] in self.prefix_chars:\n            return None\n\n        # if the option string is present in the parser, return the action\n        if arg_string in self._option_string_actions:\n            action = self._option_string_actions[arg_string]\n            return action, arg_string, None\n\n        # if it's just a single character, it was meant to be positional\n        if len(arg_string) == 1:\n            return None\n\n        # if the option string before the \"=\" is present, return the action\n        if '=' in arg_string:\n            option_string, explicit_arg = arg_string.split('=', 1)\n            if option_string in self._option_string_actions:\n                action = self._option_string_actions[option_string]\n                return action, option_string, explicit_arg\n\n        # search through all possible prefixes of the option string\n        # and all actions in the parser for possible interpretations\n        option_tuples = self._get_option_tuples(arg_string)\n\n        # if multiple actions match, the option string was ambiguous\n        if len(option_tuples) > 1:\n            options = ', '.join(\n                [option_string for action, option_string, explicit_arg in option_tuples],\n            )\n            tup = arg_string, options\n            self.error(_('ambiguous option: %s could match %s') % tup)\n\n        # if exactly one action matched, this segmentation is good,\n        # so return the parsed action\n        elif len(option_tuples) == 1:\n            option_tuple, = option_tuples\n            return option_tuple\n\n        # if it was not found as an option, but it looks like a negative\n        # number, it was meant to be positional\n        # unless there are negative-number-like options\n        if self._negative_number_matcher.match(arg_string):\n            if not self._has_negative_number_optionals:\n                return None\n\n        # if it contains a space, it was meant to be a positional\n        if ' ' in arg_string:\n            return None\n\n        # it was meant to be an optional but there is no such option\n        # in this parser (though it might be a valid option in a subparser)\n        return None, arg_string, None\n\n    def _get_option_tuples(self, option_string):\n        result = []\n\n        # option strings starting with two prefix characters are only\n        # split at the '='\n        chars = self.prefix_chars\n        if option_string[0] in chars and option_string[1] in chars:\n            if '=' in option_string:\n                option_prefix, explicit_arg = option_string.split('=', 1)\n            else:\n                option_prefix = option_string\n                explicit_arg = None\n            for option_string in self._option_string_actions:\n                if option_string.startswith(option_prefix):\n                    action = self._option_string_actions[option_string]\n                    tup = action, option_string, explicit_arg\n                    result.append(tup)\n\n        # single character options can be concatenated with their arguments\n        # but multiple character options always have to have their argument\n        # separate\n        elif option_string[0] in chars and option_string[1] not in chars:\n            option_prefix = option_string\n            explicit_arg = None\n            short_option_prefix = option_string[:2]\n            short_explicit_arg = option_string[2:]\n\n            for option_string in self._option_string_actions:\n                if option_string == short_option_prefix:\n                    action = self._option_string_actions[option_string]\n                    tup = action, option_string, short_explicit_arg\n                    result.append(tup)\n                elif option_string.startswith(option_prefix):\n                    action = self._option_string_actions[option_string]\n                    tup = action, option_string, explicit_arg\n                    result.append(tup)\n\n        # shouldn't ever get here\n        else:\n            self.error(_('unexpected option string: %s') % option_string)\n\n        # return the collected option tuples\n        return result\n\n    def _get_nargs_pattern(self, action):\n        # in all examples below, we have to allow for '--' args\n        # which are represented as '-' in the pattern\n        nargs = action.nargs\n\n        # the default (None) is assumed to be a single argument\n        if nargs is None:\n            nargs_pattern = '(-*A-*)'\n\n        # allow zero or one arguments\n        elif nargs == OPTIONAL:\n            nargs_pattern = '(-*A?-*)'\n\n        # allow zero or more arguments\n        elif nargs == ZERO_OR_MORE:\n            nargs_pattern = '(-*[A-]*)'\n\n        # allow one or more arguments\n        elif nargs == ONE_OR_MORE:\n            nargs_pattern = '(-*A[A-]*)'\n\n        # allow any number of options or arguments\n        elif nargs == REMAINDER:\n            nargs_pattern = '([-AO]*)'\n\n        # allow one argument followed by any number of options or arguments\n        elif nargs == PARSER:\n            nargs_pattern = '(-*A[-AO]*)'\n\n        # all others should be integers\n        else:\n            nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)\n\n        # if this is an optional action, -- is not allowed\n        if action.option_strings:\n            nargs_pattern = nargs_pattern.replace('-*', '')\n            nargs_pattern = nargs_pattern.replace('-', '')\n\n        # return the pattern\n        return nargs_pattern\n\n    # ========================\n    # Value conversion methods\n    # ========================\n    def _get_values(self, action, arg_strings):\n        # for everything but PARSER args, strip out '--'\n        if action.nargs not in [PARSER, REMAINDER]:\n            arg_strings = [s for s in arg_strings if s != '--']\n\n        # optional argument produces a default when not present\n        if not arg_strings and action.nargs == OPTIONAL:\n            if action.option_strings:\n                value = action.const\n            else:\n                value = action.default\n            if isinstance(value, basestring):\n                value = self._get_value(action, value)\n                self._check_value(action, value)\n\n        # when nargs='*' on a positional, if there were no command-line\n        # args, use the default if it is anything other than None\n        elif (\n            not arg_strings and action.nargs == ZERO_OR_MORE and\n            not action.option_strings\n        ):\n            if action.default is not None:\n                value = action.default\n            else:\n                value = arg_strings\n            self._check_value(action, value)\n\n        # single argument or optional argument produces a single value\n        elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:\n            arg_string, = arg_strings\n            value = self._get_value(action, arg_string)\n            self._check_value(action, value)\n\n        # REMAINDER arguments convert all values, checking none\n        elif action.nargs == REMAINDER:\n            value = [self._get_value(action, v) for v in arg_strings]\n\n        # PARSER arguments convert all values, but check only the first\n        elif action.nargs == PARSER:\n            value = [self._get_value(action, v) for v in arg_strings]\n            self._check_value(action, value[0])\n\n        # all other types of nargs produce a list\n        else:\n            value = [self._get_value(action, v) for v in arg_strings]\n            for v in value:\n                self._check_value(action, v)\n\n        # return the converted value\n        return value\n\n    def _get_value(self, action, arg_string):\n        type_func = self._registry_get('type', action.type, action.type)\n        if not _callable(type_func):\n            msg = _('%r is not callable')\n            raise ArgumentError(action, msg % type_func)\n\n        # convert the value to the appropriate type\n        try:\n            result = type_func(arg_string)\n\n        # ArgumentTypeErrors indicate errors\n        except ArgumentTypeError:\n            name = getattr(action.type, '__name__', repr(action.type))\n            msg = str(_sys.exc_info()[1])\n            raise ArgumentError(action, msg)\n\n        # TypeErrors or ValueErrors also indicate errors\n        except (TypeError, ValueError):\n            name = getattr(action.type, '__name__', repr(action.type))\n            msg = _('invalid %s value: %r')\n            raise ArgumentError(action, msg % (name, arg_string))\n\n        # return the converted value\n        return result\n\n    def _check_value(self, action, value):\n        # converted value must be one of the choices (if specified)\n        if action.choices is not None and value not in action.choices:\n            tup = value, ', '.join(map(repr, action.choices))\n            msg = _('invalid choice: %r (choose from %s)') % tup\n            raise ArgumentError(action, msg)\n\n    # =======================\n    # Help-formatting methods\n    # =======================\n    def format_usage(self):\n        formatter = self._get_formatter()\n        formatter.add_usage(\n            self.usage, self._actions,\n            self._mutually_exclusive_groups,\n        )\n        return formatter.format_help()\n\n    def format_help(self):\n        formatter = self._get_formatter()\n\n        # usage\n        formatter.add_usage(\n            self.usage, self._actions,\n            self._mutually_exclusive_groups,\n        )\n\n        # description\n        formatter.add_text(self.description)\n\n        # positionals, optionals and user-defined groups\n        for action_group in self._action_groups:\n            formatter.start_section(action_group.title)\n            formatter.add_text(action_group.description)\n            formatter.add_arguments(action_group._group_actions)\n            formatter.end_section()\n\n        # epilog\n        formatter.add_text(self.epilog)\n\n        # determine help from format above\n        return formatter.format_help()\n\n    def format_version(self):\n        import warnings\n        warnings.warn(\n            'The format_version method is deprecated -- the \"version\" '\n            'argument to ArgumentParser is no longer supported.',\n            DeprecationWarning,\n        )\n        formatter = self._get_formatter()\n        formatter.add_text(self.version)\n        return formatter.format_help()\n\n    def _get_formatter(self):\n        return self.formatter_class(prog=self.prog)\n\n    # =====================\n    # Help-printing methods\n    # =====================\n    def print_usage(self, file=None):\n        if file is None:\n            file = _sys.stdout\n        self._print_message(self.format_usage(), file)\n\n    def print_help(self, file=None):\n        if file is None:\n            file = _sys.stdout\n        self._print_message(self.format_help(), file)\n\n    def print_version(self, file=None):\n        import warnings\n        warnings.warn(\n            'The print_version method is deprecated -- the \"version\" '\n            'argument to ArgumentParser is no longer supported.',\n            DeprecationWarning,\n        )\n        self._print_message(self.format_version(), file)\n\n    def _print_message(self, message, file=None):\n        if message:\n            if file is None:\n                file = _sys.stderr\n            file.write(message)\n\n    # ===============\n    # Exiting methods\n    # ===============\n    def exit(self, status=0, message=None):\n        if message:\n            self._print_message(message, _sys.stderr)\n        _sys.exit(status)\n\n    def error(self, message):\n        \"\"\"error(message: string)\n\n        Prints a usage message incorporating the message to stderr and\n        exits.\n\n        If you override this in a subclass, it should not return -- it\n        should either exit or raise an exception.\n        \"\"\"\n        self.print_usage(_sys.stderr)\n        self.exit(2, _('%s: error: %s\\n') % (self.prog, message))\n"
  },
  {
    "path": "bin/autojump_data.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport os\nimport shutil\nimport sys\nfrom codecs import open\nfrom collections import namedtuple\nfrom tempfile import NamedTemporaryFile\nfrom time import time\n\nfrom autojump_utils import create_dir\nfrom autojump_utils import is_osx\nfrom autojump_utils import is_python3\nfrom autojump_utils import move_file\nfrom autojump_utils import unico\n\n\nif sys.version_info[0] == 3:\n    ifilter = filter\n    imap = map\nelse:\n    from itertools import ifilter  # noqa\n    from itertools import imap  # noqa\n\n\nBACKUP_THRESHOLD = 24 * 60 * 60\nEntry = namedtuple('Entry', ['path', 'weight'])\n\n\ndef dictify(entries):\n    \"\"\"\n    Converts a list of entries into a dictionary where\n        key = path\n        value = weight\n    \"\"\"\n    result = {}\n    for entry in entries:\n        result[entry.path] = entry.weight\n    return result\n\n\ndef entriefy(data):\n    \"\"\"Converts a dictionary into an iterator of entries.\"\"\"\n    convert = lambda tup: Entry(*tup)\n    if is_python3():\n        return map(convert, data.items())\n    return imap(convert, data.iteritems())\n\n\ndef load(config):\n    \"\"\"Returns a dictonary (key=path, value=weight) loaded from data file.\"\"\"\n    xdg_aj_home = os.path.join(\n        os.path.expanduser('~'),\n        '.local',\n        'share',\n        'autojump',\n    )\n\n    if is_osx() and os.path.exists(xdg_aj_home):\n        migrate_osx_xdg_data(config)\n\n    if not os.path.exists(config['data_path']):\n        return {}\n\n    # example: u'10.0\\t/home/user\\n' -> ['10.0', u'/home/user']\n    parse = lambda line: line.strip().split('\\t')\n\n    correct_length = lambda x: len(x) == 2\n\n    # example: ['10.0', u'/home/user'] -> (u'/home/user', 10.0)\n    tupleize = lambda x: (x[1], float(x[0]))\n\n    try:\n        with open(\n                config['data_path'],\n                'r', encoding='utf-8',\n                errors='replace',\n        ) as f:\n            return dict(\n                imap(\n                    tupleize,\n                    ifilter(correct_length, imap(parse, f)),\n                ),\n            )\n    except (IOError, EOFError):\n        return load_backup(config)\n\n\ndef load_backup(config):\n    if os.path.exists(config['backup_path']):\n        move_file(config['backup_path'], config['data_path'])\n        return load(config)\n    return {}\n\n\ndef migrate_osx_xdg_data(config):\n    \"\"\"\n    Older versions incorrectly used Linux XDG_DATA_HOME paths on OS X. This\n    migrates autojump files from ~/.local/share/autojump to ~/Library/autojump\n    \"\"\"\n    assert is_osx(), 'This function should only be run on OS X.'\n\n    xdg_data_home = os.path.join(os.path.expanduser('~'), '.local', 'share')\n    xdg_aj_home = os.path.join(xdg_data_home, 'autojump')\n    data_path = os.path.join(xdg_aj_home, 'autojump.txt')\n    backup_path = os.path.join(xdg_aj_home, 'autojump.txt.bak')\n\n    if os.path.exists(data_path):\n        move_file(data_path, config['data_path'])\n    if os.path.exists(backup_path):\n        move_file(backup_path, config['backup_path'])\n\n    # cleanup\n    shutil.rmtree(xdg_aj_home)\n    if len(os.listdir(xdg_data_home)) == 0:\n        shutil.rmtree(xdg_data_home)\n\n\ndef save(config, data):\n    \"\"\"Save data and create backup, creating a new data file if necessary.\"\"\"\n    data_dir = os.path.dirname(config['data_path'])\n    create_dir(data_dir)\n\n    # atomically save by writing to temporary file and moving to destination\n    try:\n        temp = NamedTemporaryFile(delete=False, dir=data_dir)\n        # Windows cannot reuse the same open file name\n        temp.close()\n\n        with open(temp.name, 'w', encoding='utf-8', errors='replace') as f:\n            for path, weight in data.items():\n                f.write(unico('%s\\t%s\\n' % (weight, path)))\n\n            f.flush()\n            os.fsync(f)\n    except IOError as ex:\n        print('Error saving autojump data (disk full?)' % ex, file=sys.stderr)\n        sys.exit(1)\n\n    # move temp_file -> autojump.txt\n    move_file(temp.name, config['data_path'])\n\n    # create backup file if it doesn't exist or is older than BACKUP_THRESHOLD\n    if not os.path.exists(config['backup_path']) or \\\n            (time() - os.path.getmtime(config['backup_path']) > BACKUP_THRESHOLD):  # noqa\n        shutil.copy(config['data_path'], config['backup_path'])\n"
  },
  {
    "path": "bin/autojump_match.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport os\nimport re\nfrom difflib import SequenceMatcher\n\nfrom autojump_utils import is_python3\nfrom autojump_utils import last\n\n\nif is_python3():  # pragma: no cover\n    ifilter = filter\n    imap = map\n    os.getcwdu = os.getcwd\nelse:\n    from itertools import ifilter\n    from itertools import imap\n\n\ndef match_anywhere(needles, haystack, ignore_case=False):\n    \"\"\"\n    Matches needles anywhere in the path as long as they're in the same (but\n    not necessary consecutive) order.\n\n    For example:\n        needles = ['foo', 'baz']\n        regex needle = r'.*foo.*baz.*'\n        haystack = [\n            (path='/foo/bar/baz', weight=10),\n            (path='/baz/foo/bar', weight=10),\n            (path='/foo/baz', weight=10),\n        ]\n\n        result = [\n            (path='/moo/foo/baz', weight=10),\n            (path='/foo/baz', weight=10),\n        ]\n    \"\"\"\n    regex_needle = '.*' + '.*'.join(imap(re.escape, needles)) + '.*'\n    regex_flags = re.IGNORECASE | re.UNICODE if ignore_case else re.UNICODE\n    found = lambda haystack: re.search(\n        regex_needle,\n        haystack.path,\n        flags=regex_flags,\n    )\n    return ifilter(found, haystack)\n\n\ndef match_consecutive(needles, haystack, ignore_case=False):\n    \"\"\"\n    Matches consecutive needles at the end of a path.\n\n    For example:\n        needles = ['foo', 'baz']\n        haystack = [\n            (path='/foo/bar/baz', weight=10),\n            (path='/foo/baz/moo', weight=10),\n            (path='/moo/foo/baz', weight=10),\n            (path='/foo/baz', weight=10),\n        ]\n\n        # We can't actually use re.compile because of re.UNICODE\n        regex_needle = re.compile(r'''\n            foo     # needle #1\n            [^/]*   # all characters except os.sep zero or more times\n            /       # os.sep\n            [^/]*   # all characters except os.sep zero or more times\n            baz     # needle #2\n            [^/]*   # all characters except os.sep zero or more times\n            $       # end of string\n            ''')\n\n        result = [\n            (path='/moo/foo/baz', weight=10),\n            (path='/foo/baz', weight=10),\n        ]\n    \"\"\"\n    regex_no_sep = '[^' + os.sep + ']*'\n    regex_no_sep_end = regex_no_sep + '$'\n    regex_one_sep = regex_no_sep + os.sep + regex_no_sep\n    regex_needle = regex_one_sep.join(imap(re.escape, needles)) + regex_no_sep_end\n    regex_flags = re.IGNORECASE | re.UNICODE if ignore_case else re.UNICODE\n    found = lambda entry: re.search(\n        regex_needle,\n        entry.path,\n        flags=regex_flags,\n    )\n    return ifilter(found, haystack)\n\n\ndef match_fuzzy(needles, haystack, ignore_case=False, threshold=0.6):\n    \"\"\"\n    Performs an approximate match with the last needle against the end of\n    every path past an acceptable threshold.\n\n    For example:\n        needles = ['foo', 'bar']\n        haystack = [\n            (path='/foo/bar/baz', weight=11),\n            (path='/foo/baz/moo', weight=10),\n            (path='/moo/foo/baz', weight=10),\n            (path='/foo/baz', weight=10),\n            (path='/foo/bar', weight=10),\n        ]\n\n    result = [\n            (path='/foo/bar/baz', weight=11),\n            (path='/moo/foo/baz', weight=10),\n            (path='/foo/baz', weight=10),\n            (path='/foo/bar', weight=10),\n        ]\n\n    This is a weak heuristic and used as a last resort to find matches.\n    \"\"\"\n    end_dir = lambda path: last(os.path.split(path))\n    if ignore_case:\n        needle = last(needles).lower()\n        match_percent = lambda entry: SequenceMatcher(\n            a=needle,\n            b=end_dir(entry.path.lower()),\n        ).ratio()\n    else:\n        needle = last(needles)\n        match_percent = lambda entry: SequenceMatcher(\n            a=needle,\n            b=end_dir(entry.path),\n        ).ratio()\n    meets_threshold = lambda entry: match_percent(entry) >= threshold\n    return ifilter(meets_threshold, haystack)\n"
  },
  {
    "path": "bin/autojump_utils.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport errno\nimport os\nimport platform\nimport re\nimport shutil\nimport sys\nimport unicodedata\nfrom itertools import islice\n\nif sys.version_info[0] == 3:\n    imap = map\n    os.getcwdu = os.getcwd\nelse:\n    from itertools import imap\n\n\ndef create_dir(path):\n    \"\"\"Creates a directory atomically.\"\"\"\n    try:\n        os.makedirs(path)\n    except OSError as exception:\n        if exception.errno != errno.EEXIST:\n            raise\n\n\ndef encode_local(string):\n    \"\"\"Converts string into user's preferred encoding.\"\"\"\n    if is_python3():\n        return string\n    return string.encode(sys.getfilesystemencoding() or 'utf-8')\n\n\ndef first(xs):\n    it = iter(xs)\n    try:\n        if is_python3():\n            return it.__next__()\n        return it.next()\n    except StopIteration:\n        return None\n\n\ndef get_tab_entry_info(entry, separator):\n    \"\"\"\n    Given a tab entry in the following format return needle, index, and path:\n\n        [needle]__[index]__[path]\n    \"\"\"\n    needle, index, path = None, None, None\n\n    match_needle = re.search(r'(.*?)' + separator, entry)\n    match_index = re.search(separator + r'([0-9]{1})', entry)\n    match_path = re.search(\n        separator + r'[0-9]{1}' + separator + r'(.*)',\n        entry,\n    )\n\n    if match_needle:\n        needle = match_needle.group(1)\n\n    if match_index:\n        index = int(match_index.group(1))\n\n    if match_path:\n        path = match_path.group(1)\n\n    return needle, index, path\n\n\ndef get_pwd():\n    try:\n        return os.getcwdu()\n    except OSError:\n        print('Current directory no longer exists.', file=sys.stderr)\n        raise\n\n\ndef has_uppercase(string):\n    if is_python3():\n        return any(ch.isupper() for ch in string)\n    return any(unicodedata.category(c) == 'Lu' for c in unicode(string))\n\n\ndef in_bash():\n    return 'bash' in os.getenv('SHELL')\n\n\ndef is_autojump_sourced():\n    return '1' == os.getenv('AUTOJUMP_SOURCED')\n\n\ndef is_python2():\n    return sys.version_info[0] == 2\n\n\ndef is_python3():\n    return sys.version_info[0] == 3\n\n\ndef is_linux():\n    return platform.system() == 'Linux'\n\n\ndef is_osx():\n    return platform.system() == 'Darwin'\n\n\ndef is_windows():\n    return platform.system() == 'Windows'\n\n\ndef last(xs):\n    it = iter(xs)\n    tmp = None\n    try:\n        if is_python3():\n            while True:\n                tmp = it.__next__()\n        else:\n            while True:\n                tmp = it.next()\n    except StopIteration:\n        return tmp\n\n\ndef move_file(src, dst):\n    \"\"\"\n    Atomically move file.\n\n    Windows does not allow for atomic file renaming (which is used by\n    os.rename / shutil.move) so destination paths must first be deleted.\n    \"\"\"\n    if is_windows() and os.path.exists(dst):\n        # raises exception if file is in use on Windows\n        os.remove(dst)\n    shutil.move(src, dst)\n\n\ndef print_entry(entry):\n    print_local('%.1f:\\t%s' % (entry.weight, entry.path))\n\n\ndef print_local(string):\n    print(encode_local(string))\n\n\ndef print_tab_menu(needle, tab_entries, separator):\n    \"\"\"\n    Prints the tab completion menu according to the following format:\n\n        [needle]__[index]__[possible_match]\n\n    The needle (search pattern) and index are necessary to recreate the results\n    on subsequent calls.\n    \"\"\"\n    for i, entry in enumerate(tab_entries):\n        print_local(\n            '%s%s%d%s%s' % (\n                needle,\n                separator,\n                i + 1,\n                separator,\n                entry.path,\n            ),\n        )\n\n\ndef sanitize(directories):\n    # edge case to allow '/' as a valid path\n    clean = lambda x: unico(x) if x == os.sep else unico(x).rstrip(os.sep)\n    return list(imap(clean, directories))\n\n\ndef second(xs):\n    it = iter(xs)\n    try:\n        if is_python2():\n            it.next()\n            return it.next()\n        elif is_python3():\n            next(it)\n            return next(it)\n    except StopIteration:\n        return None\n\n\ndef surround_quotes(string):\n    \"\"\"\n    Bash has problems dealing with certain paths so we're surrounding all\n    path outputs with quotes.\n    \"\"\"\n    if in_bash() and string:\n        # Python 2.6 requres field numbers\n        return '\"{0}\"'.format(string)\n    return string\n\n\ndef take(n, iterable):\n    \"\"\"Return first n items of an iterable.\"\"\"\n    return islice(iterable, n)\n\n\ndef unico(string):\n    \"\"\"Converts into Unicode string.\"\"\"\n    if is_python2() and not isinstance(string, unicode):\n        return unicode(string, encoding='utf-8', errors='replace')\n    return string\n"
  },
  {
    "path": "bin/j.bat",
    "content": "@echo off\r\nsetlocal EnableDelayedExpansion\r\n\r\necho %*|>nul findstr /rx \\-.*\r\nif ERRORLEVEL 1 (\r\n  for /f \"delims=\" %%i in ('python \"%~dp0\\autojump\" %*') do set new_path=%%i\r\n  if exist !new_path!\\nul (\r\n    echo !new_path!\r\n    pushd !new_path!\r\n    REM endlocal is necessary so that we can change directory for outside of this script\r\n    REM but will automatically popd. We mush pushd twice to work around this.\r\n    pushd !new_path!\r\n    endlocal\r\n    popd\r\n  ) else (\r\n    echo autojump: directory %* not found\r\n    echo try `autojump --help` for more information\r\n  )\r\n) else (\r\n  python \"%~dp0\\autojump\" %*\r\n)\r\n"
  },
  {
    "path": "bin/jc.bat",
    "content": "@echo off\r\n\r\necho %*|>nul findstr /rx \\-.*\r\nif ERRORLEVEL 1 (\r\n  \"%~dp0\\j.bat\" \"%cd%\" %*\r\n) else (\r\n  python \"%~dp0\\autojump\" %*\r\n)\r\n"
  },
  {
    "path": "bin/jco.bat",
    "content": "@echo off\r\n\r\necho %*|>nul findstr /rx \\-.*\r\nif ERRORLEVEL 1 (\r\n  \"%~dp0\\jc.bat\" \"%cd%\" %*\r\n) else (\r\n  python \"%~dp0\\autojump\" %*\r\n)\r\n"
  },
  {
    "path": "bin/jo.bat",
    "content": "@echo off\r\nsetlocal EnableDelayedExpansion\r\n\r\necho %*|>nul findstr /rx \\-.*\r\nif ERRORLEVEL 1 (\r\n  for /f \"delims=\" %%i in ('python \"%~dp0\\autojump\" %*') do set new_path=%%i\r\n  if exist !new_path!\\nul (\r\n    start \"\" \"explorer\" !new_path!\r\n  ) else (\r\n    echo autojump: directory %* not found\r\n    echo try `autojump --help` for more information\r\n  )\r\n) else (\r\n  python \"%~dp0\\autojump\" %*\r\n)\r\n"
  },
  {
    "path": "docs/autojump.1",
    "content": ".\\\" Automatically generated by Pandoc 1.16.0.2\n.\\\"\n.TH \"autojump\" \"1\" \"2018\\-09\\-09\" \"release\\-v22.5.3\" \"\"\n.hy\n.SS NAME\n.PP\nautojump \\- a faster way to navigate your filesystem\n.SS DESCRIPTION\n.PP\nautojump is a faster way to navigate your filesystem.\nIt works by maintaining a database of the directories you use the most\nfrom the command line.\n.PP\n\\f[I]Directories must be visited first before they can be jumped to.\\f[]\n.SS USAGE\n.PP\n\\f[C]j\\f[] is a convenience wrapper function around \\f[C]autojump\\f[].\nAny option that can be used with \\f[C]autojump\\f[] can be used with\n\\f[C]j\\f[] and vice versa.\n.IP \\[bu] 2\nJump To A Directory That Contains \\f[C]foo\\f[]:\n.RS 2\n.IP\n.nf\n\\f[C]\nj\\ foo\n\\f[]\n.fi\n.RE\n.IP \\[bu] 2\nJump To A Child Directory:\n.RS 2\n.PP\nSometimes it\\[aq]s convenient to jump to a child directory\n(sub\\-directory of current directory) rather than typing out the full\nname.\n.IP\n.nf\n\\f[C]\njc\\ bar\n\\f[]\n.fi\n.RE\n.IP \\[bu] 2\nOpen File Manager To Directories (instead of jumping):\n.RS 2\n.PP\nInstead of jumping to a directory, you can open a file explorer window\n(Mac Finder, Windows Explorer, GNOME Nautilus, etc.) to the directory\ninstead.\n.IP\n.nf\n\\f[C]\njo\\ music\n\\f[]\n.fi\n.PP\nOpening a file manager to a child directory is also supported:\n.IP\n.nf\n\\f[C]\njco\\ images\n\\f[]\n.fi\n.RE\n.IP \\[bu] 2\nUsing Multiple Arguments:\n.RS 2\n.PP\nLet\\[aq]s assume the following database:\n.IP\n.nf\n\\f[C]\n30\\ \\ \\ /home/user/mail/inbox\n10\\ \\ \\ /home/user/work/inbox\n\\f[]\n.fi\n.PP\n\\f[C]j\\ in\\f[] would jump into /home/user/mail/inbox as the higher\nweighted entry.\nHowever you can pass multiple arguments to autojump to prefer a\ndifferent entry.\nIn the above example, \\f[C]j\\ w\\ in\\f[] would then change directory to\n/home/user/work/inbox.\n.RE\n.PP\nFor more options refer to help:\n.IP\n.nf\n\\f[C]\nautojump\\ \\-\\-help\n\\f[]\n.fi\n.SS KNOWN ISSUES\n.IP \\[bu] 2\nautojump does not support directories that begin with \\f[C]\\-\\f[].\n.IP \\[bu] 2\nFor bash users, autojump keeps track of directories by modifying\n\\f[C]$PROMPT_COMMAND\\f[].\nDo not overwrite \\f[C]$PROMPT_COMMAND\\f[]:\n.RS 2\n.IP\n.nf\n\\f[C]\nexport\\ PROMPT_COMMAND=\"history\\ \\-a\"\n\\f[]\n.fi\n.PP\nInstead append to the end of the existing $PROMPT_COMMAND:\n.IP\n.nf\n\\f[C]\nexport\\ PROMPT_COMMAND=\"${PROMPT_COMMAND:+$PROMPT_COMMAND\\ ;}\\ history\\ \\-a\"\n\\f[]\n.fi\n.RE\n.SS REPORTING BUGS\n.PP\nFor any questions or issues please visit:\n.IP\n.nf\n\\f[C]\nhttps://github.com/wting/autojump/issues\n\\f[]\n.fi\n.SS AUTHORS\n.PP\nautojump was originally written by Joël Schaerer, and currently\nmaintained by William Ting.\nMore contributors can be found in \\f[C]AUTHORS\\f[].\n.SS COPYRIGHT\n.PP\nCopyright © 2016 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later\n<http://gnu.org/licenses/gpl.html>.\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\n"
  },
  {
    "path": "docs/body.md",
    "content": "KNOWN ISSUES\n------------\n\n-   autojump does not support directories that begin with `-`.\n\n-   For bash users, autojump keeps track of directories by modifying\n    `$PROMPT_COMMAND`. Do not overwrite `$PROMPT_COMMAND`:\n\n        export PROMPT_COMMAND=\"history -a\"\n\n    Instead append to the end of the existing \\$PROMPT\\_COMMAND:\n\n        export PROMPT_COMMAND=\"${PROMPT_COMMAND:+$PROMPT_COMMAND ;} history -a\"\n\nREPORTING BUGS\n--------------\n\nFor any questions or issues please visit:\n\n    https://github.com/wting/autojump/issues\n\nAUTHORS\n-------\n\nautojump was originally written by Joël Schaerer, and currently maintained by\nWilliam Ting. More contributors can be found in `AUTHORS`.\n\nCOPYRIGHT\n---------\n\nCopyright © 2016 Free Software Foundation, Inc. License GPLv3+: GNU  GPL version\n3 or later <http://gnu.org/licenses/gpl.html>. This is free software: you are\nfree to change and redistribute it. There is NO WARRANTY, to the extent\npermitted by law.\n"
  },
  {
    "path": "docs/header.md",
    "content": "NAME\n----\n\nautojump - a faster way to navigate your filesystem\n\nDESCRIPTION\n-----------\n\nautojump is a faster way to navigate your filesystem. It works by maintaining a\ndatabase of the directories you use the most from the command line.\n\n*Directories must be visited first before they can be jumped to.*\n\nUSAGE\n-----\n\n`j` is a convenience wrapper function around `autojump`. Any option that can\nbe used with `autojump` can be used with `j` and vice versa.\n\n- Jump To A Directory That Contains `foo`:\n\n        j foo\n\n- Jump To A Child Directory:\n\n    Sometimes it's convenient to jump to a child directory (sub-directory of\n    current directory) rather than typing out the full name.\n\n        jc bar\n\n- Open File Manager To Directories (instead of jumping):\n\n    Instead of jumping to a directory, you can open a file explorer window (Mac\n    Finder, Windows Explorer, GNOME Nautilus, etc.) to the directory instead.\n\n        jo music\n\n    Opening a file manager to a child directory is also supported:\n\n        jco images\n\n- Using Multiple Arguments:\n\n    Let's assume the following database:\n\n        30   /home/user/mail/inbox\n        10   /home/user/work/inbox\n\n    `j in` would jump into /home/user/mail/inbox as the higher weighted\n    entry. However you can pass multiple arguments to autojump to prefer\n    a different entry. In the above example, `j w in` would then change\n    directory to /home/user/work/inbox.\n\nFor more options refer to help:\n\n    autojump --help\n"
  },
  {
    "path": "docs/install.md",
    "content": "## INSTALLATION\n\n### REQUIREMENTS\n\n- Python v2.6+ or Python v3.3+\n- Supported shells\n    - bash  - first class support\n    - zsh - first class support\n    - fish - community supported\n    - tcsh - community supported\n    - clink - community supported\n- Supported platforms\n    - Linux - first class support\n    - OS X - first class support\n    - Windows - community supported\n    - BSD - community supported\n- Supported installation methods\n    - source code - first class support\n    - Debian and derivatives - first class support\n    - ArchLinux / Gentoo / openSUSE / RedHat and derivatives - community supported\n    - Homebrew / MacPorts - community supported\n\nDue to limited time and resources, only \"first class support\" items will be\nmaintained by the primary committers. All \"community supported\" items will be\nupdated based on pull requests submitted by the general public.\n\nPlease continue opening issues and providing feedback for community supported\nitems since consolidating information helps other users troubleshoot and submit\nenhancements and fixes.\n\n### MANUAL\n\nGrab a copy of autojump:\n\n    git clone git://github.com/wting/autojump.git\n\nRun the installation script and follow on screen instructions.\n\n    cd autojump\n    ./install.py or ./uninstall.py\n\n### AUTOMATIC\n\n#### Linux\n\nautojump is included in the following distro repositories, please use relevant\npackage management utilities to install (e.g. apt-get, yum, pacman, etc):\n\n- Debian, Ubuntu, Linux Mint\n\n    All Debian-derived distros require manual activation for policy reasons,\n    please see `/usr/share/doc/autojump/README.Debian`.\n\n- RedHat, Fedora, CentOS\n\n    Install `autojump-zsh` for zsh, `autojump-fish` for fish, etc.\n\n- ArchLinux\n- Gentoo\n- Frugalware\n- Slackware\n\n#### OS X\n\nHomebrew is the recommended installation method for Mac OS X:\n\n    brew install autojump\n\nMacPorts is also available:\n\n    port install autojump\n\n## Windows\n\nWindows support is enabled by [clink](https://mridgers.github.io/clink/) which\nshould be installed prior to installing autojump.\n"
  },
  {
    "path": "docs/manpage_header.md",
    "content": "% autojump(1) release-v22.5.3\n%\n% 2018-09-09\n"
  },
  {
    "path": "install.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport os\nimport platform\nimport shutil\nimport sys\n\nsys.path.append('bin')\nfrom autojump_argparse import ArgumentParser  # noqa\n\nSUPPORTED_SHELLS = ('bash', 'zsh', 'fish', 'tcsh')\n\n\ndef cp(src, dest, dryrun=False):\n    print('copying file: %s -> %s' % (src, dest))\n    if not dryrun:\n        shutil.copy(src, dest)\n\n\ndef get_shell():\n    return os.path.basename(os.getenv('SHELL', ''))\n\n\ndef mkdir(path, dryrun=False):\n    print('creating directory:', path)\n    if not dryrun and not os.path.exists(path):\n        os.makedirs(path)\n\n\ndef modify_autojump_sh(etc_dir, share_dir, dryrun=False):\n    \"\"\"Append custom installation path to autojump.sh\"\"\"\n    custom_install = '\\\n        \\n# check custom install \\\n        \\nif [ -s %s/autojump.${shell} ]; then \\\n        \\n    source %s/autojump.${shell} \\\n        \\nfi\\n' % (share_dir, share_dir)\n\n    with open(os.path.join(etc_dir, 'autojump.sh'), 'a') as f:\n        f.write(custom_install)\n\n\ndef modify_autojump_lua(clink_dir, bin_dir, dryrun=False):\n    \"\"\"Prepend custom AUTOJUMP_BIN_DIR definition to autojump.lua\"\"\"\n    custom_install = \"local AUTOJUMP_BIN_DIR = \\\"%s\\\"\\n\" % bin_dir.replace(\n        '\\\\',\n        '\\\\\\\\',\n    )\n    clink_file = os.path.join(clink_dir, 'autojump.lua')\n    with open(clink_file, 'r') as f:\n        original = f.read()\n    with open(clink_file, 'w') as f:\n        f.write(custom_install + original)\n\n\ndef parse_arguments():  # noqa\n    if platform.system() == 'Windows':\n        default_user_destdir = os.path.join(\n            os.getenv('LOCALAPPDATA', ''),\n            'autojump',\n        )\n    else:\n        default_user_destdir = os.path.join(\n            os.path.expanduser('~'),\n            '.autojump',\n        )\n    default_user_prefix = ''\n    default_user_zshshare = 'functions'\n    default_system_destdir = '/'\n    default_system_prefix = '/usr/local'\n    default_system_zshshare = '/usr/share/zsh/site-functions'\n    default_clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink')\n\n    parser = ArgumentParser(\n        description='Installs autojump globally for root users, otherwise \\\n            installs in current user\\'s home directory.'\n    )\n    parser.add_argument(\n        '-n', '--dryrun', action='store_true', default=False,\n        help='simulate installation',\n    )\n    parser.add_argument(\n        '-f', '--force', action='store_true', default=False,\n        help='skip root user, shell type, Python version checks',\n    )\n    parser.add_argument(\n        '-d', '--destdir', metavar='DIR', default=default_user_destdir,\n        help='set destination to DIR',\n    )\n    parser.add_argument(\n        '-p', '--prefix', metavar='DIR', default=default_user_prefix,\n        help='set prefix to DIR',\n    )\n    parser.add_argument(\n        '-z', '--zshshare', metavar='DIR', default=default_user_zshshare,\n        help='set zsh share destination to DIR',\n    )\n    parser.add_argument(\n        '-c', '--clinkdir', metavar='DIR', default=default_clink_dir,\n        help='set clink directory location to DIR (Windows only)',\n    )\n    parser.add_argument(\n        '-s', '--system', action='store_true', default=False,\n        help='install system wide for all users',\n    )\n\n    args = parser.parse_args()\n\n    if not args.force:\n        if sys.version_info[0] == 2 and sys.version_info[1] < 6:\n            print('Python v2.6+ or v3.0+ required.', file=sys.stderr)\n            sys.exit(1)\n        if args.system:\n            if platform.system() == 'Windows':\n                print(\n                    'System-wide installation is not supported on Windows.',\n                    file=sys.stderr,\n                )\n                sys.exit(1)\n            elif os.geteuid() != 0:\n                print(\n                    'Please rerun as root for system-wide installation.',\n                    file=sys.stderr,\n                )\n                sys.exit(1)\n\n        if platform.system() != 'Windows' \\\n                and get_shell() not in SUPPORTED_SHELLS:\n            print(\n                'Unsupported shell: %s' % os.getenv('SHELL'),\n                file=sys.stderr,\n            )\n            sys.exit(1)\n\n    if args.destdir != default_user_destdir \\\n            or args.prefix != default_user_prefix \\\n            or args.zshshare != default_user_zshshare:\n        args.custom_install = True\n    else:\n        args.custom_install = False\n\n    if args.system:\n        if args.custom_install:\n            print(\n                'Custom paths incompatible with --system option.',\n                file=sys.stderr,\n            )\n            sys.exit(1)\n\n        args.destdir = default_system_destdir\n        args.prefix = default_system_prefix\n        args.zshshare = default_system_zshshare\n\n    return args\n\n\ndef show_post_installation_message(etc_dir, share_dir, bin_dir):\n    if platform.system() == 'Windows':\n        print('\\nPlease manually add %s to your user path' % bin_dir)\n    else:\n        if get_shell() == 'fish':\n            aj_shell = '%s/autojump.fish' % share_dir\n            source_msg = 'if test -f %s; . %s; end' % (aj_shell, aj_shell)\n            rcfile = '~/.config/fish/config.fish'\n        else:\n            aj_shell = '%s/autojump.sh' % etc_dir\n            source_msg = '[[ -s %s ]] && source %s' % (aj_shell, aj_shell)\n\n            if platform.system() == 'Darwin' and get_shell() == 'bash':\n                rcfile = '~/.profile'\n            else:\n                rcfile = '~/.%src' % get_shell()\n\n        print('\\nPlease manually add the following line(s) to %s:' % rcfile)\n        print('\\n\\t' + source_msg)\n        if get_shell() == 'zsh':\n            print('\\n\\tautoload -U compinit && compinit -u')\n\n    print('\\nPlease restart terminal(s) before running autojump.\\n')\n\n\ndef main(args):\n    if args.dryrun:\n        print('Installing autojump to %s (DRYRUN)...' % args.destdir)\n    else:\n        print('Installing autojump to %s ...' % args.destdir)\n\n    bin_dir = os.path.join(args.destdir, args.prefix, 'bin')\n    etc_dir = os.path.join(args.destdir, 'etc', 'profile.d')\n    doc_dir = os.path.join(args.destdir, args.prefix, 'share', 'man', 'man1')\n    share_dir = os.path.join(args.destdir, args.prefix, 'share', 'autojump')\n    zshshare_dir = os.path.join(args.destdir, args.zshshare)\n\n    mkdir(bin_dir, args.dryrun)\n    mkdir(doc_dir, args.dryrun)\n    mkdir(etc_dir, args.dryrun)\n    mkdir(share_dir, args.dryrun)\n\n    cp('./bin/autojump', bin_dir, args.dryrun)\n    cp('./bin/autojump_argparse.py', bin_dir, args.dryrun)\n    cp('./bin/autojump_data.py', bin_dir, args.dryrun)\n    cp('./bin/autojump_match.py', bin_dir, args.dryrun)\n    cp('./bin/autojump_utils.py', bin_dir, args.dryrun)\n    cp('./bin/icon.png', share_dir, args.dryrun)\n    cp('./docs/autojump.1', doc_dir, args.dryrun)\n\n    if platform.system() == 'Windows':\n        cp('./bin/autojump.lua', args.clinkdir, args.dryrun)\n        cp('./bin/autojump.bat', bin_dir, args.dryrun)\n        cp('./bin/j.bat', bin_dir, args.dryrun)\n        cp('./bin/jc.bat', bin_dir, args.dryrun)\n        cp('./bin/jo.bat', bin_dir, args.dryrun)\n        cp('./bin/jco.bat', bin_dir, args.dryrun)\n\n        if args.custom_install:\n            modify_autojump_lua(args.clinkdir, bin_dir, args.dryrun)\n    else:\n        mkdir(etc_dir, args.dryrun)\n        mkdir(share_dir, args.dryrun)\n        mkdir(zshshare_dir, args.dryrun)\n\n        cp('./bin/autojump.sh', etc_dir, args.dryrun)\n        cp('./bin/autojump.bash', share_dir, args.dryrun)\n        cp('./bin/autojump.fish', share_dir, args.dryrun)\n        cp('./bin/autojump.zsh', share_dir, args.dryrun)\n        cp('./bin/_j', zshshare_dir, args.dryrun)\n\n        if args.custom_install:\n            modify_autojump_sh(etc_dir, share_dir, args.dryrun)\n\n    show_post_installation_message(etc_dir, share_dir, bin_dir)\n\n\nif __name__ == '__main__':\n    sys.exit(main(parse_arguments()))\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/integration/__init__.py",
    "content": ""
  },
  {
    "path": "tests/unit/__init__.py",
    "content": ""
  },
  {
    "path": "tests/unit/autojump_match_test.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport sys\n\nimport pytest\n\nsys.path.append(os.path.join(os.getcwd(), 'bin'))  # noqa\nfrom autojump_data import Entry\nfrom autojump_match import match_anywhere\nfrom autojump_match import match_consecutive\n\n\nclass TestMatchAnywhere(object):\n\n    entry1 = Entry('/foo/bar/baz', 10)\n    entry2 = Entry('/baz/foo/bar', 10)\n    entry3 = Entry('/foo/baz', 10)\n    entry4 = Entry('/中/zhong/国/guo', 10)\n    entry5 = Entry('/is\\'t/this/a/b*tchin/edge/case?', 10)\n    win_entry1 = Entry('C:\\\\foo\\\\bar\\\\baz', 10)\n    win_entry2 = Entry('D:\\Program Files (x86)\\GIMP', 10)\n    win_entry3 = Entry('C:\\Windows\\System32', 10)\n\n    @pytest.fixture\n    def haystack(self):\n        return [\n            self.entry1,\n            self.entry2,\n            self.entry3,\n            self.entry4,\n            self.entry5,\n        ]\n\n    @pytest.fixture\n    def windows_haystack(self):\n        return [self.win_entry1, self.win_entry2, self.win_entry3]\n\n    def test_single_needle(self, haystack):\n        assert list(match_anywhere(['bar'], haystack)) == [self.entry1, self.entry2]\n\n    def test_consecutive(self, haystack):\n        assert list(match_anywhere(['foo', 'bar'], haystack)) \\\n            == [self.entry1, self.entry2]\n        assert list(match_anywhere(['bar', 'foo'], haystack)) == []\n\n    def test_skip(self, haystack):\n        assert list(match_anywhere(['baz', 'bar'], haystack)) == [self.entry2]\n        assert list(match_anywhere(['中', '国'], haystack)) == [self.entry4]\n\n    def test_ignore_case(self, haystack):\n        assert list(match_anywhere(['bAz', 'bAR'], haystack, ignore_case=True)) \\\n            == [self.entry2]\n\n    def test_backslashes_for_windows_paths(self, windows_haystack):\n        # https://github.com/wting/autojump/issues/281\n        assert list(match_anywhere(['foo', 'baz'], windows_haystack)) \\\n            == [self.win_entry1]\n        assert list(match_anywhere(['program', 'gimp'], windows_haystack, True)) \\\n            == [self.win_entry2]\n        assert list(match_anywhere(['win', '32'], windows_haystack, True)) \\\n            == [self.win_entry3]\n\n    def test_wildcard_in_needle(self, haystack):\n        # https://github.com/wting/autojump/issues/402\n        assert list(match_anywhere(['*', 'this'], haystack)) == []\n        assert list(match_anywhere(['this', '*'], haystack)) == [self.entry5]\n\n\nclass TestMatchConsecutive(object):\n\n    entry1 = Entry('/foo/bar/baz', 10)\n    entry2 = Entry('/baz/foo/bar', 10)\n    entry3 = Entry('/foo/baz', 10)\n    entry4 = Entry('/中/zhong/国/guo', 10)\n    entry5 = Entry('/日/本', 10)\n    entry6 = Entry('/is\\'t/this/a/b*tchin/edge/case?', 10)\n    win_entry1 = Entry('C:\\Foo\\Bar\\Baz', 10)\n    win_entry2 = Entry('D:\\Program Files (x86)\\GIMP', 10)\n    win_entry3 = Entry('C:\\Windows\\System32', 10)\n\n    @pytest.fixture\n    def haystack(self):\n        return [\n            self.entry1,\n            self.entry2,\n            self.entry3,\n            self.entry4,\n            self.entry5,\n        ]\n\n    @pytest.fixture\n    def windows_haystack(self):\n        return [self.win_entry1, self.win_entry2, self.win_entry3]\n\n    def test_single_needle(self, haystack):\n        assert list(match_consecutive(['baz'], haystack)) == [self.entry1, self.entry3]\n        assert list(match_consecutive(['本'], haystack)) == [self.entry5]\n\n    def test_consecutive(self, haystack):\n        assert list(match_consecutive(['bar', 'baz'], haystack)) == [self.entry1]\n        assert list(match_consecutive(['foo', 'bar'], haystack)) == [self.entry2]\n        assert list(match_consecutive(['国', 'guo'], haystack)) == [self.entry4]\n        assert list(match_consecutive(['bar', 'foo'], haystack)) == []\n\n    def test_ignore_case(self, haystack):\n        assert list(match_consecutive(['FoO', 'bAR'], haystack, ignore_case=True)) \\\n            == [self.entry2]\n\n    def test_windows_ignore_case(self, windows_haystack):\n        assert list(match_consecutive(['gimp'], windows_haystack, True)) == [self.win_entry2]\n\n    @pytest.mark.xfail(reason='https://github.com/wting/autojump/issues/418')\n    def test_backslashes_for_windows_paths(self, windows_haystack):\n        assert list(match_consecutive(['program', 'gimp'], windows_haystack, True)) \\\n            == [self.win_entry2]\n\n    @pytest.mark.xfail(reason='https://github.com/wting/autojump/issues/418')\n    def test_foo_bar_baz(self, windows_haystack):\n        assert list(match_consecutive(['bar', 'baz'], windows_haystack, ignore_case=True)) \\\n            == [self.win_entry1]\n\n    @pytest.mark.xfail(reason='https://github.com/wting/autojump/issues/402')\n    def test_thing(self, windows_haystack):\n        assert list(match_consecutive(['win', '32'], windows_haystack, True)) \\\n            == [self.win_entry3]\n\n    @pytest.mark.xfail(reason='https://github.com/wting/autojump/issues/402')\n    def test_wildcard_in_needle(self, haystack):\n        assert list(match_consecutive(['*', 'this'], haystack)) == []\n        assert list(match_consecutive(['*', 'edge', 'case'], haystack)) == [self.entry6]\n"
  },
  {
    "path": "tests/unit/autojump_utils_test.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport sys\n\nimport mock\nimport pytest\n\nsys.path.append(os.path.join(os.getcwd(), 'bin'))  # noqa\nimport autojump_utils\nfrom autojump_utils import encode_local\nfrom autojump_utils import first\nfrom autojump_utils import get_tab_entry_info\nfrom autojump_utils import has_uppercase\nfrom autojump_utils import in_bash\nfrom autojump_utils import is_python3\nfrom autojump_utils import last\nfrom autojump_utils import sanitize\nfrom autojump_utils import second\nfrom autojump_utils import surround_quotes\nfrom autojump_utils import take\nfrom autojump_utils import unico\n\n\nif is_python3():\n    os.getcwdu = os.getcwd\n    xrange = range\n\n\ndef u(string):\n    \"\"\"\n    This is a unicode() wrapper since u'string' is a Python3 compiler error.\n    \"\"\"\n    if is_python3():\n        return string\n    return unicode(string, encoding='utf-8', errors='strict')\n\n\n# strings\n@pytest.mark.skipif(is_python3(), reason='Unicode sucks.')\n@mock.patch.object(sys, 'getfilesystemencoding', return_value='ascii')\ndef test_encode_local_ascii(_):\n    assert encode_local(u('foo')) == b'foo'\n\n\n@pytest.mark.skipif(is_python3(), reason='Unicode sucks.')\n@pytest.mark.xfail(reason='disabled due to pytest bug: https://bitbucket.org/hpk42/pytest/issue/534/pytest-fails-to-catch-unicodedecodeerrors')  # noqa\n@mock.patch.object(sys, 'getfilesystemencoding', return_value='ascii')\ndef test_encode_local_ascii_fails(_):\n    with pytest.raises(UnicodeDecodeError):\n        encode_local(u('日本語'))\n\n\n@pytest.mark.skipif(is_python3(), reason='Unicode sucks.')\n@mock.patch.object(sys, 'getfilesystemencoding', return_value=None)\ndef test_encode_local_empty(_):\n    assert encode_local(b'foo') == u('foo')\n\n\n@pytest.mark.skipif(is_python3(), reason='Unicode sucks.')\n@mock.patch.object(sys, 'getfilesystemencoding', return_value='utf-8')\ndef test_encode_local_unicode(_):\n    assert encode_local(b'foo') == u('foo')\n    assert encode_local(u('foo')) == u('foo')\n\n\ndef test_has_uppercase():\n    assert has_uppercase('Foo')\n    assert has_uppercase('foO')\n    assert not has_uppercase('foo')\n    assert not has_uppercase('')\n\n\n@mock.patch.object(autojump_utils, 'in_bash', return_value=True)\ndef test_surround_quotes_in_bash(_):\n    assert surround_quotes('foo') == '\"foo\"'\n\n\n@mock.patch.object(autojump_utils, 'in_bash', return_value=False)\ndef test_dont_surround_quotes_not_in_bash(_):\n    assert surround_quotes('foo') == 'foo'\n\n\ndef test_sanitize():\n    assert sanitize([]) == []\n    assert sanitize([r'/foo/bar/', r'/']) == [u('/foo/bar'), u('/')]\n\n\n@pytest.mark.skipif(is_python3(), reason='Unicode sucks.')\ndef test_unico():\n    assert unico(str('blah')) == u('blah')\n    assert unico(str('日本語')) == u('日本語')\n    assert unico(u('でもおれは中国人だ。')) == u('でもおれは中国人だ。')\n\n\n# iteration\ndef test_first():\n    assert first(xrange(5)) == 0\n    assert first([]) is None\n\n\ndef test_second():\n    assert second(xrange(5)) == 1\n    assert second([]) is None\n\n\ndef test_last():\n    assert last(xrange(4)) == 3\n    assert last([]) is None\n\n\ndef test_take():\n    assert list(take(1, xrange(3))) == [0]\n    assert list(take(2, xrange(3))) == [0, 1]\n    assert list(take(4, xrange(3))) == [0, 1, 2]\n    assert list(take(10, [])) == []\n\n\n# environment variables\ndef test_in_bash():\n    for path in ['/bin/bash', '/usr/bin/bash']:\n        os.environ['SHELL'] = path\n        assert in_bash()\n\n    for path in ['/bin/zsh', '/usr/bin/zsh']:\n        os.environ['SHELL'] = '/usr/bin/zsh'\n        assert not in_bash()\n\n\n# helper functions\ndef test_get_needle():\n    assert get_tab_entry_info('foo__', '__') == ('foo', None, None)\n\n\ndef test_get_index():\n    assert get_tab_entry_info('foo__2', '__') == ('foo', 2, None)\n\n\ndef test_get_path():\n    assert get_tab_entry_info('foo__3__/foo/bar', '__') \\\n        == ('foo', 3, '/foo/bar')\n\n\ndef test_get_none():\n    assert get_tab_entry_info('gibberish content', '__') == (None, None, None)\n"
  },
  {
    "path": "tools/autojump_ipython.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nIPython autojump magic\n\nWritten by keith hughitt <keith.hughitt@gmail.com>, based on an earlier\nversion by Mario Pastorelli <pastorelli.mario@gmail.com>.\n\nTo install, create a new IPython user profile by running:\n\n    ipython profile create\n\nAnd copy this file into the \"startup\" folder of your new profile (e.g.\n\"$HOME/.config/ipython/profile_default/startup/\").\n\n@TODO: extend %cd to call \"autojump -a\"\n\"\"\"\nfrom subprocess import PIPE\nfrom subprocess import Popen\n\nfrom IPython.core.magic import register_line_magic\n\nip = get_ipython()  # noqa\n\n\n@register_line_magic\ndef j(path):\n    cmd = ['autojump'] + path.split()\n    newpath = Popen(\n        cmd,\n        stdout=PIPE,\n        shell=False,\n    ).communicate()[0].strip()\n\n    if newpath:\n        ip.magic('cd %s' % newpath.decode('utf-8'))\n\n\n# remove from namespace\ndel j\n"
  },
  {
    "path": "tox.ini",
    "content": "[tox]\nenvlist =\n    py26,\n    py27,\n    py33,\n    py34,\n    py35\n# ignore missing setup.py\nskipsdist = True\n\n[testenv]\nsetenv =\n    PYTHONDONTWRITEBYTECODE = 1\ndeps =\n    mock\n    coverage\n    ipdb\n    ipython\n    pytest >= 2.9\ncommands =\n    coverage run --source=bin/ --omit=bin/autojump_argparse.py -m \\\n        py.test -vv -rxs --tb native -s --strict {posargs:tests}\n    coverage report -m\n\n\n[testenv:pre-commit]\ndeps =\n    pre-commit>=0.7.0\ncommands =\n    pre-commit {posargs}\n\n[pytest]\nnorecursedirs = .git .tox docs\n"
  },
  {
    "path": "uninstall.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport os\nimport platform\nimport shutil\nimport sys\n\nsys.path.append('bin')\nfrom autojump_argparse import ArgumentParser  # noqa\n\n\ndef is_empty_dir(path):\n    \"\"\"\n    Checks if any files are present within a directory and all sub-directories.\n    \"\"\"\n    for _, _, files in os.walk(path):\n        if files:\n            return False\n    return True\n\n\ndef parse_arguments():\n    default_clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink')\n\n    parser = ArgumentParser(\n        description='Uninstalls autojump.',\n    )\n    parser.add_argument(\n        '-n', '--dryrun', action='store_true', default=False,\n        help='simulate installation',\n    )\n    parser.add_argument(\n        '-u', '--userdata', action='store_true', default=False,\n        help='delete user data',\n    )\n    parser.add_argument(\n        '-d', '--destdir', metavar='DIR',\n        help='custom destdir',\n    )\n    parser.add_argument(\n        '-p', '--prefix', metavar='DIR', default='',\n        help='custom prefix',\n    )\n    parser.add_argument(\n        '-z', '--zshshare', metavar='DIR', default='functions',\n        help='custom zshshare',\n    )\n    parser.add_argument(\n        '-c', '--clinkdir', metavar='DIR', default=default_clink_dir,\n    )\n\n    return parser.parse_args()\n\n\ndef remove_custom_installation(args, dryrun=False):\n    if not args.destdir:\n        return\n\n    bin_dir = os.path.join(args.destdir, args.prefix, 'bin')\n    doc_dir = os.path.join(args.destdir, args.prefix, 'share', 'man', 'man1')\n    etc_dir = os.path.join(args.destdir, 'etc', 'profile.d')\n    share_dir = os.path.join(args.destdir, args.prefix, 'share', 'autojump')\n    zshshare_dir = os.path.join(args.destdir, args.zshshare)\n\n    if not os.path.exists(share_dir):\n        return\n\n    print('\\nFound custom installation...')\n    rm(os.path.join(bin_dir, 'autojump'), dryrun)\n    rm(os.path.join(bin_dir, 'autojump_data.py'), dryrun)\n    rm(os.path.join(bin_dir, 'autojump_utils.py'), dryrun)\n    rm(os.path.join(bin_dir, 'autojump_argparse.py'), dryrun)\n    if platform.system() == 'Windows':\n        if os.path.exists(args.clinkdir):\n            rm(os.path.join(args.clinkdir, 'autojump.lua'), dryrun)\n        rm(os.path.join(bin_dir, 'autojump.bat'), dryrun)\n        rm(os.path.join(bin_dir, 'j.bat'), dryrun)\n        rm(os.path.join(bin_dir, 'jc.bat'), dryrun)\n        rm(os.path.join(bin_dir, 'jco.bat'), dryrun)\n        rm(os.path.join(bin_dir, 'jo.bat'), dryrun)\n    else:\n        rm(os.path.join(etc_dir, 'autojump.sh'), dryrun)\n        rm(os.path.join(share_dir, 'autojump.bash'), dryrun)\n        rm(os.path.join(share_dir, 'autojump.fish'), dryrun)\n        rm(os.path.join(share_dir, 'autojump.tcsh'), dryrun)\n        rm(os.path.join(share_dir, 'autojump.zsh'), dryrun)\n        rm(os.path.join(zshshare_dir, '_j'), dryrun)\n    rmdir(share_dir, dryrun)\n    rm(os.path.join(doc_dir, 'autojump.1'), dryrun)\n\n    if is_empty_dir(args.destdir):\n        rmdir(args.destdir, dryrun)\n\n\ndef remove_system_installation(dryrun=False):\n    default_destdir = '/'\n    default_prefix = '/usr/local'\n    default_zshshare = '/usr/share/zsh/site-functions'\n\n    bin_dir = os.path.join(default_destdir, default_prefix, 'bin')\n    doc_dir = os.path.join(\n        default_destdir,\n        default_prefix,\n        'share',\n        'man',\n        'man1',\n    )\n    etc_dir = os.path.join(default_destdir, 'etc', 'profile.d')\n    share_dir = os.path.join(\n        default_destdir,\n        default_prefix,\n        'share',\n        'autojump',\n    )\n    zshshare_dir = os.path.join(default_destdir, default_zshshare)\n\n    if not os.path.exists(share_dir):\n        return\n\n    print('\\nFound system installation...')\n\n    if os.geteuid() != 0:\n        print(\n            'Please rerun as root for system-wide uninstall, skipping...',\n            file=sys.stderr,\n        )\n        return\n\n    rm(os.path.join(bin_dir, 'autojump'), dryrun)\n    rm(os.path.join(bin_dir, 'autojump_data.py'), dryrun)\n    rm(os.path.join(bin_dir, 'autojump_utils.py'), dryrun)\n    rm(os.path.join(etc_dir, 'autojump.sh'), dryrun)\n    rm(os.path.join(share_dir, 'autojump.bash'), dryrun)\n    rm(os.path.join(share_dir, 'autojump.fish'), dryrun)\n    rm(os.path.join(share_dir, 'autojump.tcsh'), dryrun)\n    rm(os.path.join(share_dir, 'autojump.zsh'), dryrun)\n    rm(os.path.join(zshshare_dir, '_j'), dryrun)\n    rmdir(share_dir, dryrun)\n    rm(os.path.join(doc_dir, 'autojump.1'), dryrun)\n\n\ndef remove_user_data(dryrun=False):\n    if platform.system() == 'Darwin':\n        data_home = os.path.join(\n            os.path.expanduser('~'),\n            'Library',\n            'autojump',\n        )\n    elif platform.system() == 'Windows':\n        data_home = os.path.join(\n            os.getenv('APPDATA'),\n            'autojump',\n        )\n    else:\n        data_home = os.getenv(\n            'XDG_DATA_HOME',\n            os.path.join(\n                os.path.expanduser('~'),\n                '.local',\n                'share',\n                'autojump',\n            ),\n        )\n\n    if os.path.exists(data_home):\n        print('\\nFound user data...')\n        rmdir(data_home, dryrun)\n\n\ndef remove_user_installation(dryrun=False):\n    if platform.system() == 'Windows':\n        default_destdir = os.path.join(\n            os.getenv('LOCALAPPDATA', ''),\n            'autojump',\n        )\n        clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink')\n    else:\n        default_destdir = os.path.join(os.path.expanduser('~'), '.autojump')\n\n    if os.path.exists(default_destdir):\n        print('\\nFound user installation...')\n        rmdir(default_destdir, dryrun)\n        if platform.system() == 'Windows' and os.path.exists(clink_dir):\n            rm(os.path.join(clink_dir, 'autojump.lua'), dryrun)\n\n\ndef rm(path, dryrun):\n    if os.path.exists(path):\n        print('deleting file:', path)\n        if not dryrun:\n            os.remove(path)\n\n\ndef rmdir(path, dryrun):\n    if os.path.exists(path):\n        print('deleting directory:', path)\n        if not dryrun:\n            shutil.rmtree(path)\n\n\ndef main(args):\n    if args.dryrun:\n        print('Uninstalling autojump (DRYRUN)...')\n    else:\n        print('Uninstalling autojump...')\n\n    remove_user_installation(args.dryrun)\n    remove_system_installation(args.dryrun)\n    remove_custom_installation(args, args.dryrun)\n    if args.userdata:\n        remove_user_data(args.dryrun)\n\n\nif __name__ == '__main__':\n    sys.exit(main(parse_arguments()))\n"
  }
]