├── .github └── workflows │ └── test.yml ├── .gitignore ├── AUTHORS ├── COPYING ├── ChangeLog ├── MANIFEST.in ├── README.rst ├── bin └── cppman ├── cppman ├── __init__.py ├── config.py ├── crawler.py ├── environ.py ├── formatter │ ├── __init__.py │ ├── cplusplus.py │ ├── cppreference.py │ └── tableparser.py ├── lib │ ├── cppman.vim │ ├── index.db │ └── pager.sh ├── main.py └── util.py ├── dev ├── chver.sh ├── control ├── rules └── update_authors.sh ├── misc ├── completions │ ├── cppman.bash │ ├── fish │ │ └── cppman.fish │ └── zsh │ │ └── _cppman └── cppman.1 ├── requirements.txt ├── setup.cfg ├── setup.py ├── test └── test.py └── wiki ├── cppman-1.png ├── cppman-2.png ├── cppman-3.png ├── cppman-4.png ├── cppman-5.png ├── demo.gif └── screenshot.png /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Python CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-24.04 8 | strategy: 9 | matrix: 10 | python-version: ["3.12"] 11 | 12 | steps: 13 | - name: Set up Python ${{ matrix.python-version }} 14 | uses: actions/setup-python@v2 15 | with: 16 | python-version: ${{ matrix.python-version }} 17 | architecture: x64 18 | 19 | - name: Check out repository 20 | uses: actions/checkout@v2 21 | 22 | - name: Upgrade pip and setuptools 23 | run: | 24 | python -m pip install --upgrade pip setuptools 25 | 26 | - name: Install dependencies 27 | run: | 28 | pip install . 29 | 30 | - name: Run tests 31 | run: | 32 | python test/test.py 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .*.swp 2 | *.pyc 3 | build/ 4 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Developers 2 | ---------- 3 | Wei-Ning Huang 4 | 5 | Contributors 6 | ------------ 7 | Alexander 'z33ky' Hirsch <1zeeky@gmail.com> 8 | Brian Foley 9 | ChangZhuo Chen (陳昌倬) 10 | Chris Smith 11 | DSsoto 12 | Gerwin Uittenbogaard 13 | Jakub Wilk 14 | Jan Chren (rindeal) 15 | Jimmy Hu 16 | Jochen Schneider 17 | John Easton 18 | Masanori Misono 19 | Matan Rosenberg 20 | Reverend Homer 21 | Rui Chen 22 | Simon Gene Gottlieb 23 | belkka 24 | glenvt18 25 | taiyu 26 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | ------------------------------------------------------------------------------ 2 | cppman Changelog 3 | ------------------------------------------------------------------------------ 4 | 5 | cppman 0.5.9 (Apr 10th, 2025): 6 | 7 | Features added: 8 | * Present users with a menu of keyword results in multiple hits 9 | * update index.db 10 | 11 | cppman 0.5.7 (Jun 27th, 2024): 12 | 13 | Bug fixed: 14 | * cppreference.com: fix [static], [virtual] 15 | * pager: propoerly fallback to less (#173) 16 | * Properly escape regex string literals 17 | 18 | cppman 0.5.6 (Mar 27th, 2023): 19 | 20 | Bug fixed: 21 | * Default UA blocked by cppreference.com 22 | 23 | cppman 0.5.5 (Mar 24th, 2023): 24 | 25 | Features added: 26 | * Improve crawler reliability. 27 | * Update index.db 28 | 29 | cppman 0.5.4 (Oct 3rd, 2022): 30 | 31 | Features added: 32 | * Update index.db 33 | 34 | cppman 0.5.3 (January 8th, 2021): 35 | 36 | Bug fixed: 37 | * VIM pager re-rendering. 38 | 39 | cppman 0.5.2 (January 5th, 2021): 40 | 41 | Bug fixed: 42 | * Python 3.9 compatibility 43 | * Fix index building 44 | * Fix keyword searching 45 | 46 | cppman 0.5.1 (June 15th, 2020): 47 | 48 | Bug fixed: 49 | * Tones of bug fixed, thanks @SGSSGene, again! 50 | 51 | cppman 0.5.0 (August 18th, 2018): 52 | 53 | Features added: 54 | * index.db update. 55 | * Separate keyword table for better queries. 56 | * Add neovim as pager support 57 | 58 | Bug fixed: 59 | * Tones of bug fixed, thanks @SGSSGene 60 | 61 | cppman 0.4.9 (April 24th, 2016): 62 | 63 | Bug fixed: 64 | * Several bug fixes and parser improvement. 65 | * pager.sh improvements. 66 | * Fix regexp for python 3.7 67 | 68 | cppman 0.4.8 (April 24th, 2016): 69 | 70 | Bug fixed: 71 | * Fix in-vim loading. 72 | * Use html5lib instead of html.parser. 73 | * Fix table parser for certain situation. 74 | * Various bug fixes. 75 | * Unify pager script. 76 | 77 | cppman 0.4.6 (October 8th, 2015): 78 | 79 | Bug fixed: 80 | * Various of bug fix. 81 | 82 | Features add: 83 | * MacOS support 84 | 85 | cppman 0.4.5 (July 1th, 2015): 86 | 87 | Bug fixed: 88 | * Multiple formatting bugs fixed 89 | * Fix typos 90 | 91 | Features add: 92 | * Migrate to Python 3 93 | 94 | cppman 0.4.2 (January 18th, 2015): 95 | 96 | Bug fixed: 97 | * `cache-all` now respect user's selection of source 98 | * fallback to less if vim is not found 99 | 100 | cppman 0.4.1 (October 12th, 2014): 101 | 102 | Bug fixed: 103 | * Minor bug fixes 104 | * Fix empty man pages on some system (MacOS) 105 | * Fix wrong output dev 106 | 107 | cppman 0.4.0 (October 10th, 2014): 108 | 109 | Features added: 110 | * Add cppreference.com backend 111 | 112 | cppman 0.3.1 (November 29th, 2013): 113 | 114 | Bug fixed: 115 | * Minor bug fixes 116 | * Update manpage copyright year 117 | 118 | Features added: 119 | * Allow right click to go back to previous page 120 | * Update README with RST format. 121 | 122 | cppman 0.3.0 (November 15th, 2013): 123 | 124 | Bug fixed: 125 | * Fix various formatting bugs, issue #15, #17 126 | 127 | Features added: 128 | * Update search index (index.db). 129 | * New DOM-based table parser, all table can be rendered correctly. 130 | * Automatically re-render when window is resized. 131 | * Better hyperlink support, implement our own page loader instead of 132 | using VIM's keyword program. 133 | * We can now jump between hyperlinks with mouse double-click 134 | 135 | cppman 0.2.7 (September 25th, 2013): 136 | 137 | Bug fixed: 138 | * Fix prefix bug that still persist in 0.2.6 version 139 | 140 | cppman 0.2.6 (September 24th, 2013): 141 | 142 | Bug fixed: 143 | * Fix prefix when install via easy_install or pip 144 | * Fix formatting bugs 145 | * Add Travis CI test 146 | 147 | cppman 0.2.5 (July 28th, 2013): 148 | 149 | Bug fixed: 150 | * Extra color control characters on some distro 151 | * Misc formatting bugs 152 | * Redirect format error to /dev/null 153 | 154 | cppman 0.2.4 (June 05th, 2013): 155 | 156 | Bug fixed: 157 | * Fix some formatting issue 158 | * Fix typos 159 | 160 | Features added: 161 | * New index crawler, much faster! 162 | * Update index.db 163 | 164 | cppman 0.2.3 (February 13rd, 2013): 165 | 166 | Features added: 167 | * More C++11 support 168 | * Update cplusplus.com index 169 | * Faster crawler (30x improvement) 170 | 171 | cppman 0.2.2 (January 19th, 2013): 172 | 173 | Bug fixed: 174 | * Fix formatting due to the change of cplusplus.com 175 | * Fix syntax highlighting in vim 176 | 177 | Features added: 178 | * Reimplement table converter, now support unlimited column table 179 | generation 180 | 181 | cppman 0.2.0 (September 19th, 2012): 182 | 183 | Bug fixed: 184 | * Fix formatting due to the change of cplusplus.com 185 | 186 | Misc: 187 | * Rename project from manpages-cpp to cppman 188 | 189 | cppman 0.1.9 (April 22nd, 2012): 190 | 191 | Bug fixed: 192 | * Fix formatting due to the change of cplusplus.com 193 | 194 | cppman 0.1.8 (November 29th, 2011): 195 | 196 | Bug fixed: 197 | * Fix formatting due to the change of cplusplus.com 198 | 199 | 200 | cppman 0.1.7 (October 7th, 2011): 201 | 202 | Bug fixed: 203 | * Minor formatting bug 204 | 205 | Features added: 206 | * Pager is now configurable, either 'vim' or 'less' is accepted. 207 | * Integration of mandb is now configurable, default disabled. 208 | 209 | cppman 0.1.6 (April 2nd, 2011): 210 | 211 | Bug fixed: 212 | * Fix formatting due to the change of cplusplus.com 213 | 214 | cppman 0.1.5 (January 31st, 2011): 215 | 216 | Bug fixed: 217 | * Backslashes in EXAMPLE section disappear 218 | * Empty "#include" line in some pages 219 | 220 | Features added: 221 | * Syntax highlighting support for SYNOPSIS and EXAMPLE section 222 | * Update database 223 | 224 | cppman 0.1.3 (September 26th, 2010): 225 | 226 | Features added: 227 | * Add BSD support (Issue #1) 228 | 229 | cppman 0.1.2 (September 21st, 2010): 230 | 231 | Bugs fixed: 232 | * Minor bug fix 233 | 234 | cppman 0.1.1 (September 11st, 2010): 235 | 236 | Bugs fixed: 237 | * Minor bug fix 238 | 239 | Features added: 240 | * Enable mandb support 241 | 242 | cppman 0.1.0 (September 11st, 2010): 243 | 244 | * Initial release 245 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include bin/* 2 | include cppman/* 3 | include cppman/formatter/* 4 | include misc/* 5 | include requirements.txt 6 | include README.rst 7 | include AUTHORS 8 | include COPYING 9 | include ChangeLog 10 | include MANIFEST.in 11 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: http://img.shields.io/pypi/v/cppman.svg?style=flat 2 | :target: https://pypi.python.org/pypi/cppman 3 | .. image:: https://img.shields.io/github/downloads/aitjcize/cppman/total.svg 4 | :target: https://pypi.python.org/pypi/cppman#downloads 5 | 6 | cppman 7 | ====== 8 | C++ 98/11/14/17/20 manual pages for Linux, with source from `cplusplus.com `_ and `cppreference.com `_. 9 | 10 | .. image:: https://raw.github.com/aitjcize/cppman/master/wiki/screenshot.png 11 | 12 | Features 13 | -------- 14 | * Supports two backends (switch it with ``cppman -s``): 15 | 16 | + `cplusplus.com `_ 17 | + `cppreference.com `_ 18 | 19 | * Syntax highlighting support for sections and example source code. 20 | * Usage/Interface similar to the 'man' command 21 | * Hyperlink between manpages (only available when pager=vim) 22 | 23 | + Press ``Ctrl-]`` when cursor is on keyword to go forward and ``Ctrl-T`` to go backward. 24 | + You can also double-click on keyword to go forward and right-click to go backward. 25 | 26 | * Frequently update to support `cplusplus.com `_. 27 | 28 | Demo 29 | ---- 30 | Using vim as pager 31 | 32 | .. image:: https://raw.github.com/aitjcize/cppman/master/wiki/demo.gif 33 | 34 | Installation 35 | ------------ 36 | 1. Install from PyPI: 37 | 38 | .. code-block:: bash 39 | 40 | $ pip install cppman 41 | 42 | Note that cppman requires Python 3. Make sure that either ``pip`` is configured for Python 3 installation, your default Python interpreter is version 3 or just use ``pip3`` instead. 43 | 44 | 2. Arch Linux users can find it on AUR or using `Trizen `_: 45 | 46 | .. code-block:: bash 47 | 48 | $ trizen -S cppman 49 | 50 | or install the git version 51 | 52 | .. code-block:: bash 53 | 54 | $ trizen -S cppman-git 55 | 56 | 3. Debian / Ubuntu: cppman is available in Debian sid/unstable and Ubuntu vivid. 57 | 58 | .. code-block:: bash 59 | 60 | $ sudo apt-get install cppman 61 | 62 | 4. MacOS X: cppman is available in Homebrew and MacPorts. 63 | 64 | .. code-block:: bash 65 | 66 | $ brew install cppman 67 | 68 | or 69 | 70 | .. code-block:: bash 71 | 72 | $ sudo port install cppman 73 | 74 | Package Maintainers 75 | ------------------- 76 | * Arch Linux: myself 77 | * Debian: `czchen `_ 78 | * MacPorts: `eborisch `_ 79 | 80 | FAQ 81 | --- 82 | * Q: Can I use the system ``man`` command instead of ``cppman``? 83 | * A: Yes, just execute ``cppman -m true`` and all cached man pages are exposed to the system ``man`` command. Note: You may want to download all available man pages with ``cppman -c``. 84 | * Q: Why is bash completion is not working properly with ``::``? 85 | * A: It is because bash treats ``:`` like a white space. To fix this add ``export COMP_WORDBREAKS="${COMP_WORDBREAKS//:}"`` to your ``~/.bashrc``. 86 | 87 | Bugs 88 | ---- 89 | * Please report bugs / mis-formatted pages to the github issue tracker. 90 | 91 | Contributing 92 | ------------ 93 | 1. Fork it 94 | 2. Create your feature branch (``git checkout -b my-new-feature``) 95 | 3. Commit your changes (``git commit -am 'Add some feature'``) 96 | 4. Push to the branch (``git push origin my-new-feature``) 97 | 5. Create new Pull Request 98 | 99 | Notes 100 | ----- 101 | * manpages-cpp is renamed to cppman since September 19, 2012 102 | -------------------------------------------------------------------------------- /bin/cppman: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # cppman.py 5 | # 6 | # Copyright (C) 2010 - Wei-Ning Huang (AZ) 7 | # All Rights reserved. 8 | # 9 | # This file is part of cppman. 10 | # 11 | # This program is free software; you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation; either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # 21 | # You should have received a copy of the GNU General Public License 22 | # along with this program; if not, write to the Free Software Foundation, 23 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 24 | # 25 | 26 | 27 | 28 | import os 29 | import sys 30 | from optparse import OptionParser, make_option 31 | 32 | 33 | program = sys.argv[0] 34 | LAUNCH_DIR = os.path.dirname(os.path.abspath(sys.path[0])) 35 | 36 | # If launched from source directory 37 | if program.startswith('./') or program.startswith('bin/'): 38 | sys.path.insert(0, LAUNCH_DIR) 39 | 40 | from cppman.main import Cppman 41 | from cppman.environ import config 42 | from cppman.util import update_mandb_path, update_man3_link 43 | 44 | program_name = sys.argv[0] 45 | program_version = '0.5.9' 46 | 47 | 48 | def version(): 49 | sys.stderr.write( 50 | """%s Ver %s 51 | Copyright (C) 2010 Wei-Ning Huang 52 | License GPLv3+: GNU GPL version 3 or later . 53 | This is free software: you are free to change and redistribute it. 54 | There is NO WARRANTY, to the extent permitted by law.\n 55 | Written by Wei-Ning Huang (AZ) .\n""" 56 | % (program_name, program_version)) 57 | 58 | 59 | def main(): 60 | option_list = [ 61 | make_option('-s', '--source', action='store', dest='source', 62 | help="Select source, either 'cppreference.com' or " 63 | "'cplusplus.com'. Default is 'cppreference.com'."), 64 | make_option('-c', '--cache-all', action='store_true', 65 | dest='cache_all', default=False, 66 | help='Cache all available man pages from cppreference.com ' 67 | 'and cplusplus.com to enable offline browsing.'), 68 | make_option('-C', '--clear-cache', action='store_true', 69 | dest='clear_cache', default=False, 70 | help='Clear all cached files.'), 71 | make_option('-f', '--find-page', action='store', type='string', 72 | dest='keyword', default=None, 73 | help='Find man page.'), 74 | make_option('-o', '--force-update', action='store_true', 75 | dest='force', default=False, 76 | help="Force cppman to update existing cache when " 77 | "'--cache-all' or browsing man pages that were already " 78 | "cached."), 79 | make_option('-m', '--use-mandb', action='store', dest='mandb', 80 | help="Accepts 'true' or 'false'. If true, cppman adds " 81 | "manpage path to mandb so that you can view C++ manpages " 82 | "with `man' command. The default value is 'false'."), 83 | make_option('-p', '--pager', action='store', dest='pager', 84 | help="Select pager to use, accepts 'vim', 'nvim', 'less'" 85 | "or 'system'. 'system' uses $PAGER environment as pager. " 86 | "The default value is 'vim'."), 87 | make_option('-r', '--rebuild-index', action='store_true', 88 | dest='rebuild_index', default=False, 89 | help="rebuild index database for the selected source, " 90 | "either 'cppreference.com' or 'cplusplus.com'."), 91 | make_option('-v', '--version', action='store_true', dest='version', 92 | default=False, help='Show version information.'), 93 | make_option('--force-columns', action='store', dest='force_columns', 94 | type=int, default=-1, help='Force terminal columns.') 95 | ] 96 | 97 | parser = OptionParser( 98 | usage='Usage: cppman [OPTION...] PAGE...', option_list=option_list) 99 | 100 | options, args = parser.parse_args() 101 | 102 | if options.version: 103 | version() 104 | sys.exit(0) 105 | 106 | if options.cache_all: 107 | cm = Cppman(options.force) 108 | cm.cache_all() 109 | sys.exit(0) 110 | 111 | cm = Cppman() 112 | 113 | if options.clear_cache: 114 | cm.clear_cache() 115 | sys.exit(0) 116 | 117 | if options.keyword: 118 | try: 119 | cm.find(options.keyword) 120 | sys.exit(0) 121 | except RuntimeError as e: 122 | print(e, file=sys.stderr) 123 | sys.exit(16) 124 | 125 | if options.source: 126 | if options.source not in config.SOURCES: 127 | raise Exception("invalid value `%s' for option `--source'" % 128 | options.source) 129 | else: 130 | config.Source = options.source 131 | update_man3_link() 132 | print("Source set to `%s'." % options.source) 133 | sys.exit(0) 134 | 135 | if options.pager: 136 | if options.pager not in config.PAGERS: 137 | raise Exception("invalid value `%s' for option `--pager'" % 138 | options.pager) 139 | else: 140 | config.Pager = options.pager 141 | print("Pager set to `%s'." % options.pager) 142 | sys.exit(0) 143 | 144 | if options.mandb: 145 | if options.mandb not in ('true', 'false'): 146 | raise Exception("invalid value `%s' for option `--use-mandb'" % 147 | options.mandb) 148 | config.UpdateManPath = config.parse_bool(options.mandb) 149 | update_mandb_path() 150 | update_man3_link() 151 | sys.exit(0) 152 | 153 | if options.rebuild_index: 154 | cm.rebuild_index() 155 | sys.exit(0) 156 | 157 | if not args or len(args) == 0: 158 | sys.stderr.write('What manual page do you want?\n') 159 | sys.exit(1) 160 | 161 | try: 162 | keyword = cm.fuzzy_find(args[0]) 163 | if not keyword: 164 | sys.exit(1) 165 | 166 | pid = cm.man(keyword) 167 | except RuntimeError as e: 168 | print(e, file=sys.stderr) 169 | sys.exit(16) 170 | else: 171 | os.waitpid(pid, 0) 172 | 173 | if __name__ == '__main__': 174 | try: 175 | main() 176 | except BrokenPipeError: 177 | sys.exit() 178 | except (Exception, KeyboardInterrupt) as e: 179 | if type(e) == KeyboardInterrupt: 180 | print('\nAborted.', file=sys.stderr) 181 | else: 182 | print('error:', e, file=sys.stderr) 183 | -------------------------------------------------------------------------------- /cppman/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # __init__.py 4 | # 5 | # Copyright (C) 2010 - 2015 Wei-Ning Huang (AZ) 6 | # All Rights reserved. 7 | # 8 | # This program is free software; you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation; either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program; if not, write to the Free Software Foundation, 20 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | # 22 | 23 | import os 24 | 25 | package_dir = os.path.dirname(__file__) 26 | 27 | 28 | def get_lib_path(filename): 29 | return os.path.join(package_dir, 'lib', filename) 30 | -------------------------------------------------------------------------------- /cppman/config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # config.py 4 | # 5 | # Copyright (C) 2010 - 2015 Wei-Ning Huang (AZ) 6 | # All Rights reserved. 7 | # 8 | # This file is part of cppman. 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software Foundation, 22 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | 25 | import configparser 26 | import os 27 | 28 | 29 | class Config(object): 30 | PAGERS = ['vim', 'nvim', 'less', 'system'] 31 | SOURCES = ['cplusplus.com', 'cppreference.com'] 32 | 33 | DEFAULTS = { 34 | 'Source': 'cppreference.com', 35 | 'UpdateManPath': 'false', 36 | 'Pager': 'less' 37 | } 38 | 39 | def __init__(self, configfile): 40 | self._configfile = configfile 41 | 42 | if not os.path.exists(configfile): 43 | self.set_default() 44 | else: 45 | self._config = configparser.RawConfigParser() 46 | self._config.read(self._configfile) 47 | 48 | def __getattr__(self, name): 49 | try: 50 | value = self._config.get('Settings', name) 51 | except configparser.NoOptionError: 52 | value = self.DEFAULTS[name] 53 | setattr(self, name, value) 54 | self._config.read(self._configfile) 55 | 56 | return self.parse_bool(value) 57 | 58 | def __setattr__(self, name, value): 59 | if not name.startswith('_'): 60 | self._config.set('Settings', name, value) 61 | self.save() 62 | self.__dict__[name] = self.parse_bool(value) 63 | 64 | def set_default(self): 65 | """Set config to default.""" 66 | try: 67 | os.makedirs(os.path.dirname(self._configfile)) 68 | except: 69 | pass 70 | 71 | self._config = configparser.RawConfigParser() 72 | self._config.add_section('Settings') 73 | 74 | for key, val in self.DEFAULTS.items(): 75 | self._config.set('Settings', key, val) 76 | 77 | with open(self._configfile, 'w') as f: 78 | self._config.write(f) 79 | 80 | def save(self): 81 | """Store config back to file.""" 82 | try: 83 | os.makedirs(os.path.dirname(self._configfile)) 84 | except: 85 | pass 86 | 87 | with open(self._configfile, 'w') as f: 88 | self._config.write(f) 89 | 90 | def parse_bool(self, val): 91 | if type(val) == str: 92 | if val.lower() == 'true': 93 | return True 94 | elif val.lower() == 'false': 95 | return False 96 | return val 97 | -------------------------------------------------------------------------------- /cppman/crawler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # crawler.py 4 | # 5 | # Copyright (C) 2010 - 2016 Wei-Ning Huang (AZ) 6 | # All Rights reserved. 7 | # 8 | # This file is part of cppman. 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software Foundation, 22 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | 25 | from __future__ import print_function 26 | 27 | import re 28 | import sys 29 | import time 30 | from threading import Lock, Thread 31 | from urllib.parse import urljoin, urlparse, urlunparse 32 | import urllib.request 33 | import urllib.error 34 | import http.client 35 | import cppman.util 36 | 37 | from bs4 import BeautifulSoup 38 | 39 | # See https://tools.ietf.org/html/rfc3986#section-3.3 40 | _CONTAINS_DISALLOWED_URL_PCHAR_RE = re.compile('[\x00-\x20\x7f]') 41 | 42 | class NoRedirection(urllib.request.HTTPErrorProcessor): 43 | """A handler that disables redirection""" 44 | def http_response(self, request, response): 45 | if response.code in Crawler.F_REDIRECT_CODES: 46 | return response 47 | return super().http_response(request, response) 48 | 49 | https_response = http_response 50 | 51 | class Crawler(object): 52 | F_ANY, F_SAME_HOST, F_SAME_PATH = list(range(3)) 53 | F_REDIRECT_CODES = (301, 302) 54 | 55 | def __init__(self): 56 | self.queued = set() 57 | self.targets = set() 58 | self.failed_targets = set() 59 | self.max_failed_retries = 3 60 | self.failed_retry = 0 61 | self.downloaded = False 62 | self.threads = [] 63 | self.concurrency = 0 64 | self.max_outstanding = 16 65 | self.max_depth = 0 66 | self.follow_mode = self.F_SAME_HOST 67 | self.content_type_filter = '(text/html)' 68 | self.url_filters = [] 69 | self.prefix_filter = '^(#|javascript:|mailto:)' 70 | 71 | self.targets_lock = Lock() 72 | self.concurrency_lock = Lock() 73 | 74 | def set_content_type_filter(self, cf): 75 | self.content_type_filter = '(%s)' % ('|'.join(cf)) 76 | 77 | def add_url_filter(self, uf): 78 | self.url_filters.append(uf) 79 | 80 | def set_follow_mode(self, mode): 81 | if mode > 2: 82 | raise RuntimeError('invalid follow mode %s.' % mode) 83 | self.follow_mode = mode 84 | 85 | def set_concurrency_level(self, level): 86 | self.max_outstanding = level 87 | 88 | def set_max_depth(self, max_depth): 89 | self.max_depth = max_depth 90 | 91 | def link_parser(self, url, content): 92 | links = re.findall(r'''href\s*=\s*['"]\s*([^'"]+)['"]''', content) 93 | links = [self._fix_link(url, link) for link in links] 94 | return links 95 | 96 | def crawl(self, url, path=None): 97 | self.url = urlparse(url) 98 | if path: 99 | self.url = self.url._replace(path=path) 100 | self.url = self.url._replace(fragment="") 101 | 102 | self.failed_targets = set() 103 | self.downloaded = True 104 | self.failed_retry = self.max_failed_retries 105 | 106 | self._add_target(url, 1) 107 | while True: 108 | self._spawn_new_worker() 109 | 110 | while True: 111 | with self.concurrency_lock: 112 | threads = list(self.threads) 113 | if not threads: 114 | break 115 | try: 116 | for t in threads: 117 | t.join(1) 118 | if not t.is_alive(): 119 | with self.concurrency_lock: 120 | self.threads.remove(t) 121 | except KeyboardInterrupt: 122 | sys.exit(1) 123 | 124 | n_failed = len(self.failed_targets) 125 | if n_failed == 0: 126 | break 127 | if self.downloaded: # at least one URL succeeded 128 | self.failed_retry = self.max_failed_retries 129 | else: 130 | self.failed_retry -= 1 131 | if self.failed_retry <= 0: 132 | print("No retries are left to download failed URLs") 133 | break 134 | print("Some URLs failed to download ({}). Retrying ({})...".format( 135 | n_failed, self.failed_retry)) 136 | self.targets = self.failed_targets 137 | self.failed_targets = set() 138 | self.downloaded = False 139 | time.sleep(2) 140 | 141 | if self.failed_targets: 142 | print("=== Failed URLs ({}):".format(len(self.failed_targets))) 143 | for depth, url in self.failed_targets: 144 | print("{} (depth {})".format(url, depth)) 145 | print("=== Done {}".format(url)) 146 | 147 | def process_document(self, url, content, depth): 148 | """callback to insert index""" 149 | # Should be implemented by a derived class. Make pylint happy 150 | return True 151 | 152 | def _fix_link(self, root, link): 153 | # Encode invalid characters 154 | link = re.sub(_CONTAINS_DISALLOWED_URL_PCHAR_RE, 155 | lambda m: '%{:02X}'.format(ord(m.group())), link.strip()) 156 | link = urlparse(link) 157 | if (link.fragment != ""): 158 | link = link._replace(fragment="") 159 | return urljoin(root, urlunparse(link)) 160 | 161 | def _valid_link(self, link): 162 | if not link: 163 | return False 164 | 165 | link = urlparse(link) 166 | if self.follow_mode == self.F_ANY: 167 | return True 168 | elif self.follow_mode == self.F_SAME_HOST: 169 | return self.url.hostname == link.hostname 170 | elif self.follow_mode == self.F_SAME_PATH: 171 | return self.url.hostname == link.hostname and \ 172 | link.path.startswith(self.url.path) 173 | return False 174 | 175 | def _add_target(self, url, depth): 176 | if not self._valid_link(url): 177 | return 178 | 179 | if self.max_depth and depth > self.max_depth: 180 | return 181 | 182 | with self.targets_lock: 183 | if url in self.queued: 184 | return 185 | self.queued.add(url) 186 | self.targets.add((depth, url)) 187 | 188 | def _target_failed(self, url, depth): 189 | with self.targets_lock: 190 | self.failed_targets.add((depth, url)) 191 | 192 | def _spawn_new_worker(self): 193 | with self.concurrency_lock: 194 | if self.concurrency < self.max_outstanding: 195 | self.concurrency += 1 196 | t = Thread(target=self._worker, args=(self.concurrency,)) 197 | t.daemon = True 198 | self.threads.append(t) 199 | t.start() 200 | 201 | def _worker(self, sid): 202 | while True: 203 | with self.targets_lock: 204 | if not self.targets: 205 | break 206 | depth, url = sorted(self.targets)[0] 207 | self.targets.remove((depth, url)) 208 | 209 | opener = cppman.util.build_opener(NoRedirection) 210 | request_error = None 211 | try: 212 | res = opener.open(url, timeout=10) 213 | with self.targets_lock: 214 | self.downloaded = True 215 | except urllib.error.HTTPError as err: 216 | if err.code == 404: 217 | continue 218 | request_error = err 219 | except Exception as err: 220 | request_error = err 221 | if request_error is not None: 222 | print("URL failed ({}): {}".format(url, request_error)) 223 | self._target_failed(url, depth) 224 | continue 225 | 226 | if res.status in self.F_REDIRECT_CODES: 227 | target = self._fix_link(url, res.getheader('location')) 228 | self._add_target(target, depth+1) 229 | continue 230 | 231 | # Check content type 232 | try: 233 | if not re.search( 234 | self.content_type_filter, 235 | res.getheader('Content-Type')): 236 | continue 237 | except TypeError: # getheader result is None 238 | print("Getting Content-Type failed ({})".format(url)) 239 | continue 240 | 241 | try: 242 | content = res.read().decode() 243 | except http.client.HTTPException as err: 244 | print("Content read() failed ({}): {}".format(url, err)) 245 | self._target_failed(url, depth) 246 | continue 247 | 248 | if self.process_document(url, content, depth): 249 | # Find links in document 250 | links = self.link_parser(url, content) 251 | for link in links: 252 | self._add_target(link, depth+1) 253 | 254 | self._spawn_new_worker() 255 | 256 | with self.concurrency_lock: 257 | self.concurrency -= 1 258 | -------------------------------------------------------------------------------- /cppman/environ.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # environ.py 4 | # 5 | # Copyright (C) 2010 - 2015 Wei-Ning Huang (AZ) 6 | # All Rights reserved. 7 | # 8 | # This file is part of cppman. 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software Foundation, 22 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | 25 | import os 26 | 27 | from cppman import get_lib_path 28 | from cppman.config import Config 29 | 30 | HOME = os.environ["HOME"] 31 | 32 | XDG_CACHE_HOME = os.getenv("XDG_CACHE_HOME", os.path.join(HOME, ".cache")) 33 | XDG_CONFIG_HOME = os.getenv("XDG_CONFIG_HOME", os.path.join(HOME, ".config")) 34 | 35 | cache_dir = os.path.join(XDG_CACHE_HOME, 'cppman') 36 | manindex_dir = os.path.join(cache_dir, 'manindex') 37 | config_dir = os.path.join(XDG_CONFIG_HOME, 'cppman') 38 | config_file = os.path.join(config_dir, 'cppman.cfg') 39 | 40 | config = Config(config_file) 41 | 42 | try: 43 | os.makedirs(cache_dir) 44 | os.makedirs(manindex_dir) 45 | os.makedirs(config_dir) 46 | update_man3_link() 47 | except: 48 | pass 49 | 50 | index_db_re = os.path.join(cache_dir, 'index.db') 51 | 52 | index_db = index_db_re if os.path.exists(index_db_re) \ 53 | else get_lib_path('index.db') 54 | 55 | pager = config.Pager 56 | pager_config = get_lib_path('cppman.vim') 57 | pager_script = get_lib_path('pager.sh') 58 | 59 | source = config.Source 60 | if source not in config.SOURCES: 61 | source = config.SOURCES[0] 62 | config.Source = source 63 | -------------------------------------------------------------------------------- /cppman/formatter/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitjcize/cppman/90ee17da0b2af719db9f1512d202025e2c7ebb9b/cppman/formatter/__init__.py -------------------------------------------------------------------------------- /cppman/formatter/cplusplus.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # formatter.py - format html from cplusplus.com to groff syntax 4 | # 5 | # Copyright (C) 2010 - 2015 Wei-Ning Huang (AZ) 6 | # All Rights reserved. 7 | # 8 | # This file is part of cppman. 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software Foundation, 22 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | 25 | import datetime 26 | import re 27 | 28 | from cppman.formatter.tableparser import parse_table 29 | from cppman.util import fixupHTML, html2man, urlopen 30 | 31 | # Format replacement RE list 32 | # The '.SE' pseudo macro is described in the function: html2groff 33 | pre_rps = [ 34 | # Snippet, ugly hack: we don't want to treat code listing as table 35 | (r'(.*?)
', 36 | r'\n.in +2n\n\1\n.in\n.sp\n', re.S), 37 | ] 38 | 39 | rps = [ 40 | # Header, Name 41 | (r'\s*
]*>(.*?)\s*
\s*' 42 | r'
]*>(.*?)
\s*' 43 | r'

(.*?)

\s*
]*>' 44 | r'(.*?)
\s*
]*>(.*?)
', 45 | r'.TH "\3" 3 "%s" "cplusplus.com" "C++ Programmer\'s Manual"\n' 46 | r'\n.SH "NAME"\n\3 - \5\n' 47 | r'\n.SE\n.SH "TYPE"\n\1\n' 48 | r'\n.SE\n.SH "SYNOPSIS"\n#include \2\n.sp\n\4\n' 49 | r'\n.SE\n.SH "DESCRIPTION"\n' % datetime.date.today(), re.S), 50 | (r'\s*
]*>(.*?)\s*
\s*' 51 | r'
]*>(.*?)
\s*' 52 | r'

(.*?)

\s*' 53 | r'
]*>(.*?)
', 54 | r'.TH "\3" 3 "%s" "cplusplus.com" "C++ Programmer\'s Manual"\n' 55 | r'\n.SH "NAME"\n\3 - \4\n' 56 | r'\n.SE\n.SH "TYPE"\n\1\n' 57 | r'\n.SE\n.SH "SYNOPSIS"\n#include \2\n.sp\n' 58 | r'\n.SE\n.SH "DESCRIPTION"\n' % datetime.date.today(), re.S), 59 | (r'\s*
]*>(.*?)\s*
\s*

(.*?)

\s*' 60 | r'
]*>(.*?)
', 61 | r'.TH "\2" 3 "%s" "cplusplus.com" "C++ Programmer\'s Manual"\n' 62 | r'\n.SH "NAME"\n\2 - \3\n' 63 | r'\n.SE\n.SH "TYPE"\n\1\n' 64 | r'\n.SE\n.SH "DESCRIPTION"\n' % datetime.date.today(), re.S), 65 | (r'\s*
]*>(.*?)\s*
\s*

(.*?)

\s*' 66 | r'
]*>(.*?)
\s*
]*>' 67 | '(.*?)
', 68 | r'.TH "\2" 3 "%s" "cplusplus.com" "C++ Programmer\'s Manual"\n' 69 | r'\n.SH "NAME"\n\2 - \4\n' 70 | r'\n.SE\n.SH "TYPE"\n\1\n' 71 | r'\n.SE\n.SH "DESCRIPTION"\n' % datetime.date.today(), re.S), 72 | (r'\s*
]*>(.*?)\s*
\s*

(.*?)

\s*' 73 | r'
]*>(.*?)
\s*' 74 | r'
]*>(.*?)
', 75 | r'.TH "\2" 3 "%s" "cplusplus.com" "C++ Programmer\'s Manual"\n' 76 | r'\n.SH "NAME"\n\2 - \4\n' 77 | r'\n.SE\n.SH "TYPE"\n\1\n' 78 | r'\n.SE\n.SH "SYNOPSIS"\n\3\n' 79 | r'\n.SE\n.SH "DESCRIPTION"\n' % datetime.date.today(), re.S), 80 | (r']*>', 81 | r' [C++11]', re.S), 82 | # Remove empty #include 83 | (r'#include \n.sp\n', r'', 0), 84 | # Remove empty sections 85 | (r'\n.SH (.+?)\n+.SE', r'', 0), 86 | # Section headers 87 | (r'.*

(.+?)

', r'\n.SE\n.SH "\1"\n', 0), 88 | # 'ul' tag 89 | (r'
    ', r'\n.RS 2\n', 0), 90 | (r'
', r'\n.RE\n.sp\n', 0), 91 | # 'li' tag 92 | (r'
  • \s*(.+?)
  • ', r'\n.IP \[bu] 3\n\1\n', re.S), 93 | # 'pre' tag 94 | (r']*>(.+?)', r'\n.nf\n\1\n.fi\n', re.S), 95 | # Subsections 96 | (r'(.+?):
    ', r'.SS \1\n', 0), 97 | # Member functions / See Also table 98 | # Without C++11 tag 99 | (r'', 101 | r'\n.IP "\1 (3)"\n\2 (\3)\n', re.S), 102 | # With C++11 tag 103 | (r'', 106 | r'\n.IP "\1 (3) [\2]"\n\3 (\4)\n', re.S), 107 | # Footer 108 | (r'
    .*$', 109 | r'\n.SE\n.SH "REFERENCE"\n' 110 | r'cplusplus.com, 2000-2015 - All rights reserved.', re.S), 111 | # C++ version tag 112 | (r']*>', r'.sp\n\1\n', 0), 113 | # 'br' tag 114 | (r'
    ', r'\n.br\n', 0), 115 | (r'\n.br\n.br\n', r'\n.sp\n', 0), 116 | # 'dd' 'dt' tag 117 | (r'
    (.+?)
    \s*
    (.+?)
    ', r'.IP "\1"\n\2\n', re.S), 118 | # Bold 119 | (r'(.+?)', r'\n.B \1\n', 0), 120 | # Remove row number in EXAMPLE 121 | (r'.*?', r'', re.S), 122 | # Any other tags 123 | (r']*>[^<]*', r'', 0), 124 | (r'<.*?>', r'', re.S), 125 | # Misc 126 | (r'<', r'<', 0), 127 | (r'>', r'>', 0), 128 | (r'"', r'"', 0), 129 | (r'&', r'&', 0), 130 | (r' ', r' ', 0), 131 | (r'\\([^\^nE])', r'\\\\\1', 0), 132 | (r'>/">', r'', 0), 133 | (r'/">', r'', 0), 134 | # Remove empty lines 135 | (r'\n\s*\n+', r'\n', 0), 136 | (r'\n\n+', r'\n', 0), 137 | # Preserve \n" in EXAMPLE 138 | (r'\\n', r'\\en', 0), 139 | ] 140 | 141 | 142 | def escape_pre_section(table): 143 | """Escape
     section in table."""
    144 |     def replace_newline(g):
    145 |         return g.group(1).replace('\n', '\n.br\n')
    146 | 
    147 |     return re.sub('(.*?)
    ', replace_newline, table, flags=re.S) 148 | 149 | 150 | def html2groff(data, name): 151 | """Convert HTML text from cplusplus.com to Groff-formatted text.""" 152 | # Remove sidebar 153 | try: 154 | data = data[data.index('
    '):] 155 | except ValueError: 156 | pass 157 | 158 | # Pre replace all 159 | for rp in pre_rps: 160 | data = re.compile(rp[0], rp[2]).sub(rp[1], data) 161 | 162 | for table in re.findall(r'.*?', data, re.S): 163 | tbl = parse_table(escape_pre_section(table)) 164 | # Escape column with '.' as prefix 165 | tbl = re.compile(r'T{\n(\..*?)\nT}', re.S).sub(r'T{\n\\E \1\nT}', tbl) 166 | data = data.replace(table, tbl) 167 | 168 | # Replace all 169 | for rp in rps: 170 | data = re.compile(rp[0], rp[2]).sub(rp[1], data) 171 | 172 | # Upper case all section headers 173 | for st in re.findall(r'.SH .*\n', data): 174 | data = data.replace(st, st.upper()) 175 | 176 | # Add tags to member/inherited member functions 177 | # e.g. insert -> vector::insert 178 | # 179 | # .SE is a pseudo macro I created which means 'SECTION END' 180 | # The reason I use it is because I need a marker to know where section 181 | # ends. 182 | # re.findall find patterns which does not overlap, which means if I do 183 | # this: secs = re.findall(r'\n\.SH "(.+?)"(.+?)\.SH', data, re.S) 184 | # re.findall will skip the later .SH tag and thus skip the later section. 185 | # To fix this, '.SE' is used to mark the end of the section so the next 186 | # '.SH' can be find by re.findall 187 | 188 | page_type = re.search(r'\n\.SH "TYPE"\n(.+?)\n', data) 189 | if page_type and 'class' in page_type.group(1): 190 | class_name = re.search( 191 | r'\n\.SH "NAME"\n(?:.*::)?(.+?) ', data).group(1) 192 | 193 | secs = re.findall(r'\n\.SH "(.+?)"(.+?)\.SE', data, re.S) 194 | 195 | for sec, content in secs: 196 | # Member functions 197 | if ('MEMBER' in sec and 198 | 'NON-MEMBER' not in sec and 199 | 'INHERITED' not in sec and 200 | sec != 'MEMBER TYPES'): 201 | content2 = re.sub(r'\n\.IP "([^:]+?)"', r'\n.IP "%s::\1"' 202 | % class_name, content) 203 | # Replace (constructor) (destructor) 204 | content2 = re.sub(r'\(constructor\)', r'%s' % class_name, 205 | content2) 206 | content2 = re.sub(r'\(destructor\)', r'~%s' % class_name, 207 | content2) 208 | data = data.replace(content, content2) 209 | # Inherited member functions 210 | elif 'MEMBER' in sec and 'INHERITED' in sec: 211 | inherit = re.search(r'.+?INHERITED FROM (.+)', 212 | sec).group(1).lower() 213 | content2 = re.sub(r'\n\.IP "(.+)"', r'\n.IP "%s::\1"' 214 | % inherit, content) 215 | data = data.replace(content, content2) 216 | 217 | # Remove pseudo macro '.SE' 218 | data = data.replace('\n.SE', '') 219 | 220 | return data 221 | 222 | 223 | def func_test(): 224 | """Test if there is major format changes in cplusplus.com""" 225 | ifs = urlopen('http://www.cplusplus.com/printf') 226 | result = html2groff(fixupHTML(ifs.read()), 'printf') 227 | assert '.SH "NAME"' in result 228 | assert '.SH "TYPE"' in result 229 | assert '.SH "DESCRIPTION"' in result 230 | 231 | 232 | def test(): 233 | """Simple Text""" 234 | ifs = urlopen('http://www.cplusplus.com/vector') 235 | print(html2groff(fixupHTML(ifs.read()), 'std::vector'), end=' ') 236 | # with open('test.html') as ifs: 237 | # print html2groff(fixupHTML(ifs.read()), 'std::vector'), 238 | 239 | 240 | if __name__ == '__main__': 241 | test() 242 | -------------------------------------------------------------------------------- /cppman/formatter/cppreference.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # formatter.py - format html from cplusplus.com to groff syntax 4 | # 5 | # Copyright (C) 2010 - 2015 Wei-Ning Huang (AZ) 6 | # All Rights reserved. 7 | # 8 | # This file is part of cppman. 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software Foundation, 22 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | 25 | import datetime 26 | import re 27 | import string 28 | from functools import partial 29 | 30 | from cppman.formatter.tableparser import parse_table 31 | from cppman.util import fixupHTML, html2man, urlopen 32 | 33 | 34 | def member_table_def(g): 35 | tbl = parse_table('%s
    ' % str(g.group(3))) 36 | # Escape column with '.' as prefix 37 | tbl = re.compile(r'T{\n(\..*?)\nT}', re.S).sub(r'T{\n\\E \1\nT}', tbl) 38 | return '\n.IP "%s"\n%s\n%s\n' % (g.group(1), g.group(2), tbl) 39 | 40 | 41 | def member_type_function(g): 42 | if g.group(1).find("', '', g.group(1)).strip() 45 | tail = '' 46 | 47 | spectag = re.search(r'^(.*?)(\[(?:static|virtual)\])(.*)$', head) 48 | if spectag: 49 | head = spectag.group(1).strip() + ' ' + spectag.group(3).strip() 50 | tail = ' ' + spectag.group(2) 51 | 52 | cppvertag = re.search( 53 | r'^(.*?)(\[(?:(?:since|until) )?C\+\+\d+\]\s*(,\s*)?)+$', head) 54 | if cppvertag: 55 | head = cppvertag.group(1).strip() 56 | tail = ' ' + cppvertag.group(2) 57 | 58 | if ',' in head: 59 | head = ', '.join([x.strip() + ' (3)' for x in head.split(',')]) 60 | else: 61 | head = head.strip() + ' (3)' 62 | 63 | full = (head + tail).replace('"', '\\(dq') 64 | return '\n.IP "%s"\n%s\n' % (full, g.group(2)) 65 | 66 | 67 | NAV_BAR_END = '
    .?
    ' 68 | 69 | # Format replacement RE list 70 | # The '.SE' pseudo macro is described in the function: html2groff 71 | rps = [ 72 | # Workaround: remove

    in t-dcl 73 | (r'(.*?)', 74 | lambda g: re.sub('

    ', '', g.group(1)), re.S), 75 | # Header, Name 76 | (r'(.*?)', 77 | r'\n.TH "{{name}}" 3 "%s" "cppreference.com" "C++ Programmer\'s Manual"\n' 78 | r'\n.SH "NAME"\n{{name}} {{shortdesc}}\n.SE\n' % datetime.date.today(), 79 | re.S), 80 | # Defined in header 81 | (r'

    ]*>.*?' + NAV_BAR_END + r'.*?' 82 | r'Defined in header (.*?)(.*?)', 83 | r'\n.SH "SYNOPSIS"\n#include \1\n.sp\n' 84 | r'.nf\n\2\n.fi\n.SE\n' 85 | r'\n.SH "DESCRIPTION"\n', re.S), 86 | (r'
    ]*>.*?' + NAV_BAR_END + 87 | r'(.*?)', 88 | r'\n.SH "SYNOPSIS"\n.nf\n\1\n.fi\n.SE\n' 89 | r'\n.SH "DESCRIPTION"\n', re.S), 90 | # 91 | (r'
    ]*>.*?' + NAV_BAR_END + 92 | r'(.*?)', 93 | r'\n.SH "DESCRIPTION"\n\1\n', re.S), 94 | # access specifiers 95 | (r'
    ]*>.*?' + NAV_BAR_END + 96 | r'(.*?)\s*\([0-9]+\)\s*', r'', 0), 99 | # Section headers 100 | (r'
    .*?

    .*?Inherited from\s*(.*?)\s*

    ', 101 | r'\n.SE\n.IEND\n.IBEGIN \1\n', re.S), 102 | # Remove tags 103 | (r'.*? ?', r'', re.S), 104 | (r'[edit]', r'', re.S), 105 | (r'\[edit\]', r'', re.S), 106 | (r'
    .*?
    ', r'', 0), 107 | (r'
    .*?
    ', r'', 0), 108 | (r'
    ]*>.*?
    ', r'', re.S), 109 | (r']*>.*?', r'', re.S), 110 | (r'
    .*?
    ', r'', re.S), 111 | (r'.*?', r'', re.S), 112 | # C++11/14/17/20 113 | (r'\(((?:since|until) C\+\+\d+)\)', r' [\1]', re.S), 114 | (r'\((C\+\+\d+)\)', r' [\1]', re.S), 115 | # Subsections 116 | (r']*>\s*(.*)', r'\n.SS "\1"\n', 0), 117 | # Group t-lines 118 | (r'', r'', re.S), 119 | (r'(?:.+?.*)+', 120 | lambda x: re.sub(r'\s*\s*', r', ', x.group(0)), re.S), 121 | # Member type & function second col is group see basic_fstream for example 122 | (r'\s*?((?:(?!).)*?)\s*?' 123 | r'((?:(?!).)*?)]*>((?:(?!).)*?)' 124 | r'(?:(?!).)*?\s*?', 125 | member_table_def, re.S), 126 | # Section headers 127 | (r'.*

    (.+?)

    ', r'\n.SE\n.SH "\1"\n', 0), 128 | # Member type & function 129 | (r'\n?\s*(.*?)\n?.*?\s*(.*?).*?', 130 | member_type_function, re.S), 131 | # Parameters 132 | (r'.*?\s*(.*?)\n?.*?.*?.*?' 133 | r'\s*(.*?).*?', 134 | r'\n.IP "\1"\n\2\n', re.S), 135 | # 'ul' tag 136 | (r'
      ', r'\n.RS 2\n', 0), 137 | (r'
    ', r'\n.RE\n.sp\n', 0), 138 | # 'li' tag 139 | (r'
  • \s*(.+?)
  • ', r'\n.IP \[bu] 3\n\1\n', re.S), 140 | # 'pre' tag 141 | (r']*>(.+?)', r'\n.in +2n\n.nf\n\1\n.fi\n.in\n', re.S), 142 | # Footer 143 | (r'
    ', 144 | r'\n.SE\n.IEND\n.SH "REFERENCE"\n' 145 | r'cppreference.com, 2015 - All rights reserved.', re.S), 146 | # C++ version tag 147 | (r'
    ]*>', r'.sp\n\1\n', 0), 148 | # Output 149 | (r'

    Output:\n?

    ', r'\n.sp\nOutput:\n', re.S), 150 | # Paragraph 151 | (r'

    (.*?)

    ', r'\n\1\n.sp\n', re.S), 152 | (r'
    (.*?)
    ', r'\n\1\n.sp\n', re.S), 153 | (r'
    (.*?)
    ', 154 | r'\n.RS\n\1\n.RE\n.sp\n', re.S), 155 | # 'br' tag 156 | (r'
    ', r'\n.br\n', 0), 157 | (r'\n.br\n.br\n', r'\n.sp\n', 0), 158 | # 'dd' 'dt' tag 159 | (r'
    (.+?)
    \s*
    (.+?)
    ', r'\n.IP "\1"\n\2\n', re.S), 160 | # Bold 161 | (r'(.+?)', r'\n.B \1\n', 0), 162 | # Any other tags 163 | (r']*>[^<]*', r'', 0), 164 | (r'<.*?>', r'', re.S), 165 | # Escape 166 | (r'^#', r'\#', 0), 167 | (r' ', ' ', 0), 168 | (r'&#(\d+);', lambda g: chr(int(g.group(1))), 0), 169 | # Misc 170 | (r'<', r'<', 0), 171 | (r'>', r'>', 0), 172 | (r'"', r'"', 0), 173 | (r'&', r'&', 0), 174 | (r' ', r' ', 0), 175 | (r'\\([^\^nE])', r'\\\\\1', 0), 176 | (r'>/">', r'', 0), 177 | (r'/">', r'', 0), 178 | # Remove empty sections 179 | (r'\n.SH (.+?)\n+.SE', r'', 0), 180 | # Remove empty lines 181 | (r'\n\s*\n+', r'\n', 0), 182 | (r'\n\n+', r'\n', 0), 183 | # Preserve \n" in EXAMPLE 184 | (r'\\n', r'\\en', 0), 185 | # Remove leading whitespace 186 | (r'^\s+', r'', re.S), 187 | # Trailing white-spaces 188 | (r'\s+\n', r'\n', re.S), 189 | # Remove extra whitespace and newline in .SH/SS/IP section 190 | (r'.(SH|SS|IP) "\s*(.*?)\s*\n?"', r'.\1 "\2"', 0), 191 | # Remove extra whitespace before .IP bullet 192 | (r'(.IP \\\\\[bu\] 3)\n\s*(.*?)\n', r'\1\n\2\n', 0), 193 | # Remove extra '\n' before C++ version Tag (don't do it in table) 194 | (r'(?'):] 203 | data = data[:data.index('
    ') + 25] 204 | except ValueError: 205 | pass 206 | 207 | # Remove non-printable characters 208 | data = ''.join([x for x in data if x in string.printable]) 209 | 210 | for table in re.findall( 211 | r']*>.*?
    ', 212 | data, re.S): 213 | tbl = parse_table(table) 214 | # Escape column with '.' as prefix 215 | tbl = re.compile(r'T{\n(\..*?)\nT}', re.S).sub(r'T{\n\\E \1\nT}', tbl) 216 | data = data.replace(table, tbl) 217 | 218 | # Pre replace all 219 | for rp in rps: 220 | data = re.compile(rp[0], rp[2]).sub(rp[1], data) 221 | 222 | # Remove non-printable characters 223 | data = ''.join([x for x in data if x in string.printable]) 224 | 225 | # Upper case all section headers 226 | for st in re.findall(r'.SH .*\n', data): 227 | data = data.replace(st, st.upper()) 228 | 229 | # Add tags to member/inherited member functions 230 | # e.g. insert -> vector::insert 231 | # 232 | # .SE is a pseudo macro I created which means 'SECTION END' 233 | # The reason I use it is because I need a marker to know where section 234 | # ends. 235 | # re.findall find patterns which does not overlap, which means if I do 236 | # this: secs = re.findall(r'\n\.SH "(.+?)"(.+?)\.SH', data, re.S) 237 | # re.findall will skip the later .SH tag and thus skip the later section. 238 | # To fix this, '.SE' is used to mark the end of the section so the next 239 | # '.SH' can be find by re.findall 240 | 241 | try: 242 | idx = data.index('.IEND') 243 | except ValueError: 244 | idx = None 245 | 246 | def add_header_multi(prefix, g): 247 | if ',' in g.group(1): 248 | res = ', '.join(['%s::%s' % (prefix, x.strip()) 249 | for x in g.group(1).split(',')]) 250 | else: 251 | res = '%s::%s' % (prefix, g.group(1)) 252 | 253 | return '\n.IP "%s"' % res 254 | 255 | if idx: 256 | class_name = name 257 | if class_name.startswith('std::'): 258 | normalized_class_name = class_name[len('std::'):] 259 | else: 260 | normalized_class_name = class_name 261 | class_member_content = data[:idx] 262 | secs = re.findall(r'\.SH "(.+?)"(.+?)\.SE', class_member_content, re.S) 263 | 264 | for sec, content in secs: 265 | # Member functions 266 | if (('MEMBER' in sec and 267 | 'NON-MEMBER' not in sec and 268 | 'INHERITED' not in sec and 269 | 'MEMBER TYPES' != sec) or 270 | 'CONSTANTS' == sec): 271 | content2 = re.sub(r'\n\.IP "([^:]+?)"', 272 | partial(add_header_multi, class_name), 273 | content) 274 | # Replace (constructor) (destructor) 275 | content2 = re.sub(r'\(constructor\)', r'%s' % 276 | normalized_class_name, content2) 277 | content2 = re.sub(r'\(destructor\)', r'~%s' % 278 | normalized_class_name, content2) 279 | data = data.replace(content, content2) 280 | 281 | blocks = re.findall(r'\.IBEGIN\s*(.+?)\s*\n(.+?)\.IEND', data, re.S) 282 | 283 | for inherited_class, content in blocks: 284 | content2 = re.sub(r'\.SH "(.+?)"', r'\n.SH "\1 INHERITED FROM %s"' 285 | % inherited_class.upper(), content) 286 | data = data.replace(content, content2) 287 | 288 | secs = re.findall(r'\.SH "(.+?)"(.+?)\.SE', content, re.S) 289 | 290 | for sec, content in secs: 291 | # Inherited member functions 292 | if 'MEMBER' in sec and \ 293 | sec != 'MEMBER TYPES': 294 | content2 = re.sub(r'\n\.IP "(.+)"', 295 | partial(add_header_multi, inherited_class), 296 | content) 297 | data = data.replace(content, content2) 298 | 299 | # Remove unneeded pseudo macro 300 | data = re.sub('(?:\n.SE|.IBEGIN.*?\n|\n.IEND)', '', data) 301 | 302 | # Replace all macros 303 | desc_re = re.search(r'.SH "DESCRIPTION"\n.*?([^\n\s].*?)\n', data) 304 | shortdesc = '' 305 | 306 | # not empty description 307 | if desc_re and not desc_re.group(1).startswith('.SH'): 308 | shortdesc = '- ' + desc_re.group(1) 309 | 310 | def dereference(g): 311 | d = dict(name=name, shortdesc=shortdesc) 312 | if g.group(1) in d: 313 | return d[g.group(1)] 314 | 315 | data = re.sub('{{(.*?)}}', dereference, data) 316 | 317 | return data 318 | 319 | 320 | def func_test(): 321 | """Test if there is major format changes in cplusplus.com""" 322 | ifs = urlopen('http://en.cppreference.com/w/cpp/container/vector') 323 | result = html2groff(fixupHTML(ifs.read()), 'std::vector') 324 | assert '.SH "NAME"' in result 325 | assert '.SH "SYNOPSIS"' in result 326 | assert '.SH "DESCRIPTION"' in result 327 | 328 | 329 | def test(): 330 | """Simple Text""" 331 | ifs = urlopen('http://en.cppreference.com/w/cpp/container/vector') 332 | print(html2groff(fixupHTML(ifs.read()), 'std::vector'), end=' ') 333 | # with open('test.html') as ifs: 334 | # data = fixupHTML(ifs.read()) 335 | # print html2groff(data, 'std::vector'), 336 | 337 | 338 | if __name__ == '__main__': 339 | test() 340 | -------------------------------------------------------------------------------- /cppman/formatter/tableparser.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # tableparser.py - format html from cplusplus.com to groff syntax 4 | # 5 | # Copyright (C) 2010 - 2015 Wei-Ning Huang (AZ) 6 | # All Rights reserved. 7 | # 8 | # This file is part of cppman. 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software Foundation, 22 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | 25 | import io 26 | import platform 27 | import re 28 | 29 | NODE = re.compile(r'<\s*([^/]\w*)\s?(.*?)>(.*?)<\s*/\1.*?>', re.S) 30 | ATTR = re.compile(r'\s*(\w+?)\s*=\s*([\'"])((?:\\.|(?!\2).)*)\2') 31 | 32 | 33 | class Node(object): 34 | def __init__(self, parent, name, attr_list, body): 35 | self.parent = parent 36 | self.name = name 37 | self.body = body 38 | self.attr = dict((x[0], x[2]) for x in ATTR.findall(attr_list)) 39 | 40 | if self.name in ['th', 'td']: 41 | self.text = self.strip_tags(self.body) 42 | self.children = [] 43 | else: 44 | self.text = '' 45 | self.children = [Node(self, *g) for g in NODE.findall(self.body)] 46 | 47 | def __repr__(self): 48 | return "" % self.name 49 | 50 | def strip_tags(self, html): 51 | if type(html) != str: 52 | html = html.group(3) 53 | return NODE.sub(self.strip_tags, html) 54 | 55 | def traverse(self, depth=0): 56 | print('%s%s: %s %s' % (' ' * depth, self.name, self.attr, self.text)) 57 | 58 | for c in self.children: 59 | c.traverse(depth + 2) 60 | 61 | def get_row_width(self): 62 | total = 0 63 | assert self.name == 'tr' 64 | for c in self.children: 65 | if 'colspan' in c.attr: 66 | total += int(c.attr['colspan']) 67 | else: 68 | total += 1 69 | return total 70 | 71 | def scan_format(self, index=0, width=0, rowspan=None): 72 | if rowspan is None: 73 | rowspan = {} 74 | 75 | format_str = '' 76 | 77 | expand_char = 'x' if platform.system() != 'Darwin' else '' 78 | 79 | if self.name in ['th', 'td']: 80 | extend = ((width == 3 and index == 1) or 81 | (width != 3 and width < 5 and index == width - 1)) 82 | 83 | if self.name == 'th': 84 | format_str += 'c%s ' % (expand_char if extend else '') 85 | else: 86 | format_str += 'l%s ' % (expand_char if extend else '') 87 | 88 | if 'colspan' in self.attr: 89 | for i in range(int(self.attr['colspan']) - 1): 90 | format_str += 's ' 91 | 92 | if 'rowspan' in self.attr and int(self.attr['rowspan']) > 1: 93 | rowspan[index] = int(self.attr['rowspan']) - 1 94 | 95 | if self.name == 'tr' and len(rowspan) > 0: 96 | ci = 0 97 | for i in range(width): 98 | if i in rowspan: 99 | format_str += '^ ' 100 | if rowspan[i] == 1: 101 | del rowspan[i] 102 | else: 103 | rowspan[i] -= 1 104 | else: 105 | # There is a row span, but the current number of column is 106 | # not enough. Pad empty node when this happens. 107 | if ci >= len(self.children): 108 | self.children.append(Node(self, 'td', '', '')) 109 | 110 | format_str += self.children[ci].scan_format(i, width, 111 | rowspan) 112 | ci += 1 113 | else: 114 | if self.children and self.children[0].name == 'tr': 115 | width = self.children[0].get_row_width() 116 | 117 | for i, c in enumerate(self.children): 118 | format_str += c.scan_format(i, width, rowspan) 119 | 120 | if self.name == 'table': 121 | format_str += '.\n' 122 | elif self.name == 'tr': 123 | format_str += '\n' 124 | 125 | return format_str 126 | 127 | def gen(self, fd, index=0, last=False, rowspan=None): 128 | if rowspan is None: 129 | rowspan = {} 130 | 131 | if self.name == 'table': 132 | fd.write('.TS\n') 133 | fd.write('allbox tab(|);\n') 134 | fd.write(self.scan_format()) 135 | elif self.name in ['th', 'td']: 136 | fd.write('T{\n%s' % self.text) 137 | if 'rowspan' in self.attr and int(self.attr['rowspan']) > 1: 138 | rowspan[index] = int(self.attr['rowspan']) - 1 139 | else: 140 | fd.write(self.text) 141 | 142 | if self.name == 'tr' and len(rowspan) > 0: 143 | total = len(rowspan) + len(self.children) 144 | ci = 0 145 | for i in range(total): 146 | if i in rowspan: 147 | fd.write(r'\^%s' % ('|' if i < total - 1 else '')) 148 | if rowspan[i] == 1: 149 | del rowspan[i] 150 | else: 151 | rowspan[i] -= 1 152 | else: 153 | # There is a row span, but the current number of column is 154 | # not enough. Pad empty node when this happens. 155 | if ci >= len(self.children): 156 | self.children.append(Node(self, 'td', '', '')) 157 | 158 | self.children[ci].gen(fd, i, i == total - 1, rowspan) 159 | ci += 1 160 | else: 161 | for i, c in enumerate(self.children): 162 | c.gen(fd, i, i == len(self.children) - 1, rowspan) 163 | 164 | if self.name == 'table': 165 | fd.write('.TE\n') 166 | fd.write('.sp\n.sp\n') 167 | elif self.name == 'tr': 168 | fd.write('\n') 169 | elif self.name in ['th', 'td']: 170 | fd.write('\nT}%s' % ('|' if not last else '')) 171 | 172 | 173 | def parse_table(html): 174 | root = Node(None, 'root', '', html) 175 | fd = io.StringIO() 176 | root.gen(fd) 177 | return fd.getvalue() 178 | -------------------------------------------------------------------------------- /cppman/lib/cppman.vim: -------------------------------------------------------------------------------- 1 | " cppman.vim 2 | " 3 | " Copyright (C) 2010 - Wei-Ning Huang (AZ) 4 | " All Rights reserved. 5 | " 6 | " This program is free software; you can redistribute it and/or modify 7 | " it under the terms of the GNU General Public License as published by 8 | " the Free Software Foundation; either version 3 of the License, or 9 | " (at your option) any later version. 10 | " 11 | " This program is distributed in the hope that it will be useful, 12 | " but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | " GNU General Public License for more details. 15 | " 16 | " You should have received a copy of the GNU General Public License 17 | " along with this program; if not, write to the Free Software Foundation, 18 | " Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | " 20 | " 21 | " Vim syntax file 22 | " Language: Man page 23 | " Maintainer: SungHyun Nam 24 | " Modified: Wei-Ning Huang 25 | " Previous Maintainer: Gautam H. Mudunuri 26 | " Version Info: 27 | " Last Change: 2008 Sep 17 28 | 29 | " Additional highlighting by Johannes Tanzler : 30 | " * manSubHeading 31 | " * manSynopsis (only for sections 2 and 3) 32 | 33 | " For version 5.x: Clear all syntax items 34 | " For version 6.x: Quit when a syntax file was already loaded 35 | 36 | setl nonu 37 | setl nornu 38 | setl noma 39 | setl keywordprg=cppman 40 | setl buftype=nofile 41 | noremap q :q! 42 | 43 | if version < 600 44 | syntax clear 45 | elseif exists("b:current_syntax") 46 | finish 47 | endif 48 | 49 | syntax on 50 | syntax case ignore 51 | syntax match manReference "[a-z_:+-\*][a-z_:+-~!\*<>()]\+ ([1-9][a-z]\=)" 52 | syntax match manTitle "^\w.\+([0-9]\+[a-z]\=).*" 53 | syntax match manSectionHeading "^[a-z][a-z_ \-:]*[a-z]$" 54 | syntax match manSubHeading "^\s\{3\}[a-z][a-z ]*[a-z]$" 55 | syntax match manOptionDesc "^\s*[+-][a-z0-9]\S*" 56 | syntax match manLongOptionDesc "^\s*--[a-z0-9-]\S*" 57 | 58 | syntax include @cppCode runtime! syntax/cpp.vim 59 | syntax match manCFuncDefinition display "\<\h\w*\>\s*("me=e-1 contained 60 | 61 | syntax region manSynopsis start="^SYNOPSIS"hs=s+8 end="^\u\+\s*$"me=e-12 keepend contains=manSectionHeading,@cppCode,manCFuncDefinition 62 | syntax region manSynopsis start="^EXAMPLE"hs=s+7 end="^ [^ ]"he=s-1 keepend contains=manSectionHeading,@cppCode,manCFuncDefinition 63 | 64 | " Define the default highlighting. 65 | " For version 5.7 and earlier: only when not done already 66 | " For version 5.8 and later: only when an item doesn't have highlighting yet 67 | if version >= 508 || !exists("did_man_syn_inits") 68 | if version < 508 69 | let did_man_syn_inits = 1 70 | command -nargs=+ HiLink hi link 71 | else 72 | command -nargs=+ HiLink hi def link 73 | endif 74 | 75 | HiLink manTitle Title 76 | HiLink manSectionHeading Statement 77 | HiLink manOptionDesc Constant 78 | HiLink manLongOptionDesc Constant 79 | HiLink manReference PreProc 80 | HiLink manSubHeading Function 81 | HiLink manCFuncDefinition Function 82 | 83 | delcommand HiLink 84 | endif 85 | 86 | """ Vim Viewer 87 | setl mouse=a 88 | setl colorcolumn=0 89 | 90 | let s:old_col = &co 91 | 92 | function s:reload() 93 | setl noro 94 | setl ma 95 | echo "Loading..." 96 | exec "%d" 97 | exec "0r! cppman --force-columns " . (&co - 2) . " '" . g:page_name . "'" 98 | setl ro 99 | setl noma 100 | setl nomod 101 | endfunction 102 | 103 | function Rerender() 104 | if &co != s:old_col 105 | let s:old_col = &co 106 | let save_cursor = getpos(".") 107 | call s:reload() 108 | call setpos('.', save_cursor) 109 | end 110 | endfunction 111 | 112 | autocmd VimResized * call Rerender() 113 | 114 | let g:stack = [] 115 | 116 | function LoadNewPage() 117 | " Save current page to stack 118 | call add(g:stack, [g:page_name, getpos(".")]) 119 | let g:page_name = expand("") 120 | setl noro 121 | setl ma 122 | call s:reload() 123 | normal! gg 124 | setl ro 125 | setl noma 126 | setl nomod 127 | endfunction 128 | 129 | function BackToPrevPage() 130 | if len(g:stack) > 0 131 | let context = g:stack[-1] 132 | call remove(g:stack, -1) 133 | let g:page_name = context[0] 134 | call s:reload() 135 | call setpos('.', context[1]) 136 | end 137 | endfunction 138 | 139 | noremap K :call LoadNewPage() 140 | map K 141 | map K 142 | map <2-LeftMouse> K 143 | 144 | noremap :call BackToPrevPage() 145 | map 146 | 147 | let b:current_syntax = "man" 148 | -------------------------------------------------------------------------------- /cppman/lib/index.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitjcize/cppman/90ee17da0b2af719db9f1512d202025e2c7ebb9b/cppman/lib/index.db -------------------------------------------------------------------------------- /cppman/lib/pager.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # pager.sh 4 | # 5 | # Copyright (C) 2010 - 2016 Wei-Ning Huang (AZ) 6 | # All Rights reserved. 7 | # 8 | # This file is part of cppman. 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software Foundation, 22 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | 25 | # Script arguments: 26 | # $1: pager type 27 | # $2: page path 28 | # $3: column 29 | # $4: vim config 30 | # $5: page name 31 | 32 | get_dev_type() { 33 | local dev=ascii 34 | local var 35 | for var in $LC_ALL $LANG; do 36 | if [ -n "$(printf "%s" "${var}" | sed 's/-//g' | grep -i utf8)" ]; then 37 | dev=utf8 38 | break 39 | fi 40 | done 41 | printf "%s" "${dev}" 42 | } 43 | 44 | output_dev=$(get_dev_type) 45 | 46 | pager_type=$1 47 | page_path=$2 48 | col=$3 49 | vim_config=$4 50 | page_name=$5 51 | 52 | render() { 53 | gunzip -c "$page_path" | \ 54 | groff -t -c -m man -T$output_dev -rLL=${col}n -rLT=${col}n 2>/dev/null 55 | } 56 | 57 | remove_escape() { 58 | local escape=$(printf '\033') 59 | sed "s/$escape\[[^m]*m//g" | col -x -b 60 | } 61 | 62 | if [ -z "$(which groff)" ]; then 63 | echo "error: groff not found, please install the groff command" 64 | exit 1 65 | fi 66 | 67 | if [ "$pager_type" = "nvim" ]; then 68 | if ! which nvim >/dev/null 2>&1; then 69 | pager_type=vim 70 | fi 71 | fi 72 | if [ "$pager_type" = "vim" ]; then 73 | if ! which vim >/dev/null 2>&1; then 74 | if which nvim >/dev/null 2>&1; then 75 | pager_type=nvim 76 | else 77 | pager_type=less 78 | fi 79 | fi 80 | fi 81 | 82 | case $pager_type in 83 | system) 84 | [ -z "$PAGER" ] && PAGER=less 85 | render | $PAGER 86 | ;; 87 | 88 | vim|nvim) 89 | render | remove_escape 3<&- | { 90 | $pager_type \ 91 | --cmd "let g:is_cppman_active=1" \ 92 | -R \ 93 | -c "let g:page_name=\"$page_name\"" \ 94 | -S $vim_config \ 95 | /dev/fd/3 6 | # All Rights reserved. 7 | # 8 | # This file is part of cppman. 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software Foundation, 22 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | 25 | import collections 26 | import gzip 27 | import html 28 | import importlib 29 | import os 30 | import os.path 31 | import re 32 | import shutil 33 | import sqlite3 34 | import subprocess 35 | import sys 36 | 37 | from bs4 import BeautifulSoup 38 | from cppman import environ, util 39 | from cppman.crawler import Crawler 40 | from urllib.parse import urlparse, unquote 41 | 42 | 43 | 44 | def _sort_crawl(entry): 45 | """ Sorting entries for putting '(1)' indexes behind keyword 46 | 47 | 1. keywords that have 'std::' in them have highest priority 48 | 2. priority if 'std::' is inside their name 49 | 3. sorting by keyword 50 | 4. sorting by name 51 | """ 52 | id, title, keyword, count = entry 53 | hasStd1 = keyword.find("std::") 54 | if hasStd1 == -1: 55 | hasStd1 = 1 56 | else: 57 | hasStd1 = 0 58 | 59 | hasStd2 = title.find("std::") 60 | if hasStd2 == -1: 61 | hasStd2 = 1 62 | else: 63 | hasStd2 = 0 64 | 65 | return (hasStd1, hasStd2, keyword, title) 66 | 67 | 68 | def _sort_search(entry, pattern): 69 | """ Sort results 70 | 0. exact match goes first 71 | 1. sort by 'std::' (an entry with `std::` goes before an entry without) 72 | 2. sort by which position the keyword appears 73 | """ 74 | 75 | title, keyword, url = entry 76 | 77 | if keyword == pattern: 78 | # Exact match - lowest key value 79 | return (-1, -1, 0, keyword) 80 | 81 | hasStd1 = keyword.find("std::") 82 | if hasStd1 == -1: 83 | hasStd1 = 1 84 | else: 85 | hasStd1 = 0 86 | 87 | hasStd2 = title.find("std::") 88 | if hasStd2 == -1: 89 | hasStd2 = 1 90 | else: 91 | hasStd2 = 0 92 | 93 | return (hasStd1, hasStd2, keyword.find(pattern), keyword) 94 | 95 | # Return the longest prefix of all list elements. 96 | def _commonprefix(s1, s2): 97 | """" Given two strings, returns the longest common leading prefix """ 98 | 99 | if len(s1) > len(s2): 100 | s1, s2 = s2, s1; 101 | for i, c in enumerate(s1): 102 | if c != s2[i]: 103 | return s1[:i] 104 | return s1 105 | 106 | def _removeprefix(string, prefix): 107 | if prefix and string.startswith(prefix): 108 | return string[len(prefix):] 109 | return string 110 | 111 | def _removesuffix(string, suffix): 112 | if suffix and string.endswith(suffix): 113 | return string[:-len(suffix)] 114 | return string 115 | 116 | class Cppman(Crawler): 117 | """ Manage cpp man pages, indexes. """ 118 | 119 | def __init__(self, forced=False, force_columns=-1): 120 | Crawler.__init__(self) 121 | self.forced = forced 122 | self.success_count = None 123 | self.failure_count = None 124 | self.force_columns = force_columns 125 | 126 | def rebuild_index(self): 127 | """ Rebuild index database from cplusplus.com and cppreference.com. """ 128 | 129 | self.db_conn = sqlite3.connect(environ.index_db_re) 130 | self.db_cursor = self.db_conn.cursor() 131 | try: 132 | self.add_url_filter(r'\.(jpg|jpeg|gif|png|js|css|swf|svg)$') 133 | self.set_follow_mode(Crawler.F_SAME_PATH) 134 | 135 | sources = [('cplusplus.com', 'https://cplusplus.com/reference/', None), 136 | ('cppreference.com', 'https://en.cppreference.com/w/cpp', '/w/cpp')] 137 | 138 | for table, url, path in sources: 139 | """ Drop and recreate tables. """ 140 | self.db_cursor.execute( 141 | 'DROP TABLE IF EXISTS "%s"' 142 | % table) 143 | 144 | self.db_cursor.execute( 145 | 'DROP TABLE IF EXISTS "%s_keywords"' 146 | % table) 147 | 148 | self.db_cursor.execute( 149 | 'CREATE TABLE "%s" (' 150 | 'id INTEGER NOT NULL PRIMARY KEY, ' 151 | 'title VARCHAR(255) NOT NULL UNIQUE, ' 152 | 'url VARCHAR(255) NOT NULL UNIQUE' 153 | ')' % table) 154 | 155 | self.db_cursor.execute( 156 | 'CREATE TABLE "%s_keywords" (' 157 | 'id INTEGER NOT NULL, ' 158 | 'keyword VARCHAR(255), ' 159 | 'FOREIGN KEY(id) REFERENCES "%s"(id)' 160 | ')' % (table, table)) 161 | 162 | """ Crawl and insert all entries. """ 163 | self.results = collections.defaultdict(list) 164 | self.crawl(url) 165 | results = self._results_with_unique_title() 166 | 167 | for title in results: 168 | """ 1. insert title """ 169 | self.db_cursor.execute( 170 | 'INSERT INTO "%s" (title, url) VALUES (?, ?)' 171 | % table, (title, results[title]["url"])) 172 | 173 | lastRow = self.db_cursor.execute( 174 | 'SELECT last_insert_rowid()').fetchall()[0][0] 175 | 176 | """ 2. insert all keywords """ 177 | for k in results[title]["keywords"]: 178 | self.db_cursor.execute( 179 | 'INSERT INTO "%s_keywords" (id, keyword) ' 180 | 'VALUES (?, ?)' 181 | % table, (lastRow, k)) 182 | 183 | """ 3. add all aliases """ 184 | for title in results: 185 | for (k, a) in results[title]["aliases"]: 186 | """ search for combinations of words 187 | 188 | e.g. std::basic_string::append 189 | """ 190 | sql_results = self.db_cursor.execute( 191 | 'SELECT id, keyword FROM "%s_keywords" ' 192 | 'WHERE keyword LIKE "%%::%s::%%" ' 193 | 'OR keyword LIKE "%s::%%" ' 194 | 'OR keyword LIKE "%s" ' 195 | 'OR keyword LIKE "%s %%" ' 196 | 'OR keyword LIKE "%s)%%" ' 197 | 'OR keyword LIKE "%s,%%"' 198 | % (table, k, k, k, k, k, k)).fetchall() 199 | 200 | for id, keyword in sql_results: 201 | keyword = re.sub(re.escape("%s" % k), "%s" % a, keyword, flags=re.IGNORECASE) 202 | 203 | self.db_cursor.execute( 204 | 'INSERT INTO "%s_keywords" (id, keyword) ' 205 | 'VALUES (?, ?)' 206 | % table, (id, keyword)) 207 | 208 | self.db_conn.commit() 209 | 210 | """ remove duplicate keywords that link the same page """ 211 | self.db_cursor.execute( 212 | 'DELETE FROM "%s_keywords" WHERE rowid NOT IN (' 213 | 'SELECT min(rowid) FROM "%s_keywords" ' 214 | 'GROUP BY id, keyword ' 215 | ')' % (table, table)).fetchall() 216 | 217 | """ give duplicate keywords with different links entry numbers """ 218 | results = self.db_cursor.execute( 219 | 'SELECT t3.id, t3.title, t2.keyword, t1.count ' 220 | 'FROM (' 221 | ' SELECT keyword, COUNT(*) AS count FROM "%s_keywords" ' 222 | ' GROUP BY keyword HAVING count > 1) AS t1 ' 223 | 'JOIN "%s_keywords" AS t2 ' 224 | 'JOIN "%s" AS t3 ' 225 | 'WHERE t1.keyword = t2.keyword AND t3.id = t2.id ' 226 | 'ORDER BY t2.keyword, t3.title' 227 | % (table, table, table)).fetchall() 228 | 229 | keywords = {} 230 | results = sorted(results, key=_sort_crawl) 231 | for id, title, keyword, count in results: 232 | if not keyword in keywords: 233 | keywords[keyword] = 0 234 | keywords[keyword] += 1 235 | new_keyword = "%s (%s)" % (keyword, keywords[keyword]) 236 | self.db_cursor.execute( 237 | 'UPDATE "%s_keywords" SET keyword=? WHERE ' 238 | 'id=? AND keyword=?' 239 | % table, (new_keyword, id, keyword)) 240 | 241 | self.db_conn.commit() 242 | 243 | except KeyboardInterrupt: 244 | os.remove(environ.index_db_re) 245 | raise KeyboardInterrupt 246 | finally: 247 | self.db_conn.close() 248 | 249 | def process_document(self, url, content, depth): 250 | """callback to insert index""" 251 | print("Indexing '%s' (depth %s)..." % (url, depth)) 252 | name = self._extract_name(content).replace('\n', '') 253 | keywords = self._extract_keywords(content) 254 | 255 | entry = {'url': url, 'keywords': set(), 'aliases': set()} 256 | self.results[name].append(entry) 257 | 258 | for n in self._parse_title(name): 259 | """ add as keyword """ 260 | entry["keywords"].add(n) 261 | 262 | """ add as keyword without std:: """ 263 | if n.find("std::") != -1: 264 | entry["keywords"].add(n.replace('std::', '')) 265 | 266 | """ add with all keywords variations """ 267 | for k in keywords: 268 | """ add std:: to typedef if original type is in std namespace """ 269 | if n.find("std::") != -1 and k.find("std::") == -1: 270 | k = "std::" + k; 271 | 272 | entry["aliases"].add((n, k)) 273 | prefix = _commonprefix(n, k) 274 | 275 | if len(prefix) > 2 and prefix[-2:] == "::": 276 | """ Create names and keyword without prefixes """ 277 | new_name = n[len(prefix):] 278 | new_key = k[len(prefix):] 279 | entry["aliases"].add((new_name, new_key)) 280 | 281 | if k.find("std::") != -1: 282 | entry["aliases"].add( 283 | (n, k.replace('std::', ''))) 284 | 285 | return True 286 | 287 | def _results_with_unique_title(self): 288 | """process crawling results and return title -> entry dictionary; 289 | add part of the path to entries having the same title 290 | """ 291 | results = dict() 292 | for title, entries in self.results.items(): 293 | if len(entries) == 1: 294 | results[title] = entries[0] 295 | else: 296 | paths = [_removesuffix(urlparse(entry['url'])[2], '/') for entry in entries] 297 | prefix = os.path.commonpath(paths) 298 | if prefix: 299 | prefix += '/' 300 | suffix = '/' + os.path.basename(paths[0]) 301 | for path in paths: 302 | if not path.endswith(suffix): 303 | suffix = '' 304 | break 305 | for index, entry in enumerate(entries): 306 | path = _removeprefix(paths[index], prefix) 307 | path = _removesuffix(path, suffix) 308 | results["{} ({})".format(title, unquote(path))] = entry 309 | return results 310 | 311 | def _extract_name(self, data): 312 | """Extract man page name from web page.""" 313 | name = re.search('<[hH]1[^>]*>(.+?)', data, re.DOTALL).group(1) 314 | name = re.sub(r'<([^>]+)>', r'', name) 315 | name = re.sub(r'>', r'>', name) 316 | name = re.sub(r'<', r'<', name) 317 | return html.unescape(name) 318 | 319 | def _parse_expression(self, expr): 320 | """ 321 | split expression into prefix and expression 322 | tested with 323 | ``` 324 | operator== 325 | != 326 | std::rel_ops::operator!= 327 | std::atomic::operator= 328 | std::array::operator[] 329 | std::function::operator() 330 | std::vector::at 331 | std::relational operators 332 | std::vector::begin 333 | std::abs(float) 334 | std::fabs() 335 | ``` 336 | """ 337 | m = re.match(r'^(.*?(?:::)?(?:operator)?)((?:::[^:]*|[^:]*)?)$', expr) 338 | prefix = m.group(1) 339 | tail = m.group(2) 340 | return [prefix, tail] 341 | 342 | def _parse_title(self, title): 343 | """ 344 | split of the last parenthesis operator==,!=,<,<=(std::vector) 345 | tested with 346 | ``` 347 | operator==,!=,<,<=,>,>=(std::vector) 348 | operator==,!=,<,<=,>,>=(std::vector) 349 | operator==,!=,<,<=,>,>= 350 | operator==,!=,<,<=,>,>= 351 | std::rel_ops::operator!=,>,<=,>= 352 | std::atomic::operator= 353 | std::array::operator[] 354 | std::function::operator() 355 | std::vector::at 356 | std::relational operators (vector) 357 | std::vector::begin, std::vector::cbegin 358 | std::abs(float), std::fabs 359 | std::unordered_set::begin(size_type), std::unordered_set::cbegin(size_type) 360 | ``` 361 | """ 362 | """ remove all template stuff """ 363 | title = re.sub(r" ?<[^>]+>", "", title) 364 | 365 | m = re.match( 366 | r'^\s*((?:\(size_type\)|(?:.|\(\))*?)*)((?:\([^)]+\))?)\s*$', title) 367 | 368 | postfix = m.group(2) 369 | 370 | t_names = m.group(1).split(',') 371 | t_names = [n.strip() for n in t_names] 372 | prefix = self._parse_expression(t_names[0])[0] 373 | names = [] 374 | for n in t_names: 375 | r = self._parse_expression(n) 376 | if prefix == r[0]: 377 | names.append(n + postfix) 378 | else: 379 | names.append(prefix + r[1] + postfix) 380 | return names 381 | 382 | def _extract_keywords(self, text): 383 | """ 384 | extract aliases like std::string, template specializations like std::atomic_bool 385 | and helper functions like std::is_same_v 386 | """ 387 | soup = BeautifulSoup(text, "lxml") 388 | names = [] 389 | 390 | # search for typedef list 391 | for x in soup.find_all('table'): 392 | # just searching for "Type" is not enough, see std::is_same 393 | p = x.find_previous_sibling('h3') 394 | if p: 395 | if p.get_text().strip() == "Member types": 396 | continue 397 | 398 | typedefTable = False 399 | for tr in x.find_all('tr'): 400 | tds = tr.find_all('td') 401 | if len(tds) == 2: 402 | if re.match(r"\s*Type\s*", tds[0].get_text()): 403 | typedefTable = True 404 | elif typedefTable: 405 | res = re.search(r'^\s*(\S*)\s+.*$', tds[0].get_text()) 406 | if res and res.group(1): 407 | names.append(res.group(1)) 408 | elif not typedefTable: 409 | break 410 | if typedefTable: 411 | break 412 | 413 | # search for "Helper variable template" list 414 | for x in soup.find_all('h3'): 415 | variableTemplateHeader = False 416 | if x.find('span', id="Helper_variable_template"): 417 | e = x.find_next_sibling() 418 | while e.name == "": 419 | e = e.find_next_sibling() 420 | if e.name == "table": 421 | for tr in e.find_all('tr'): 422 | text = re.sub('\n', ' ', tr.get_text()) 423 | res = re.search(r'^.* (\S+)\s*=.*$', text) 424 | if res: 425 | names.append(res.group(1)) 426 | # search for "Helper types" list 427 | for x in soup.find_all('h3'): 428 | variableTemplateHeader = False 429 | if x.find('span', id="Helper_types"): 430 | e = x.find_next_sibling() 431 | while e.name == "": 432 | e = e.find_next_sibling() 433 | if e.name == "table": 434 | for tr in e.find_all('tr'): 435 | text = re.sub('\n', ' ', tr.get_text()) 436 | res = re.search(r'^.* (\S+)\s*=.*$', text) 437 | if res: 438 | names.append(res.group(1)) 439 | return [html.unescape(n) for n in names] 440 | 441 | def cache_all(self): 442 | """Cache all available man pages""" 443 | 444 | respond = input( 445 | 'By default, cppman fetches pages on-the-fly if corresponding ' 446 | 'page is not found in the cache. The "cache-all" option is only ' 447 | 'useful if you want to view man pages offline. ' 448 | 'Caching all contents will take several minutes, ' 449 | 'do you want to continue [y/N]? ') 450 | if not (respond and 'yes'.startswith(respond.lower())): 451 | raise KeyboardInterrupt 452 | 453 | try: 454 | os.makedirs(environ.cache_dir) 455 | except: 456 | pass 457 | 458 | self.success_count = 0 459 | self.failure_count = 0 460 | 461 | if not os.path.exists(environ.index_db): 462 | raise RuntimeError("can't find index.db") 463 | 464 | conn = sqlite3.connect(environ.index_db) 465 | cursor = conn.cursor() 466 | 467 | source = environ.config.source 468 | print('Caching manpages from %s ...' % source) 469 | data = cursor.execute('SELECT title, url FROM "%s"' % source).fetchall() 470 | 471 | for name, url in data: 472 | print('Caching %s ...' % name) 473 | retries = 3 474 | while retries > 0: 475 | try: 476 | self.cache_man_page(source, url, name) 477 | except Exception: 478 | print('Retrying ...') 479 | retries -= 1 480 | else: 481 | self.success_count += 1 482 | break 483 | else: 484 | print('Error caching %s ...' % name) 485 | self.failure_count += 1 486 | 487 | conn.close() 488 | 489 | print('\n%d manual pages cached successfully.' % self.success_count) 490 | print('%d manual pages failed to cache.' % self.failure_count) 491 | self.update_mandb(False) 492 | 493 | def cache_man_page(self, source, url, name): 494 | """callback to cache new man page""" 495 | # Skip if already exists, override if forced flag is true 496 | outname = self.get_page_path(source, name) 497 | if os.path.exists(outname) and not self.forced: 498 | return 499 | 500 | try: 501 | os.makedirs(os.path.join(environ.cache_dir, source)) 502 | except OSError: 503 | pass 504 | 505 | # There are often some errors in the HTML, for example: missing closing 506 | # tag. We use fixupHTML to fix this. 507 | data = util.fixupHTML(util.urlopen(url).read()) 508 | 509 | formatter = importlib.import_module( 510 | 'cppman.formatter.%s' % source[:-4]) 511 | groff_text = formatter.html2groff(data, name) 512 | 513 | with gzip.open(outname, 'w') as f: 514 | f.write(groff_text.encode('utf-8')) 515 | 516 | def clear_cache(self): 517 | """Clear all cache in man""" 518 | shutil.rmtree(environ.cache_dir) 519 | 520 | def _fetch_page_by_keyword(self, keyword): 521 | """ fetches result for a keyword """ 522 | return self.cursor.execute( 523 | 'SELECT t1.title, t2.keyword, t1.url ' 524 | 'FROM "%s" AS t1 ' 525 | 'JOIN "%s_keywords" AS t2 ' 526 | 'WHERE t1.id = t2.id AND t2.keyword ' 527 | 'LIKE ? ORDER BY t2.keyword' 528 | % (self.source, self.source), ['%%%s%%' % keyword]).fetchall() 529 | 530 | def _search_keyword(self, pattern): 531 | """ multiple fetches for each pattern """ 532 | if not os.path.exists(environ.index_db): 533 | raise RuntimeError("can't find index.db") 534 | 535 | conn = sqlite3.connect(environ.index_db) 536 | self.cursor = conn.cursor() 537 | self.source = environ.source 538 | 539 | self.cursor.execute('PRAGMA case_sensitive_like=ON') 540 | results = self._fetch_page_by_keyword("%s" % pattern) 541 | results.extend(self._fetch_page_by_keyword("%s %%" % pattern)) 542 | results.extend(self._fetch_page_by_keyword("%% %s" % pattern)) 543 | results.extend(self._fetch_page_by_keyword("%% %s %%" % pattern)) 544 | 545 | results.extend(self._fetch_page_by_keyword("%s%%" % pattern)) 546 | if len(results) == 0: 547 | results = self._fetch_page_by_keyword("%%%s%%" % pattern) 548 | 549 | conn.close() 550 | return sorted(list(set(results)), key=lambda e: _sort_search(e, pattern)) 551 | 552 | def man(self, pattern): 553 | """Call viewer.sh to view man page""" 554 | results = self._search_keyword(pattern) 555 | if len(results) == 0: 556 | raise RuntimeError('No manual entry for %s ' % pattern) 557 | 558 | page_name, keyword, url = results[0] 559 | 560 | try: 561 | avail = os.listdir(os.path.join(environ.cache_dir, environ.source)) 562 | except OSError: 563 | avail = [] 564 | 565 | page_filename = self.get_normalized_page_name(page_name) 566 | if self.forced or page_filename + '.3.gz' not in avail: 567 | self.cache_man_page(environ.source, url, page_name) 568 | 569 | pager_type = environ.pager if sys.stdout.isatty() else 'pipe' 570 | 571 | # Call viewer 572 | columns = (util.get_width() if self.force_columns == -1 else 573 | self.force_columns) 574 | pid = os.fork() 575 | if pid == 0: 576 | os.execl('/bin/sh', '/bin/sh', environ.pager_script, pager_type, 577 | self.get_page_path(environ.source, page_name), 578 | str(columns), environ.pager_config, pattern) 579 | return pid 580 | 581 | def find(self, pattern): 582 | """Find pages in database.""" 583 | 584 | results = self._search_keyword(pattern) 585 | 586 | pat = re.compile(r'(.*?)(%s)(.*?)( \(.*\))?$' % 587 | re.escape(pattern), re.I) 588 | 589 | if results: 590 | for name, keyword, url in results: 591 | 592 | if os.isatty(sys.stdout.fileno()): 593 | keyword = pat.sub( 594 | r'\1\033[1;31m\2\033[0m\3\033[1;33m\4\033[0m', keyword) 595 | print("%s - %s" % (keyword, name)) 596 | else: 597 | raise RuntimeError('%s: nothing appropriate.' % pattern) 598 | 599 | def fuzzy_find(self, pattern): 600 | """Find pages in database and present an interactive selection menu.""" 601 | results = self._search_keyword(pattern) 602 | 603 | if not results: 604 | raise RuntimeError('%s: nothing appropriate.' % pattern) 605 | 606 | if len(results) == 1: 607 | return results[0][1] 608 | 609 | for i, (name, keyword, url) in enumerate(results, 1): 610 | print(f"{i}. {keyword} - {name}") 611 | 612 | while True: 613 | try: 614 | selection = input("\nPlease enter the selection: ") 615 | if not selection: 616 | return None 617 | 618 | idx = int(selection) - 1 619 | if 0 <= idx < len(results): 620 | return results[idx][1] 621 | print("Invalid selection. Please try again.") 622 | except ValueError: 623 | print("Please enter a valid number.") 624 | except KeyboardInterrupt: 625 | print("\nOperation cancelled.") 626 | return None 627 | 628 | def update_mandb(self, quiet=True): 629 | """Update mandb.""" 630 | if not environ.config.UpdateManPath: 631 | return 632 | print('\nrunning mandb...') 633 | cmd = 'mandb %s' % (' -q' if quiet else '') 634 | subprocess.Popen(cmd, shell=True).wait() 635 | 636 | def get_normalized_page_name(self, name): 637 | return name.replace('/', '_') 638 | 639 | def get_page_path(self, source, name): 640 | name = self.get_normalized_page_name(name) 641 | return os.path.join(environ.cache_dir, source, name + '.3.gz') 642 | -------------------------------------------------------------------------------- /cppman/util.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # util.py - Misc utilities 4 | # 5 | # Copyright (C) 2010 - 2015 Wei-Ning Huang (AZ) 6 | # All Rights reserved. 7 | # 8 | # This file is part of cppman. 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software Foundation, 22 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 23 | # 24 | 25 | import os 26 | import shutil 27 | import subprocess 28 | import urllib.request 29 | 30 | import bs4 31 | from cppman import environ 32 | 33 | # User-Agent header value to use with all requests 34 | _USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/111.0" 35 | 36 | def update_mandb_path(): 37 | """Add $XDG_CACHE_HOME/cppman/man to $HOME/.manpath""" 38 | manpath_file = os.path.join(environ.HOME, ".manpath") 39 | man_dir = environ.cache_dir 40 | manindex_dir = environ.manindex_dir 41 | 42 | lines = [] 43 | 44 | """ read all lines """ 45 | try: 46 | with open(manpath_file, 'r') as f: 47 | lines = f.readlines() 48 | except IOError: 49 | return 50 | 51 | """ remove MANDATORY_MANPATH and MANDB_MAP entry """ 52 | lines = [line for line in lines if man_dir not in line] 53 | 54 | with open(manpath_file, 'w') as f: 55 | if environ.config.UpdateManPath: 56 | lines.append('MANDATORY_MANPATH\t%s\n' % man_dir) 57 | lines.append('MANDB_MAP\t\t\t%s\t%s\n' % (man_dir, manindex_dir)) 58 | 59 | f.writelines(lines) 60 | 61 | 62 | def update_man3_link(): 63 | man3_path = os.path.join(environ.cache_dir, 'man3') 64 | 65 | if os.path.lexists(man3_path): 66 | if os.path.islink(man3_path): 67 | if os.readlink(man3_path) == environ.config.Source: 68 | return 69 | else: 70 | os.unlink(man3_path) 71 | else: 72 | raise RuntimeError("Can't create link since `%s' already exists" % 73 | man3_path) 74 | try: 75 | os.makedirs(os.path.join(environ.cache_dir, environ.config.Source)) 76 | except Exception: 77 | pass 78 | 79 | os.symlink(environ.config.Source, man3_path) 80 | 81 | 82 | def get_width(): 83 | """Get terminal width""" 84 | # Get terminal size 85 | columns, lines = shutil.get_terminal_size() 86 | width = min(columns * 39 // 40, columns - 2) 87 | return width 88 | 89 | 90 | def groff2man(data): 91 | """Read groff-formatted text and output man pages.""" 92 | width = get_width() 93 | 94 | cmd = 'groff -t -Tascii -m man -rLL=%dn -rLT=%dn' % (width, width) 95 | handle = subprocess.Popen( 96 | cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, 97 | stderr=subprocess.PIPE) 98 | man_text, stderr = handle.communicate(data) 99 | return man_text 100 | 101 | 102 | def html2man(data, formatter): 103 | """Convert HTML text from cplusplus.com to man pages.""" 104 | groff_text = formatter(data) 105 | man_text = groff2man(groff_text) 106 | return man_text 107 | 108 | 109 | def fixupHTML(data): 110 | return str(bs4.BeautifulSoup(data, "html5lib")) 111 | 112 | def urlopen(url, *args, **kwargs): 113 | """A wrapper around urllib.request.urlopen() which adds custom headers""" 114 | if isinstance(url, urllib.request.Request): 115 | req = url 116 | else: 117 | req = urllib.request.Request(url) 118 | req.add_header('User-Agent', _USER_AGENT) 119 | return urllib.request.urlopen(req, *args, **kwargs) 120 | 121 | def build_opener(*args, **kwargs): 122 | """A wrapper around urllib.request.build_opener() which adds custom headers""" 123 | opener = urllib.request.build_opener(*args, **kwargs) 124 | opener.addheaders = [('User-Agent', _USER_AGENT)] 125 | return opener 126 | -------------------------------------------------------------------------------- /dev/chver.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | sed -i "s/program_version = '.*'/program_version = '$1'/" bin/cppman 4 | sed -i "s/version = '.*'/version = '$1'/" setup.py 5 | -------------------------------------------------------------------------------- /dev/control: -------------------------------------------------------------------------------- 1 | Source: manpages-cpp 2 | Section: devel 3 | Priority: optional 4 | Maintainer: Wei-Ning Huang (AZ) 5 | Build-Depends: cdbs (>=0.4.49), debhelper (>= 5), python-central (>=0.5.6) 6 | XS-Python-Version: >=2.6 7 | Standards-Version: 3.7.2 8 | 9 | Package: manpages-cpp 10 | Architecture: all 11 | XB-Python-Version: ${python:Versions} 12 | Depends: ${python:Depends}, vim, groff 13 | Description: C++ man pages generator 14 | cppman generates C++ manual pages from cplusplus.com or cppreference.com and provide a man-like 15 | interface to view man pages. 16 | -------------------------------------------------------------------------------- /dev/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | 3 | DEB_PYTHON_SYSTEM=pycentral 4 | 5 | include /usr/share/cdbs/1/rules/debhelper.mk 6 | include /usr/share/cdbs/1/class/python-distutils.mk 7 | 8 | # Add here any variable or target overrides you need. 9 | -------------------------------------------------------------------------------- /dev/update_authors.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | AUTHOR='AZ Huang ' 4 | 5 | cat << EOF > AUTHORS 6 | Developers 7 | ---------- 8 | $AUTHOR 9 | 10 | Contributors 11 | ------------ 12 | EOF 13 | 14 | git log --all --format='%aN <%cE>' | \ 15 | egrep -v '(wnhuang|aitjcize)' | \ 16 | sort -u | \ 17 | grep -v "$AUTHOR" >> AUTHORS 18 | -------------------------------------------------------------------------------- /misc/completions/cppman.bash: -------------------------------------------------------------------------------- 1 | _cppman () 2 | { 3 | if [ "${#COMP_WORDS[@]}" -gt 2 ]; then 4 | return 5 | fi 6 | if [ -z "${COMP_WORDS[1]}" ]; then 7 | return 8 | fi 9 | P=${COMP_LINE[0]} 10 | W=${COMP_WORDS[1]} 11 | 12 | PERLP=$(printf 'if (m/^(.*?) - (.*)$/) { print "$1$/"; }' $W) 13 | 14 | params="$($P -f "$W" | perl -ne "$PERLP" | sort -u | xargs -d '\n' printf '%q ')" 15 | echo $params > test.log 16 | 17 | COMPREPLY=($(compgen -W "$params" "$W")) 18 | 19 | } 20 | complete -F _cppman cppman 21 | -------------------------------------------------------------------------------- /misc/completions/fish/cppman.fish: -------------------------------------------------------------------------------- 1 | set -l progname cppman 2 | 3 | complete -c $progname -f 4 | 5 | complete -c $progname -s s -l source -a "cppreference.com cplusplus.com" -d "Select source" 6 | complete -c $progname -s c -l cache-all -d "Cache all available man pages from cppreference.com and cplusplus.com to enable offline browsing" 7 | complete -c $progname -s C -l clear-cache -d "Clear all cached files" 8 | complete -c $progname -s f -l find-page -d "Find man page" 9 | complete -c $progname -s o -l force-update -d "Force cppman to update existing cache when '--cache-all' or browsing man pages that were already cached" 10 | complete -c $progname -s m -l use-mandb -a "true false" -d "If true, cppman adds manpage path to mandb so that you can view C++ manpages with 'man' command" 11 | complete -c $progname -s p -l pager -a "vim nvim less system" -d "Select pager to use" 12 | complete -c $progname -s r -l rebuild-index -d "rebuild index database for the selected source" 13 | complete -c $progname -s v -l version -d "Show version information" 14 | complete -c $progname -l force-columns -d "Force terminal columns" 15 | complete -c $progname -s h -l help -d "Show help message and exit" 16 | -------------------------------------------------------------------------------- /misc/completions/zsh/_cppman: -------------------------------------------------------------------------------- 1 | #compdef cppman 2 | _cppman_pages () 3 | { 4 | P=${words[1]} 5 | if [ $CURRENT -gt $NORMARG ]; then 6 | return 7 | fi 8 | W=${words[$NORMARG]} 9 | if [ -z "$W" ]; then 10 | return 11 | fi 12 | # (f)$(...) use shell output as arrays with line breaks as separators 13 | # ${...%% *} remove everything after the first space in each array element 14 | # ${(M)...:#$W*} only keep elements that match $W*, i.e. start with $W 15 | params=(${(M)${${(f)"$($P -f $W)"}%% *}:#$W*}) 16 | 17 | compadd "$@" -- $params 18 | } 19 | 20 | # (1 -) don't suggest any further after an option. Used because the code does sys.exit() after these. 21 | _arguments -n \ 22 | "(1 -)"{-s,--source=}"[Select source]:SOURCE:(cppreference.com cplusplus.com)" \ 23 | "(1 -)"{-c,--cache-all}"[Cache all available man pages from cppreference.com and cplusplus.com to enable offline browsing]" \ 24 | "(1 -)"{-C,--clear-cache}"[Clear all cached files.]" \ 25 | "(1 -)"{-f,--find-page=}"[Find man page.]:KEYWORD: " \ 26 | "(1 -)"{-h,--help}"[show help message and exit]" \ 27 | "(1 -)"{-o,--force-update}"[Force cppman to update existing cache when '--cache-all' or browsing man pages that were already cached.]" \ 28 | "(1 -)"{-m,--use-mandb=}"[If true, cppman adds manpage path to mandb so that you can view C++ manpages with 'man' command.]:MANDB:(true false)" \ 29 | "(1 -)"{-p,--pager=}"[Select pager to use.]:PAGER:(vim nvim less system)" \ 30 | "(1 -)"{-r,--rebuild-index}"[rebuild index database for the selected source.]" \ 31 | "(1 -)"{-v,--version}"[Show version information.]" \ 32 | "--force-columns=[Force terminal columns]:FORCE_COLUMNS:" \ 33 | "1:man page:_cppman_pages" \ 34 | -------------------------------------------------------------------------------- /misc/cppman.1: -------------------------------------------------------------------------------- 1 | .TH CPPMAN 1 "MAY 2010" Linux "User Manuals" 2 | .SH NAME 3 | cppman - C++ manual page viewer / fetcher 4 | .SH SYNOPSIS 5 | .B cppman [ 6 | .I OPTIONS... 7 | .B ] PAGE... 8 | .SH DESCRIPTION 9 | cppman generates C++ manual pages from cplusplus.com and provide a man\-like interface to view man pages. 10 | .sp 11 | By default, cppman fetches man pages on-the-fly, by running the command 'cppman \-c', all available manpages are cached, making offline browsing possible. This is also required if you want to use the system 'man' command. 12 | .SS Browsing man pages 13 | cppman uses Vi Improved as a pager. 14 | .br 15 | Press 'q' to leave pager. 16 | Press 'K' on an entry like 'vector::insert(3)' links you to the manual page of vector::insert, like a hyperlink. 17 | .SS man compatibility 18 | cppman automatically adds '$XDG_CACHE_HOME/cppman/man' to '~/.manpath', so the cached man pages can also be viewed with 'man' command. Note that to view uncached man pages, you still need to run 'cppman'. 19 | .SH OPTIONS 20 | .IP "\-s SOURCE, \-\-source=SOURCE" 21 | Select source, either 'cppreference.com' or 'cplusplus.com'. Default is 'cppreference.com'. 22 | .IP "\-c, \-\-cache\-all" 23 | cache all available man pages from cplusplus.com to enable offline browsing 24 | .IP "\-C, \-\-clear\-cache" 25 | clear all cached files 26 | .IP "\-f KEYWORD, \-\-find\-page=KEYWORD" 27 | find man page 28 | .IP "\-o, \-\-force\-update" 29 | force cppman to update existing cache when '\-\-cache\-all' or browsing man pages that were already cached 30 | .IP "\-m MANDB, \-\-use\-mandb=MANDB" 31 | Accepts 'true' or 'false'. If true, cppman adds manpage path to mandb so that you can view C++ manpages with `man' command. The default value is 'false'. 32 | .IP "\-p PAGER, \-\-pager=PAGER" 33 | Select pager to use, accepts 'vim', 'nvim' or 'less'. The default value is 'vim'. 34 | If 'nvim' is selected, but not available, 'vim' is used as a fallback and vice versa. If either is selected, but neither is available, 'less' is used as a fallback. 35 | .IP "\-r, \-\-rebuild\-index" 36 | rebuild index database from cplusplus.com 37 | .IP "\-v, \-\-version" 38 | show version information 39 | .IP "\-h, \-\-help" 40 | show this help message and exit 41 | .SH NOTE 42 | All contents should be cached by the user, cppman does not contain any pre\[hy]cached contents. 43 | .sp 44 | Do not distribute the cached man pages without the permission of cplusplus.com. 45 | .SH BUGS 46 | Although I spend a lot of time checking the format, there are still pages that won't display correctly. 47 | .br 48 | Feel free to report bugs at: 49 | .sp 50 | https://github.com/aitjcize/cppman/issues or 51 | .br 52 | mailto:aitjcize@gmail.com. 53 | .sp 54 | Please include the page name in the bug report. 55 | .SH AUTHOR 56 | Wei\[hy]Ning Huang (AZ) 57 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4==4.13.3 2 | bs4==0.0.2 3 | html5lib==1.1 4 | lxml==5.3.2 5 | six==1.17.0 6 | soupsieve==2.6 7 | typing_extensions==4.13.1 8 | webencodings==0.5.1 9 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | 2 | [bdist_rpm] 3 | packager = Wei-Ning Huang (AZ) 4 | release = 1 5 | requires = python, vim 6 | 7 | [install] 8 | optimize=2 9 | 10 | [build_ext] 11 | inplace=1 12 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from distutils.core import setup 4 | 5 | _package_data = [ 6 | 'lib/index.db', 7 | 'lib/pager.sh', 8 | 'lib/cppman.vim' 9 | ] 10 | 11 | _data_files = [ 12 | ('share/doc/cppman', ['README.rst', 'AUTHORS', 'COPYING', 'ChangeLog']), 13 | ('share/man/man1', ['misc/cppman.1']), 14 | ('share/bash-completion/completions', ['misc/completions/cppman.bash']), 15 | ('share/zsh/vendor-completions/', ['misc/completions/zsh/_cppman']), 16 | ('share/fish/vendor_completions.d/', ['misc/completions/fish/cppman.fish']) 17 | ] 18 | 19 | with open('requirements.txt') as f: 20 | _requirements = f.read().splitlines() 21 | 22 | setup( 23 | name = 'cppman', 24 | version = '0.5.9', 25 | description = 'C++ 98/11/14/17/20 manual pages for Linux/MacOS', 26 | author = 'Wei-Ning Huang (AZ)', 27 | author_email = 'aitjcize@gmail.com', 28 | url = 'https://github.com/aitjcize/cppman', 29 | license = 'GPL', 30 | packages = ['cppman', 'cppman.formatter'], 31 | package_data = {'cppman': _package_data}, 32 | data_files = _data_files, 33 | scripts = ['bin/cppman'], 34 | install_requires=_requirements, 35 | classifiers = [ 36 | 'Programming Language :: Python :: 3.5', 37 | 'Programming Language :: Python :: 3.6', 38 | 'Programming Language :: Python :: 3.7', 39 | 'Programming Language :: Python :: 3.8', 40 | 'Programming Language :: Python :: 3 :: Only', 41 | 'Topic :: Software Development :: Documentation', 42 | ], 43 | ) 44 | -------------------------------------------------------------------------------- /test/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | import os 5 | import os.path 6 | sys.path.insert(0, os.path.normpath(os.getcwd())) 7 | 8 | from cppman.formatter import cplusplus, cppreference 9 | 10 | cplusplus.func_test() 11 | cppreference.func_test() 12 | -------------------------------------------------------------------------------- /wiki/cppman-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitjcize/cppman/90ee17da0b2af719db9f1512d202025e2c7ebb9b/wiki/cppman-1.png -------------------------------------------------------------------------------- /wiki/cppman-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitjcize/cppman/90ee17da0b2af719db9f1512d202025e2c7ebb9b/wiki/cppman-2.png -------------------------------------------------------------------------------- /wiki/cppman-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitjcize/cppman/90ee17da0b2af719db9f1512d202025e2c7ebb9b/wiki/cppman-3.png -------------------------------------------------------------------------------- /wiki/cppman-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitjcize/cppman/90ee17da0b2af719db9f1512d202025e2c7ebb9b/wiki/cppman-4.png -------------------------------------------------------------------------------- /wiki/cppman-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitjcize/cppman/90ee17da0b2af719db9f1512d202025e2c7ebb9b/wiki/cppman-5.png -------------------------------------------------------------------------------- /wiki/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitjcize/cppman/90ee17da0b2af719db9f1512d202025e2c7ebb9b/wiki/demo.gif -------------------------------------------------------------------------------- /wiki/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitjcize/cppman/90ee17da0b2af719db9f1512d202025e2c7ebb9b/wiki/screenshot.png --------------------------------------------------------------------------------