├── LICENSE ├── README.md ├── codeSnippetsLog.py ├── demo ├── multiedit.gif ├── pyPadDemo.gif ├── pyPadDemo.py └── selection_test.py ├── pyPad ├── __init__.py ├── introspect.py ├── pyPadClient.py └── pyPadHost.py ├── pyPadCalltip.py ├── pyPadClear.py ├── pyPadExecute.py ├── pyPadExecuteFix.py ├── pyPadRestart.py └── pyPadStart.py /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyPadPlusPlus 2 | ### Addon for Notepad++ and PythonScript for interactive Python development 3 | 4 | PyPadPlusPlus is an interactive Python environment based on Notepad++ (https://notepad-plus-plus.org/) and PythonScript (https://github.com/bruderstein/PythonScript/). 5 | 6 | Its special property is a fusion of the interactive Python shell with the editor to one single tool. This means that the editor can be used for both interactive testing and storing the final code. So, you never have to copy code lines again from the editor to the shell or back. The output appears in a second frame, which is an output-only area, while the editor is an input-only area. 7 | 8 | To execute one line or a piece of code press ` + `. This executes the current line or the smallest number of lines belonging syntatically to the selection. No precise selection is required in order to execute valid parts of the code. The whole script can be executed with the selection of all lines by ` + `. Cells of code can be optionally defined by special comments starting with `#%%`. In any case you have the choice whether you want to execute cells, single lines or code selections. With the mouse wheel button you can execute any line or piece of code by one click. The output is shown in an output console frame. The console has an undo buffer for every execution that produced some output. 9 | 10 | Selecting a variable and hovering over it with the mouse or selecting any expresion and pressing ` + ` will show a popup with information about its current type and value. This also supports numpy shape information. Autocompletion lists for objects and dictionaries allows you to explore the current run-time information of a variable. 11 | 12 | The extension comes with another little feature that fits perfectly in the workflow of PyPadPlusPlus. It allows you to log small pieces of code you wish to keep but don't know where to store. Just select any piece of code and press the keyboard shortcut ` + `. The selection will be added to a file `codeSnippetsLog.txt` with the time and date in a comment line. Pressing the shortcut again without any selection opens this file. It acts as a kind of "Python diary" for code snippets. 13 | 14 | 15 | 16 | #### Features 17 | 18 | * Run Python code line-by-line with ` + ` 19 | * Run selected Python code (intelligent selection, no accurate selection is required) 20 | * Run line or selection with middle mouse button 21 | * Run line or selection multiple times while cursor does not propagate (` + + `) 22 | * Run cells of python code defined by `#%%` comments with ` + ` whey the cursor is at this comment line 23 | * A color marker highlights last executed lines 24 | * Animated color marker for active lines 25 | * Tooltip for run-time variable and object inspection of selected items and mouse hover or ` + `. 26 | * Evaluate any selected expression with ` + `, even while the code is still running 27 | * Special Tooltip with size and shape information of numpy arrays 28 | * Code auto completion for run-time defined object properties, dictionary keys, function calls 29 | * Calltip for function calls, doc string and module help 30 | * Special Tooltip to quickly switch between `True` and `False` 31 | * Click on any Tooltip to show full string or help text in output console 32 | * Output console has an undo buffer (click inside and press ` + `). This can also be used to show the Python version and initialization text after startup. 33 | * Clear output console with ` + + `. 34 | * Internal or external Python distribution can be used for Python 3 kernels. 35 | * Take controll over Notepad++ with the Npp module provided by PythonScript (only available when using the internal Python. Load library with `import Npp`) 36 | * Reset and restart Python kernel with ` + `, e.g. when stuck in endless loop. (only available when using an external Python, otherwise this only performs a variable reset. This function is currently broken.) 37 | * Matplotlib event handler to hold multiple active plot windows 38 | 39 | #### Tutorial 40 | Tutorial video on PyPadPlusPlus by Amit Christian: 41 | 42 | 43 | 44 | #### Download 45 | 46 | PyPadPlusPlus requires Notepad++ and PythonScript. Since the installation is quite cumbersome you can download the [latest release](https://github.com/bitagoras/PyPadPlusPlus/releases/latest) ready-to-play in a bundle with Notepad++ v8.6, PythonScript v3.0.16.0 and Python 3.10 as portable version: 47 | * Download [`Npp8.6_32bit_PyPadPlusPlus1.3.0_Python3.10.11.zip`](https://github.com/bitagoras/PyPadPlusPlus/releases/download/v1.3.0/Npp8.6_32bit_PyPadPlusPlus1.3.0_Python3.10.11.zip), unzip it into a folder and start `notepad++.exe`. 48 | 49 | #### Installation 50 | 51 | If you need to install PyPadPlusPlus in another version of Notepad++ there is some more work to do: 52 | 53 | 1. Install Python Script from https://github.com/bruderstein/PythonScript/releases/ or in the plugin manager of Notepad++. 54 | 2. Download the sources or the latest [release](https://github.com/bitagoras/PyPadPlusPlus/releases) of PyPadPlusPlus and extract the files into the user script folder of PythonScript: 55 |
`notepad++\plugins\config\PythonScript\scripts\` ("user scripts") 56 | 3. Start Notepad++ and go to the menu "Plugins → Python Script → Configuration..." 57 | 4. Select "User Scripts" and add the scripts to Menu items: 58 | * `pyPadClear.py` clears the console output 59 | * `pyPadExecute.py` executes the current line or selection 60 | * `pyPadExecuteFix.py` same as pyPadExecute but keeps the cursor at its position 61 | * `pyPadRestart.py` restarts the python kernel or cleans the variables 62 | * `codeSnippetsLog.py` optional: to store code snippets 63 | * `pyPadCalltip.py` Shows a calltip with the content of the variable below the cursor or the evaluation of the selected expression. 64 | 5. Press OK, restart Notepad++ and go to menu "Settings → Shortcut mapper" and define in the tab "Plugin commands" the shortcuts: 65 | * `pyPadExecute.py + ` 66 | * `pyPadExecuteFix.py + + ` 67 | * `pyPadClear.py + + ` 68 | * `pyPadCalltip.py + ` 69 | * `Show Console + + ` 70 | * `pyPadRestart.py + ` 71 | * `codeSnippetsLog.py + ` 72 | 73 | Note that you have to unset some conflicting shortcuts (Shortcuts can be removed by choosing "None" in the list of keys). 74 | 6. If you want to use the Python installation of your system, open the file 75 | `notepad++\plugins\PythonScript\scripts\` and set the variable `pythonPath` to the path that contains your `pythonw.exe`. 76 | -------------------------------------------------------------------------------- /codeSnippetsLog.py: -------------------------------------------------------------------------------- 1 | import Npp, datetime, os 2 | text = Npp.editor.getTextRange(editor.getSelectionStart(), editor.getSelectionEnd()).rstrip() 3 | 4 | filename = 'codeSnippetsLog.txt' 5 | logDir = os.path.expanduser("~") 6 | 7 | path = os.path.join(logDir, filename) 8 | 9 | if text: 10 | with open(path,'a') as f: 11 | f.write('#%% ' + '_'*25 + ' ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' ' + '_'*25 + '\n\n' + text.replace('\r','').strip() + '\n\n') 12 | n = len(text.splitlines()) 13 | Npp.notepad.messageBox('%i lines logged to %s'%(n,filename)) 14 | else: 15 | notepad.open(path) 16 | notepad.setLangType(Npp.LANGTYPE.PYTHON) 17 | -------------------------------------------------------------------------------- /demo/multiedit.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitagoras/PyPadPlusPlus/81ccd7cad2e3959227191640bf9bd2b2000f5cad/demo/multiedit.gif -------------------------------------------------------------------------------- /demo/pyPadDemo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitagoras/PyPadPlusPlus/81ccd7cad2e3959227191640bf9bd2b2000f5cad/demo/pyPadDemo.gif -------------------------------------------------------------------------------- /demo/pyPadDemo.py: -------------------------------------------------------------------------------- 1 | # This test file demonstrates features of PyPadPlusPlus 2 | 3 | #%% Execution with Keyboard and Mouse 4 | 5 | # + executes the smallest possible piece of code 6 | # that includes the line at the cursor or next to the cursor. 7 | 8 | print("hello world") 9 | 10 | # With + + the cursor stays at its position 11 | # and the same line can be executed several times. 12 | 13 | # The value of a single expression line will be printed 14 | 1+2 15 | 16 | # Multi line commands are executed as a whole and can be started 17 | # from any line inside the indented block. A yellow line shows 18 | # which lines have been executed. 19 | 20 | for i in 1,2,3: 21 | s = str(i) * 8 22 | print("loop", s) 23 | 24 | # Multiple lines can be executed by selection and + . 25 | # The selection doesn't have to cover the whole line. 26 | # With the middle mouse button (mouse wheel button) a single or 27 | # multi line command or a selection can be executed. 28 | 29 | print("* First line") 30 | print("* Second line") 31 | 32 | 33 | #%% Cells of code can be started from special comments "#%%" 34 | 35 | # The end of the cell is defined by the next comment with "#%%" 36 | # or the end of file. 37 | 38 | multiline = """Multi line commands without 39 | indent have do be started from the 40 | first line or above""" 41 | 42 | 43 | #%% Marker lines 44 | 45 | # An animated dark line indicates that Python is busy. 46 | import time 47 | for i in 1,2,3,4,5: 48 | print("wait for", i, '*'*i) 49 | time.sleep(1) 50 | # you can interrupt and restart the kernel with + 51 | # when you use an external python installation of your system 52 | 53 | # A red line indicates an syntax or runtime error. 54 | # The Python traceback error message is clickable. 55 | 56 | # find the syntax error 57 | a = [(1,13), (4,12), 58 | (6,11), (2,15), 59 | (1,12), (5,7)), 60 | (1,12), (5,14)] 61 | 62 | def test(x): 63 | print('We divide', x, 'by another number.') 64 | print('The result is:') 65 | print(x / 0) 66 | print('No runtime') 67 | print('error is present') 68 | print('any more.') 69 | 70 | # demonstrates a runtime error 71 | test(5) 72 | 73 | 74 | #%% Code completion and popups 75 | 76 | # A code completion list is shown for any objects. 77 | class planet: 78 | name = 'Proxima b' 79 | EarthSimularityIndex = 0.85 80 | distance = 4.2 81 | habitable = True 82 | # add a point "." after the variable to display the list 83 | planet 84 | 85 | # Code completion is also available for dictionaries. 86 | # This also works for h5py file objects. 87 | bike = { 88 | 'nWheels': 2, 89 | 'speed': 20, 90 | 'color': "blue" 91 | } 92 | # add a bracket "[" after the variable to display the list 93 | bike 94 | 95 | # add a parenthesis "(" after the function to display the doc string 96 | def twice(x, factor=2): 97 | """This function returns twice or more what it gets""" 98 | return factor*x 99 | # add a parenthesis "(" after the function to display the doc string 100 | twice 101 | 102 | #%% Autoinspection popups 103 | 104 | var1 = {'two': 2} 105 | var2 = [1,2,3] 106 | var3 = (1,2,3) 107 | var4 = "test" 108 | 109 | # Select each variable (double click) and hover with the mouse. 110 | # The type and string representation will be shown in a popup 111 | # When clicking at the popup the full content is printed in 112 | # the console. Use + in the console to remove it again. 113 | var1, var2, var3, var4, twice, time 114 | 115 | # Select the "True" and click at the popup to change to "False" 116 | swich = True 117 | 118 | 119 | #%% Console 120 | 121 | # The console window can be cleaned with the selected keyboard short cut 122 | # + + 123 | 124 | # When the console is closed, it can be restored by + + 125 | 126 | # The console has an undo buffer. print(some lines, click in the console 127 | # and press undo ( + ) to unto the print. 128 | print('1.' + ((' First long multi line output.'*3)+'\n')*3) 129 | print('2.' + ((' Second long multi line output.'*3)+'\n')*3) 130 | print('3.' + ((' Third long multi line output.'*3)+'\n')*3) 131 | 132 | 133 | #%% PythonScript 134 | 135 | # This feature is only available when the internal Python 136 | # version is used. 137 | 138 | # Interact with Notepad++ via the PythonScript library 139 | 140 | import Npp 141 | i = Npp.editor.getText().find('PythonScript lib') 142 | Npp.editor.callTipShow(i, 'Great library!!!') 143 | 144 | 145 | #%% Matplotlib 146 | 147 | # When an external Python kernel is used that has matplotlib installed, 148 | # multiple interactive plots can be plotted at the same time 149 | 150 | import matplotlib.pyplot as plt 151 | import numpy 152 | 153 | fig = plt.figure() 154 | x = numpy.linspace(0,10,500) 155 | for i in 1,2,3: 156 | y = 0.2*numpy.cumsum(numpy.random.randn(500)) 157 | plt.plot(x, y+5*i) 158 | plt.fill_between(x, y+5*i-0.1*y-1, y+5*i+0.1*y+1, alpha=0.2) 159 | plt.show() 160 | 161 | # The next figure can be shown while the first is visible 162 | 163 | fig = plt.figure() 164 | n, (r0, r1) = 100, numpy.random.rand(2) 165 | for i in range(n): 166 | t = numpy.linspace(i,(i+1),250) 167 | x = (1 - 0.9*t/n) * numpy.cos(1.5*2*numpy.pi*(t+r0)) 168 | y = (1 - 0.9*t/n) * (numpy.sin(3.008*2*numpy.pi*t) + numpy.sin(1.5*numpy.pi*(t+r1))) 169 | plt.plot(x, y, color=plt.cm.plasma(float(i)/n), alpha=0.9, lw=0.8) 170 | plt.show() 171 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /demo/selection_test.py: -------------------------------------------------------------------------------- 1 | # Perform selection test in every single line 2 | 3 | try: 1 4 | except: 2 5 | 3 6 | 7 | if True: 8 | 1 9 | elif True: 2 10 | else: 3 11 | 12 | if True: 1 13 | elif True:2 14 | else: 15 | 3 16 | 17 | if True: 1 18 | if True: 1 19 | 20 | elif True: 2 21 | # 22 | else: 3 23 | 24 | for i in 1,2: 1 25 | else: 2 26 | 27 | while 0: 1 28 | else: 2 29 | 30 | while 0: 1 31 | else: 32 | 2 33 | if True: 1 34 | 35 | for i in 1,2: 36 | 5 37 | 38 | if True: 1 39 | 40 | try: 41 | 1 42 | except: 43 | 2 44 | 45 | 3 46 | # 47 | 48 | finally: 49 | 3 50 | 51 | if True: 1 52 | 53 | a = 3 54 | b = 6 \ 55 | + 3 56 | c = 4 57 | 58 | # TODO: too many lines are selected !!! 59 | class a: 60 | def __enter__(self, *a): pass 61 | def __exit__(self, *a):pass 62 | 63 | # 64 | with a() as b,\ 65 | a() as c: 66 | if True: 67 | pass 68 | 69 | with a() as b,\ 70 | a() as c: 71 | if True: 72 | pass 73 | 74 | def test(x): 75 | pass 76 | 77 | 78 | 79 | @test 80 | @test 81 | def test2(): 82 | pass 83 | 84 | numbers = list(map(int, numbers.split(',')) # EOF error! 85 | 86 | class a: 87 | def __enter__(self, *a): pass 88 | def __exit__(self, *a): pass 89 | 90 | with a() as b,\ 91 | a() as c: 92 | if True: 93 | pass 94 | 95 | with a() as b,\ 96 | a() as c: 97 | if True: 98 | pass 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /pyPad/__init__.py: -------------------------------------------------------------------------------- 1 | # PyPadPlusPlus: A Notepad++ plugin for interactive Python development, 2 | # requires the Python Script plugin. 3 | 4 | __author__ = "Christian Schirm" 5 | __copyright__ = "Copyright 2021" 6 | __license__ = "GPLv3" 7 | __version__ = "1.3" 8 | 9 | import Npp 10 | from Npp import editor, console, notepad 11 | import sys, os 12 | PY3 = sys.version_info[0] >= 3 13 | import threading 14 | from math import sin, pi 15 | 16 | from ctypes import windll, Structure, c_ulong, byref 17 | def GetCursorPos(): 18 | point = (c_ulong*2)() 19 | windll.user32.GetCursorPos(byref(point)) 20 | return [int(i) for i in point] 21 | def GetWindowRect(hwnd): 22 | rect = (c_ulong*4)() 23 | windll.user32.GetWindowRect(hwnd, byref(rect)) 24 | return [int(i) for i in rect] 25 | VK_MBUTTON = 4 26 | 27 | init_matplotlib_eventHandler = """try: 28 | import matplotlib 29 | from matplotlib import _pylab_helpers 30 | from matplotlib.rcsetup import interactive_bk as _interactive_bk 31 | import matplotlib.pyplot 32 | pyplotShow = matplotlib.pyplot.show 33 | def show(*args, **kw): 34 | if not args and not 'block' in kw: 35 | kw['block'] = False 36 | pyplotShow(*args, **kw) 37 | matplotlib.pyplot.show = show # monkeypatch plt.show to default to non-blocking mode 38 | active_matplotlib_eventHandler = True 39 | except: pass 40 | """ 41 | 42 | class PseudoFileOut: 43 | def __init__(self, write): 44 | self.write = write 45 | def write(self, s): pass 46 | 47 | class pyPadPlusPlus: 48 | def __init__(self, externalPython=None, matplotlib_eventHandler=True, cellHighlight=True, 49 | popupForUnselectedVariable=True, popupForSelectedExpression=False, 50 | mouseDwellTime=200): 51 | '''Initializes PyPadPlusPlus to prepare Notepad++ 52 | for interactive Python development''' 53 | console.show() 54 | editor.grabFocus() 55 | self.windowHandle = windll.user32.GetForegroundWindow() 56 | 57 | sys.stdout=PseudoFileOut(Npp.console.write) 58 | sys.stderr=PseudoFileOut(Npp.console.writeError) 59 | sys.stdout.outp=PseudoFileOut(Npp.console.write) 60 | 61 | self.matplotlib_eventHandler = matplotlib_eventHandler 62 | self.matplotlib_enabled = False 63 | self.popupForUnselectedVariable = popupForUnselectedVariable 64 | self.popupForSelectedExpression = popupForSelectedExpression 65 | self.mouseDwellTime = mouseDwellTime 66 | 67 | self.externalPython = bool(externalPython) 68 | if self.externalPython: 69 | from . import pyPadHost 70 | self.interp = pyPadHost.interpreter(externalPython, outBuffer=self.outBuffer) 71 | else: 72 | from . import pyPadClient 73 | self.interp = pyPadClient.interpreter() 74 | 75 | if cellHighlight: 76 | self.lexer = EnhancedPythonLexer() 77 | self.lexer.main() 78 | else: 79 | self.lexer = None 80 | 81 | self.thread = None 82 | self.threadMarker = None 83 | self.bufferActive = 1 84 | self.delayedMarker = False 85 | self.activeCalltip = None 86 | editor.setTargetStart(0) 87 | self.specialMarkers = None 88 | self.bufferMarkerAction = {} 89 | self.lastActiveBufferID = -1 90 | 91 | # Marker 92 | self.markerWidth = 3 93 | editor.setMarginWidthN(3, self.markerWidth) 94 | editor.setMarginMaskN(3, (256+128+64) * (1 + 2**3 + 2**6)) 95 | self.markers = {} 96 | self.m_active, self.m_error, self.m_finish = [6 + 3*i for i in [0,1,2]] 97 | self.preCalculateMarkers() 98 | for iMarker in self.m_active, self.m_error, self.m_finish: 99 | self.drawMarker(iMarker) 100 | 101 | self.setCallbacks() 102 | 103 | editor.callTipSetBack((255,255,225)) 104 | editor.autoCSetSeparator(ord('\t')) 105 | editor.autoCSetIgnoreCase(False) 106 | editor.autoCSetCaseInsensitiveBehaviour(False) 107 | editor.autoCSetCancelAtStart(False) 108 | editor.autoCSetDropRestOfWord(False) 109 | 110 | console.clear() 111 | console.editor.setReadOnly(0) 112 | 113 | self.tTimerFlush = 0.15 114 | self.tTimerMiddleButton = 0.1 115 | self.middleButton = 0 116 | 117 | self.bufferActive = 0 118 | self.onTimerFlush() # start periodic timer to check output of subprocess 119 | self.onTimerMiddleButton() # start periodic timer to check state of middleButton 120 | 121 | def clearCallbacks(self): 122 | editor.clearCallbacks([Npp.SCINTILLANOTIFICATION.CALLTIPCLICK]) 123 | editor.clearCallbacks([Npp.SCINTILLANOTIFICATION.CHARADDED]) 124 | editor.clearCallbacks([Npp.SCINTILLANOTIFICATION.DWELLSTART]) 125 | editor.clearCallbacks([Npp.SCINTILLANOTIFICATION.MODIFIED]) 126 | notepad.clearCallbacks([Npp.NOTIFICATION.BUFFERACTIVATED]) 127 | notepad.clearCallbacks([Npp.NOTIFICATION.SHUTDOWN]) 128 | if self.lexer: 129 | notepad.clearCallbacks([Npp.SCINTILLANOTIFICATION.UPDATEUI]) 130 | notepad.clearCallbacks([Npp.NOTIFICATION.LANGCHANGED]) 131 | 132 | def setCallbacks(self): 133 | self.clearCallbacks() 134 | editor.setMouseDwellTime(self.mouseDwellTime) 135 | editor.callback(self.onCalltipClick, [Npp.SCINTILLANOTIFICATION.CALLTIPCLICK]) 136 | editor.callback(self.onAutocomplete, [Npp.SCINTILLANOTIFICATION.CHARADDED]) 137 | editor.callback(self.onMouseDwell, [Npp.SCINTILLANOTIFICATION.DWELLSTART]) 138 | editor.callback(self.textModified, [Npp.SCINTILLANOTIFICATION.MODIFIED]) 139 | notepad.callback(self.onBufferActivated, [Npp.NOTIFICATION.BUFFERACTIVATED]) 140 | notepad.callback(self.onShutdown, [Npp.NOTIFICATION.SHUTDOWN]) 141 | if self.lexer: 142 | editor.callbackSync(self.lexer.on_updateui, [Npp.SCINTILLANOTIFICATION.UPDATEUI]) 143 | notepad.callback(self.lexer.on_langchanged, [Npp.NOTIFICATION.LANGCHANGED]) 144 | 145 | def __del__(self): 146 | '''Clear call backs on exit.''' 147 | try: self.interp.proc.terminate() 148 | except: pass 149 | self.clearCallbacks() 150 | 151 | def onShutdown(self, args): 152 | try: self.interp.proc.terminate() 153 | except: pass 154 | 155 | def restartKernel(self): 156 | if self.externalPython: 157 | bufferID = self.bufferActive 158 | self.interp.restartKernel() 159 | if bufferID: 160 | self.changeMarkers(iMarker=self.m_error, bufferID=bufferID) 161 | self.bufferActive = 0 162 | else: 163 | self.interp.restartKernel() 164 | self.hideMarkers() 165 | self.lastActiveBufferID = -1 166 | self.setCallbacks() 167 | self.matplotlib_enabled = False 168 | 169 | def onBufferActivated(self, args): 170 | bufferID = args["bufferID"] 171 | if bufferID in self.bufferMarkerAction: 172 | iMarker = self.bufferMarkerAction.pop(bufferID) 173 | self.changeMarkers(iMarker, bufferID) 174 | if self.lexer: 175 | self.lexer.on_bufferactivated(args) 176 | 177 | def onTimerMiddleButton(self): 178 | middleButton = windll.user32.GetKeyState(VK_MBUTTON) 179 | if self.middleButton != middleButton and (middleButton - (middleButton & 1)) != 0: 180 | x,y = GetCursorPos() 181 | hFore = windll.user32.GetForegroundWindow() 182 | hPoint = windll.user32.WindowFromPoint(x,y) 183 | if hPoint == hFore: 184 | hPoint = windll.user32.ChildWindowFromPoint(hFore, x,y) 185 | hSelf = self.windowHandle 186 | x0,y0,x1,y1 = GetWindowRect(hPoint) 187 | if x0 <= x <= x1 and y0 <= y <= y1 and hSelf == hFore: 188 | editor.grabFocus() 189 | pos = editor.positionFromPoint(x-x0, y-y0) 190 | iLineClick = editor.lineFromPosition(pos) 191 | iStart = editor.getSelectionStart() 192 | iEnd = editor.getSelectionEnd() 193 | iLineStart = editor.lineFromPosition(iStart) 194 | iLineEnd = editor.lineFromPosition(iEnd) 195 | if iStart != iEnd and iLineStart <= iLineClick <= iLineEnd: 196 | self.runCodeAtCursor(moveCursor=False, onlyInsideCodeLines=True) 197 | elif 0 <= pos < editor.getLength(): 198 | self.runCodeAtCursor(moveCursor=False, nonSelectedLine=iLineClick, onlyInsideCodeLines=True) 199 | self.middleButton = middleButton 200 | threading.Timer(self.tTimerMiddleButton, self.onTimerMiddleButton).start() 201 | 202 | def onTimerFlush(self): 203 | #if not self.interp.active(): 204 | try: 205 | r = self.interp.flush() 206 | if r is not None: 207 | err, result = r 208 | if result: 209 | self.outBuffer(result) 210 | except: 211 | pass 212 | threading.Timer(self.tTimerFlush, self.onTimerFlush).start() 213 | 214 | def textModified(self, args): 215 | '''When the marked text is modified the execution markers 216 | will be hidden, except when the code is still running.''' 217 | if args['text'] != '': 218 | bufferID = notepad.getCurrentBufferID() 219 | if self.markers.get(bufferID, None) is not None and not self.bufferActive and len(self.markers[bufferID]) > 0: 220 | iCurrentLine = editor.lineFromPosition(editor.getCurrentPos()) 221 | iLines = [] 222 | for i in self.markers[bufferID]: 223 | iLine = editor.markerLineFromHandle(i) 224 | iLines.append(iLine) 225 | if min(iLines) <= iCurrentLine <= max(iLines): 226 | self.hideMarkers(bufferID) 227 | if self.markers.get(bufferID, None) is not None and self.bufferActive and len(self.markers[bufferID]) > 0: 228 | iCurrentLine = editor.lineFromPosition(editor.getCurrentPos()) 229 | iLines = [] 230 | for i in self.markers[bufferID]: 231 | iLine = editor.markerLineFromHandle(i) 232 | iLines.append(iLine) 233 | if len(iLines) > 0 and min(iLines) <= iCurrentLine <= max(iLines): 234 | self.setMarkers(min(iLines), max(iLines), iMarker=self.m_active, bufferID=bufferID, startAnimation=False) 235 | 236 | def runCodeAtCursor(self, moveCursor=True, nonSelectedLine=None, onlyInsideCodeLines=False): 237 | '''Executes the smallest possible code element for 238 | the current selection. Or execute one marked cell.''' 239 | if not self.bufferActive: 240 | self.thread = threading.Thread(target=self.runThread, args=(moveCursor, nonSelectedLine, onlyInsideCodeLines)) 241 | self.thread.start() 242 | 243 | def runThread(self, moveCursor=True, nonSelectedLine=None, onlyInsideCodeLines=False): 244 | '''Executes the smallest possible code element for 245 | the current selection. Or execute one marked cell.''' 246 | 247 | bufferID = notepad.getCurrentBufferID() 248 | self.bufferActive = bufferID 249 | lang = notepad.getLangType() 250 | filename = notepad.getCurrentFilename() 251 | if lang == Npp.LANGTYPE.TXT and '.' not in os.path.basename(filename): 252 | notepad.setLangType(Npp.LANGTYPE.PYTHON) 253 | elif lang != Npp.LANGTYPE.PYTHON: 254 | self.bufferActive = 0 255 | return 256 | 257 | if nonSelectedLine is None: 258 | iSelStart = editor.getSelectionStart() 259 | iSelEnd = editor.getSelectionEnd() 260 | iPos = editor.getCurrentPos() 261 | iLineCursor = iLineStart = editor.lineFromPosition(iSelStart) 262 | iLineEnd = max(iLineStart, editor.lineFromPosition(iSelEnd-1)) 263 | else: 264 | iLineCursor = iLineStart = iLineEnd = nonSelectedLine 265 | iSelStart = iSelEnd = 0 266 | selection = iSelStart != iSelEnd 267 | startLine = editor.getLine(iLineStart).rstrip() 268 | cellMode = not selection and (startLine.startswith('#%%') or startLine.startswith('# %%')) 269 | err = None 270 | if not cellMode: 271 | getLineEnd = self.completeBlockEnd(iLineStart, iLineMin=iLineEnd, iLineMax=editor.getLineCount()-1) 272 | iFirstCodeLine, iLineEnd, isEmpty, inspectLineBefore = next(getLineEnd) 273 | if not inspectLineBefore and iFirstCodeLine: 274 | iLineStart = iFirstCodeLine 275 | if isEmpty: 276 | self.hideMarkers(bufferID) 277 | self.bufferActive = 0 278 | return 279 | iLineStart = self.completeBlockStart(iLineStart, inspectLineBefore) 280 | 281 | requireMore = True 282 | 283 | iStart = editor.positionFromLine(iLineStart) 284 | iDocEnd = editor.getLength() 285 | 286 | if cellMode: 287 | iMatch = [] 288 | editor.research('^# ?%%(.*)$', lambda m: iMatch.append(m.span(0)[0]-1), 0, iStart+4, iDocEnd-1, 1) 289 | iEnd = iMatch[0] if len(iMatch) else iDocEnd 290 | iLineEnd = editor.lineFromPosition(iEnd) 291 | block = editor.getTextRange(iStart, iEnd).rstrip() 292 | r = self.interp.tryCode(iLineStart, filename, block) 293 | if r is None: 294 | self.hideMarkers(bufferID) 295 | self.bufferActive = 0 296 | return 297 | err, requireMore, isValue = r 298 | if requireMore: 299 | err = True 300 | 301 | else: 302 | # add more lines until the parser is happy or finds 303 | # a syntax error 304 | 305 | while requireMore: 306 | iEnd = editor.getLineEndPosition(iLineEnd) 307 | block = editor.getTextRange(iStart, iEnd).rstrip() 308 | if block: 309 | res = self.interp.tryCode(iLineStart, filename, block) 310 | if res is None: 311 | self.bufferActive = 0 312 | return 313 | else: 314 | err, requireMore, isValue = res 315 | else: err, requireMore, isValue = None, True, False 316 | if requireMore: 317 | nextLine = next(getLineEnd, None) 318 | if nextLine is None: 319 | self.bufferActive = 0 320 | iEnd = editor.getLength() 321 | block = editor.getTextRange(iStart, iEnd).rstrip() 322 | err, buff = self.interp.execute(block,iLineStart,filename) 323 | self.outBuffer(buff) 324 | self.setMarkers(iLineStart, iLineEnd, block, iMarker=self.m_error, bufferID=bufferID) 325 | return 326 | iCodeLineStart, iLineEnd, isEmpty, inspectLineBefore = nextLine 327 | 328 | if onlyInsideCodeLines and not selection and not iLineStart <= iLineCursor <= iLineEnd: 329 | self.hideMarkers() 330 | self.bufferActive = 0 331 | return 332 | 333 | if self.activeCalltip: 334 | editor.callTipCancel() 335 | self.activeCalltip = None 336 | 337 | self.setMarkers(iLineStart, iLineEnd, block, iMarker=(self.m_active if not err else self.m_error), bufferID=bufferID) 338 | 339 | if err is not None: 340 | if moveCursor: 341 | editor.setSelectionStart(iStart) 342 | editor.scrollRange(iEnd, iStart) 343 | if err is not True: self.outBuffer(err) 344 | 345 | else: 346 | 347 | # Check if correct path is set 348 | if self.lastActiveBufferID != bufferID and '.' in os.path.basename(filename): 349 | filePath = os.path.normpath(os.path.split(filename)[0]) 350 | self.interp.execute('os.chdir('+repr(filePath)+')') 351 | self.lastActiveBufferID = bufferID 352 | 353 | # Start a thread to execute the code 354 | if moveCursor: 355 | iNewPos = max(iPos, editor.positionFromLine(iLineEnd + 1)) 356 | editor.setSelectionStart(iNewPos) 357 | editor.setCurrentPos(iNewPos) 358 | if iNewPos >= iDocEnd and iLineEnd == editor.getLineCount()-1: 359 | editor.newLine() 360 | editor.scrollCaret() 361 | 362 | if self.matplotlib_eventHandler and not self.matplotlib_enabled: 363 | if 'matplotlib' in block: 364 | self.interp.execute(init_matplotlib_eventHandler) 365 | self.matplotlib_enabled = True 366 | 367 | if isValue: 368 | res = self.interp.evaluate() 369 | if res is not None: 370 | err, result = res 371 | if not err: 372 | if self.bufferActive: 373 | self.changeMarkers(iMarker=self.m_finish, bufferID=bufferID) 374 | if result: self.stdout(result+'\n') 375 | else: 376 | self.changeMarkers(iMarker=self.m_error, bufferID=bufferID) 377 | self.outBuffer(result) 378 | 379 | else: 380 | res = self.interp.execute() 381 | if res is not None: 382 | err, result = res 383 | if not err and self.bufferActive: 384 | self.changeMarkers(iMarker=self.m_finish, bufferID=bufferID) 385 | else: 386 | self.changeMarkers(iMarker=self.m_error, bufferID=bufferID) 387 | self.outBuffer(result) 388 | 389 | if err: 390 | self.changeMarkers(iMarker=self.m_error, bufferID=bufferID) 391 | 392 | self.bufferActive = 0 393 | 394 | def getUncompleteLine(self, iPos): 395 | '''get the whole expression with the context of a 396 | variable that is required to evaluate the variable''' 397 | iLine = editor.lineFromPosition(iPos) 398 | iStart = editor.positionFromLine(iLine) 399 | linePart = editor.getTextRange(iStart, iPos - 1) 400 | return linePart 401 | 402 | def completeBlockStart(self, iLine, inspectLineBefore): 403 | '''Add preceding lines that are required to execute 404 | the selected code, e.g. the beginning of an indented 405 | code block.''' 406 | iFirstCodeLine = iLine 407 | satisfied = False 408 | while iLine >= 0: 409 | line = editor.getLine(iLine).rstrip() 410 | isCodeLine = len(line) > 0 and not line.lstrip().startswith('#') 411 | isDecorator = line.startswith('@') 412 | if satisfied and not isDecorator: 413 | break 414 | isIndent = isCodeLine and (line.startswith(' ') or line.startswith('\t')) 415 | requireLineBefore = isIndent or line.startswith('else:') or line.startswith('elif') \ 416 | or line.startswith('except:') or line.startswith('finally:') 417 | inspectLineBefore = line.startswith('def ') or inspectLineBefore or requireLineBefore 418 | satisfied = isCodeLine and not (requireLineBefore or inspectLineBefore) 419 | satisfied = satisfied or not (requireLineBefore or isCodeLine or inspectLineBefore) 420 | if isDecorator: 421 | satisfied = False 422 | if satisfied: 423 | break 424 | if isCodeLine: 425 | iFirstCodeLine = iLine 426 | if not (requireLineBefore or isIndent): 427 | inspectLineBefore = False 428 | satisfied = True 429 | iLine -= 1 430 | return max(0, iFirstCodeLine) 431 | 432 | def completeBlockEnd(self, iLine, iLineMin, iLineMax, isEmpty=True, inspectLineBefore=False): 433 | '''Add following lines that are required to execute 434 | the selected code, without leaving code that cannot 435 | be executed seperately in the next step.''' 436 | iLastCodeLine = iLine 437 | iFirstCodeLine = None 438 | inspectLineAfter = False 439 | isFirstCodeLine = True 440 | while iLine <= iLineMax: 441 | line = editor.getLine(iLine).rstrip() 442 | isCodeLine = len(line) > 0 and not line.lstrip().startswith('#') 443 | isIndent = isCodeLine and (line.startswith(' ') or line.startswith('\t')) 444 | thisLineIsRequiredAndMaybeMore = line.startswith('elif') or line.startswith('except:') 445 | thisLineIsRequired = line.startswith('else:') or line.startswith('finally:') \ 446 | or thisLineIsRequiredAndMaybeMore 447 | mightRequireLineAfter = (thisLineIsRequiredAndMaybeMore or isFirstCodeLine and \ 448 | (line.startswith('if ') or line.startswith('for ') or line.startswith('while ') 449 | )) and not inspectLineAfter 450 | if thisLineIsRequired or isIndent or mightRequireLineAfter: 451 | inspectLineAfter = True 452 | if thisLineIsRequired: isCodeLine = True 453 | if isEmpty and isIndent: inspectLineBefore = True 454 | if isCodeLine: 455 | isEmpty = False 456 | if not thisLineIsRequired and not mightRequireLineAfter: 457 | inspectLineAfter = False 458 | if iFirstCodeLine is None: 459 | iFirstCodeLine = iLine 460 | if thisLineIsRequired or iLine <= iLineMin: 461 | iLastCodeLine = iLine 462 | if isCodeLine and line.endswith('\\'): 463 | inspectLineAfter = True 464 | satisfied = not isIndent and isCodeLine and not inspectLineAfter 465 | if iLine >= iLineMin and satisfied: 466 | yield iFirstCodeLine, iLastCodeLine, isEmpty, inspectLineBefore 467 | if isCodeLine: 468 | iLastCodeLine = iLine 469 | isFirstCodeLine = False 470 | iLine += 1 471 | yield iFirstCodeLine, iLastCodeLine, isEmpty, inspectLineBefore 472 | 473 | def preCalculateMarkers(self): 474 | if self.specialMarkers is None: 475 | self.specialMarkers = {} 476 | fade = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 477 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 478 | 255, 255, 255, 255, 255, 255, 255, 252, 246, 240, 234, 228, 223, 479 | 217, 211, 205, 199, 193, 188, 182, 176, 170, 164, 159, 153, 147, 480 | 141, 135, 130, 124, 118, 112, 106, 101, 95, 89, 83, 77, 71, 66, 481 | 60, 54, 48, 42, 37, 31, 25] 482 | self.markerHeight = len(fade) 483 | 484 | # pre-calculate animated "active" marker 485 | if PY3: 486 | def char(x): return b'%c'%x 487 | def join(x): return b''.join(x) 488 | else: 489 | def char(x): return chr(x) 490 | def join(x): return ''.join(x) 491 | animation = [] 492 | for iCycle in range(10): 493 | n = len(fade) 494 | nh = n//2 495 | rgba = [] 496 | rgba_r = [] 497 | c1 = 110, 110, 110 # basic color 498 | c2 = 170, 175, 200 # second color 499 | for iFade,f in enumerate(fade): 500 | x = min(0, -(iFade - nh)) 501 | a = sin(pi*(4*(x / float(n))**2 - iCycle / 10.))**2 502 | rgb = join([char(int(c1[i]*(1-a)+c2[i]*a)) for i in [0,1,2]]) + char(f) 503 | rgba.append(rgb*self.markerWidth) 504 | x = -min(0, (iFade - nh)) 505 | a = sin(pi*(4*(x / float(n))**2 + iCycle / 10.))**2 506 | rgb = join([char(int(c1[i]*(1-a)+c2[i]*a)) for i in [0,1,2]]) + char(fade[n-1-iFade]) 507 | rgba_r.append(rgb*self.markerWidth) 508 | rgb = tuple([(int(c1[i]*(1-a)+c2[i]*a)) for i in [0,1,2]]) 509 | rgba = join(rgba) 510 | rgba_r = join(rgba_r) 511 | animation.append((rgb, rgba, rgba_r)) 512 | self.specialMarkers[self.m_active] = animation 513 | 514 | # pre-calculate marker for "finish" and "error". 515 | for iMarker, c in ((self.m_finish, (255,220,0)), 516 | (self.m_error, (255,100,100))): 517 | rgb = char(c[0])+char(c[1])+char(c[2]) 518 | rgba = join([(rgb+char(f))*self.markerWidth for f in fade]) 519 | rgba_r = join([(rgb+char(f))*self.markerWidth for f in reversed(fade)]) 520 | rgb = c 521 | self.specialMarkers[iMarker] = rgb, rgba, rgba_r 522 | 523 | def drawMarker(self, iMarker, cycle=0): 524 | # load special marker RGBA images 525 | if iMarker == self.m_active: 526 | rgb, rgba, rgba_r = self.specialMarkers[iMarker][cycle] 527 | else: 528 | rgb, rgba, rgba_r = self.specialMarkers[iMarker] 529 | 530 | editor.rGBAImageSetWidth(self.markerWidth) 531 | editor.rGBAImageSetHeight(self.markerHeight) 532 | editor.markerDefine(iMarker, Npp.MARKERSYMBOL.LEFTRECT) 533 | editor.markerSetBack(iMarker, rgb) 534 | editor.markerDefineRGBAImage(iMarker+1, rgba) 535 | editor.markerDefine(iMarker+1, Npp.MARKERSYMBOL.RGBAIMAGE) 536 | editor.markerDefineRGBAImage(iMarker+2, rgba_r) 537 | editor.markerDefine(iMarker+2, Npp.MARKERSYMBOL.RGBAIMAGE) 538 | 539 | def setMarkers(self, iLineStart, iLineEnd, block=None, iMarker=None, bufferID=None, startAnimation=True): 540 | '''Set markers at the beginning and end of the executed 541 | code block, to show the user which part is actually executed 542 | and if the code is still running or finished or if errors 543 | occurred.''' 544 | if block: 545 | lineHasCode = [len(line) > 0 and not (line.isspace() or line.startswith('#')) for line in block.splitlines()] 546 | linesWithCode = [i for i, c in enumerate(lineHasCode) if c] 547 | iLineEnd = iLineStart + linesWithCode[-1] 548 | iLineStart = iLineStart + linesWithCode[0] 549 | nMarkedLines = iLineEnd - iLineStart + 1 550 | markerIDs = [] 551 | if bufferID is None: 552 | bufferID = notepad.getCurrentBufferID() 553 | self.hideMarkers(bufferID) 554 | if nMarkedLines <= 4: 555 | for iLine in range(nMarkedLines): 556 | markerIDs.append(editor.markerAdd(iLineStart+iLine, iMarker)) 557 | else: 558 | markerIDs.append(editor.markerAdd(iLineStart, iMarker)) 559 | markerIDs.append(editor.markerAdd(iLineStart+1, iMarker+1)) 560 | markerIDs.append(editor.markerAdd(iLineEnd, iMarker)) 561 | markerIDs.append(editor.markerAdd(iLineEnd-1, iMarker+2)) 562 | self.markers[bufferID] = markerIDs 563 | if startAnimation and iMarker == self.m_active: 564 | self.onMarkerTimer(init=True) 565 | 566 | def onMarkerTimer(self, init=False): 567 | if self.bufferActive: 568 | if init: 569 | self.markerCycle = 0 570 | else: 571 | self.markerCycle = (self.markerCycle + 1) % 10 572 | self.drawMarker(self.m_active, cycle=self.markerCycle) 573 | self.threadMarker = threading.Timer(0.1, self.onMarkerTimer) 574 | self.threadMarker.start() 575 | else: 576 | self.drawMarker(self.m_active) 577 | self.threadMarker = None 578 | 579 | def changeMarkers(self, iMarker, bufferID=None): 580 | if bufferID != notepad.getCurrentBufferID(): 581 | self.bufferMarkerAction[bufferID] = iMarker 582 | return 583 | iLines = [] 584 | for i in self.markers[bufferID]: 585 | iLine = editor.markerLineFromHandle(i) 586 | #if iLine == -1: 587 | # notepad.activateBufferID(bufferID) 588 | # iLine = editor.markerLineFromHandle(i) 589 | iLines.append(iLine) 590 | if iLines: 591 | self.setMarkers(min(iLines), max(iLines), iMarker=iMarker, bufferID=bufferID) 592 | 593 | def hideMarkers(self, bufferID=None): 594 | '''Hide all markers of the current buffer ID.''' 595 | if bufferID is None: bufferID = notepad.getCurrentBufferID() 596 | markers = self.markers.get(bufferID,[]) 597 | while markers: 598 | editor.markerDeleteHandle(markers.pop()) 599 | 600 | def stdout(self, s): 601 | console.editor.beginUndoAction() 602 | console.write(s) 603 | console.editor.endUndoAction() 604 | console.editor.setReadOnly(0) 605 | 606 | def stderr(self, s): 607 | console.editor.beginUndoAction() 608 | console.writeError(s) 609 | console.editor.endUndoAction() 610 | console.editor.setReadOnly(0) 611 | 612 | def outBuffer(self, buffer): 613 | console.editor.beginUndoAction() 614 | out = [] 615 | mode = True 616 | for err, line in buffer: 617 | if err: 618 | console.writeError(line) 619 | else: console.write(line) 620 | console.editor.endUndoAction() 621 | console.editor.setReadOnly(0) 622 | 623 | def onMouseDwell(self, args): 624 | '''Show a call tip window about the current content 625 | of a selected variable''' 626 | #if self.bufferActive or self.interp.active(): return 627 | #if editor.callTipActive(): return 628 | pos = editor.positionFromPoint(args['x'], args['y']) 629 | self.showCalltip(pos) 630 | 631 | def showCalltip(self, pos=None): 632 | iStart = editor.getSelectionStart() 633 | iEnd = editor.getSelectionEnd() 634 | if pos is None: 635 | pos = editor.getCurrentPos() 636 | CT_unselected = True 637 | CT_expression = True 638 | else: 639 | CT_unselected = self.popupForUnselectedVariable 640 | CT_expression = self.popupForSelectedExpression 641 | if iEnd != iStart and iStart <= pos <= iEnd: 642 | if CT_expression and iEnd - iStart > 1: 643 | expression = editor.getTextRange(iStart, iEnd) 644 | if expression =='False': 645 | self.activeCalltip = False 646 | editor.callTipShow(iStart, 'set to True') 647 | elif expression =='True': 648 | self.activeCalltip = True 649 | editor.callTipShow(iStart, 'set to False') 650 | elif not '\n' in expression: 651 | ret = self.interp.getCallTip(None, expression) 652 | if ret and (CT_unselected or ret[-1] != 'value error'): 653 | element, nHighlight, calltip = ret 654 | self.activeCalltip = 'doc' 655 | editor.callTipShow(iStart, ''.join(calltip)) 656 | editor.callTipSetHlt(0, int(nHighlight)) 657 | else: 658 | iLineStart = editor.positionFromLine(editor.lineFromPosition(iStart)) 659 | var = editor.getTextRange(iStart, iEnd) 660 | line = editor.getTextRange(iLineStart, iEnd) 661 | if var == '.': 662 | autoCompleteList = self.interp.autoCompleteObject(self.getUncompleteLine(iStart+1)) 663 | if autoCompleteList: 664 | editor.autoCSetSeparator(ord('\t')) 665 | editor.autoCSetIgnoreCase(False) 666 | editor.autoCSetCaseInsensitiveBehaviour(False) 667 | editor.autoCSetOrder(0) 668 | editor.autoCSetDropRestOfWord(True) 669 | editor.autoCShow(0, autoCompleteList) 670 | else: 671 | ret = self.interp.getCallTip(line, var) 672 | if ret: 673 | element, nHighlight, calltip = ret 674 | if element == var =='False': 675 | self.activeCalltip = False 676 | editor.callTipShow(iStart, 'set to True') 677 | elif element == var =='True': 678 | self.activeCalltip = True 679 | editor.callTipShow(iStart, 'set to False') 680 | elif ret[-1] != 'value error': 681 | self.activeCalltip = 'doc' 682 | editor.callTipShow(iStart, ''.join(calltip)) 683 | editor.callTipSetHlt(0, int(nHighlight)) 684 | elif CT_unselected and iStart == iEnd and pos >= 0: 685 | iLine = editor.lineFromPosition(pos) 686 | line = editor.getLine(iLine) 687 | iLineStart = editor.positionFromLine(iLine) 688 | posInLine = pos - iLineStart 689 | iWordEnd=0 690 | for iWordStart in range(posInLine, -1, -1): 691 | s = line[iWordStart] 692 | if not ('a' <= s <= 'z' or 'A' <= s <= 'Z' or '0' <= s <= '9' or s == '_'): 693 | iWordStart += 1 694 | break 695 | if iWordStart <= posInLine: 696 | for iWordEnd in range(posInLine+1, len(line)): 697 | s = line[iWordEnd] 698 | if not ('a' <= s <= 'z' or 'A' <= s <= 'Z' or '0' <= s <= '9' or s == '_'): 699 | iWordEnd -= 1 700 | break 701 | var = line[iWordStart:iWordEnd+1] 702 | if var: 703 | var = line[iWordStart:iWordEnd+1] 704 | ret = self.interp.getCallTip(line[0:iWordEnd+1], var) 705 | pos = iLineStart + iWordStart 706 | if ret: 707 | element, nHighlight, calltip = ret 708 | if calltip != 'value error': 709 | self.activeCalltip = 'doc' 710 | editor.callTipShow(pos, ''.join(calltip)) 711 | editor.callTipSetHlt(0, int(nHighlight)) 712 | 713 | 714 | def onCalltipClick(self, args): 715 | '''When clicked on the calltip write the full calltip in the output console.''' 716 | if self.activeCalltip == 'doc':# and args['position']==0: 717 | var, calltip = self.interp.getFullCallTip() 718 | head = '='*(40 - len(var)//2 - 3) + ' Info: ' + var + ' ' + '='*(40 - len(var)//2 - 3) 719 | foot = '='*len(head) 720 | self.stdout('\n' + head + '\n' + ''.join(calltip) + '\n' + foot + '\n') 721 | elif self.activeCalltip == True: 722 | editor.replaceSel('False') 723 | elif self.activeCalltip == False: 724 | editor.replaceSel('True') 725 | editor.callTipCancel() 726 | self.activeCalltip = None 727 | 728 | def onAutocomplete(self, args): 729 | '''Check if auto complete data can be added and displayed: 730 | "." after objects: show auto completion list with properties and methods 731 | "[" after dict: show auto completion list with keys 732 | "(" after functions: insert template and display a call tip with the doc string.''' 733 | if args['ch'] == 46 and args['code'] == 2001: # character "." 734 | iPos = editor.getCurrentPos() 735 | autoCompleteList = self.interp.autoCompleteObject(self.getUncompleteLine(iPos)) 736 | if autoCompleteList is None: return 737 | if autoCompleteList: 738 | editor.autoCSetSeparator(ord('\t')) 739 | editor.autoCSetIgnoreCase(False) 740 | editor.autoCSetCaseInsensitiveBehaviour(False) 741 | editor.autoCSetOrder(2) 742 | editor.autoCSetDropRestOfWord(True) 743 | editor.autoCShow(0, autoCompleteList) 744 | elif args['ch'] == 40 and args['code'] == 2001: # character "(" 745 | iPos = editor.getCurrentPos() 746 | r = self.interp.autoCompleteFunction(self.getUncompleteLine(iPos)) 747 | if r is None: return 748 | n, funcParam, callTip = r 749 | if callTip: 750 | editor.callTipShow(max(0,iPos-n), callTip) 751 | editor.callTipSetHlt(0, max(0, callTip.find('\n'))) 752 | self.activeCalltip = 'doc' 753 | if funcParam and iPos == editor.getCurrentPos(): 754 | editor.insertText(iPos,funcParam+')') 755 | editor.setSelectionStart(iPos) 756 | editor.setSelectionStart(iPos + len(funcParam) + 1) 757 | editor.setCurrentPos(iPos) 758 | elif args['ch'] == 91 and args['code'] == 2001: # character "[" 759 | iPos = editor.getCurrentPos() 760 | autoCompleteList = self.interp.autoCompleteDict(self.getUncompleteLine(iPos)) 761 | if autoCompleteList: 762 | editor.autoCSetSeparator(ord('\t')) 763 | editor.autoCSetIgnoreCase(False) 764 | editor.autoCSetCaseInsensitiveBehaviour(False) 765 | editor.autoCSetOrder(0) 766 | editor.autoCSetDropRestOfWord(True) 767 | editor.autoCShow(0, autoCompleteList) 768 | 769 | 770 | # lexer for special comments "#%%" for block execution 771 | class EnhancedPythonLexer(object): 772 | def __init__(self): 773 | self.__is_lexer_doc = False 774 | self.get_lexer_name = lambda: notepad.getLanguageName(notepad.getLangType()) 775 | self.indicator = 0 776 | 777 | @staticmethod 778 | def paint_it(indicator, pos, length): 779 | current_line = editor.lineFromPosition(pos) 780 | editor.setIndicatorCurrent(indicator) 781 | editor.indicatorFillRange(pos,length) 782 | 783 | def style(self): 784 | line_number = editor.getFirstVisibleLine() 785 | start_position = editor.positionFromLine(line_number) 786 | end_position = editor.getLineEndPosition(line_number + editor.linesOnScreen()) 787 | editor.setIndicatorCurrent(self.indicator) 788 | editor.indicatorClearRange(start_position, end_position-start_position) 789 | 790 | flag = 0 791 | editor.research('^# ?%%(.*)$', lambda m: self.paint_it(self.indicator, m.span(flag)[0], 792 | m.span(flag)[1] - m.span(flag)[0]), 0, start_position, end_position) 793 | 794 | def set_lexer_doc(self,bool_value): 795 | editor.setProperty(self.__class__.__name__, 1 if bool_value is True else -1) 796 | self.__is_lexer_doc = bool_value 797 | 798 | def on_bufferactivated(self,args): 799 | if (self.get_lexer_name() == self.lexer_name):# and (editor.getPropertyInt(self.__class__.__name__) != -1): 800 | self.__is_lexer_doc = True 801 | else: 802 | self.__is_lexer_doc = False 803 | 804 | def on_updateui(self,args): 805 | if self.__is_lexer_doc: 806 | self.style() 807 | 808 | def on_langchanged(self,args): 809 | self.set_lexer_doc(True if self.get_lexer_name() == self.lexer_name else False) 810 | 811 | def main(self): 812 | self.lexer_name = 'Python' 813 | editor.indicSetFore(self.indicator, (80, 160, 120)) 814 | editor.indicSetStyle(self.indicator, Npp.INDICATORSTYLE.COMPOSITIONTHICK) 815 | self.set_lexer_doc(True) 816 | self.style() 817 | -------------------------------------------------------------------------------- /pyPad/introspect.py: -------------------------------------------------------------------------------- 1 | # This file was taken from the wxPython project. 2 | # Slightly modified version for the use in pyPadPlusPlus. 3 | # License see original: 4 | # https://github.com/wxWidgets/Phoenix/blob/master/wx/py/introspect.py 5 | 6 | """Provides a variety of introspective-type support functions for 7 | things like call tips and command auto completion.""" 8 | 9 | __author__ = "Patrick K. O'Brien " 10 | 11 | import io 12 | import inspect 13 | import tokenize 14 | 15 | def getAutoCompleteList(command='', locals=None, includeMagic=1, 16 | includeSingle=1, includeDouble=1): 17 | """Return list of auto-completion options for command. 18 | 19 | The list of options will be based on the locals namespace.""" 20 | attributes = [] 21 | # Get the proper chunk of code from the command. 22 | root = getRoot(command, terminator='.') 23 | try: 24 | if locals is not None: 25 | obj = eval(root, locals) 26 | else: 27 | obj = eval(root) 28 | except: 29 | pass 30 | else: 31 | attributes = getAttributeNames(obj, includeMagic, 32 | includeSingle, includeDouble) 33 | return attributes 34 | 35 | def getAttributeNames(obj, includeMagic=1, includeSingle=1, 36 | includeDouble=1): 37 | """Return list of unique attributes, including inherited, for obj.""" 38 | attributes = [] 39 | dict = {} 40 | if not hasattrAlwaysReturnsTrue(obj): 41 | # Add some attributes that don't always get picked up. 42 | special_attrs = ['__bases__', '__class__', '__dict__', '__name__', 43 | 'func_closure', 'func_code', 'func_defaults', 44 | 'func_dict', 'func_doc', 'func_globals', 'func_name'] 45 | attributes += [attr for attr in special_attrs \ 46 | if hasattr(obj, attr)] 47 | if includeMagic: 48 | try: attributes += obj._getAttributeNames() 49 | except: pass 50 | # Special code to allow traits to be caught by autocomplete 51 | if hasattr(obj,'trait_get'): 52 | try: 53 | for i in obj.trait_get().keys(): 54 | if i not in attributes: 55 | if hasattr(obj, i): 56 | attributes += i 57 | except: 58 | pass 59 | # Get all attribute names. 60 | str_type = str(type(obj)) 61 | if str_type == "": 62 | attributes += dir(obj) 63 | else: 64 | attrdict = getAllAttributeNames(obj) 65 | # Store the obj's dir. 66 | obj_dir = dir(obj) 67 | for (obj_type_name, technique, count), attrlist in attrdict.items(): 68 | # This complexity is necessary to avoid accessing all the 69 | # attributes of the obj. This is very handy for objects 70 | # whose attributes are lazily evaluated. 71 | if type(obj).__name__ == obj_type_name and technique == 'dir': 72 | attributes += attrlist 73 | else: 74 | attributes += [attr for attr in attrlist \ 75 | if attr not in obj_dir and hasattr(obj, attr)] 76 | 77 | # Remove duplicates from the attribute list. 78 | for item in attributes: 79 | dict[item] = None 80 | attributes = dict.keys() 81 | # new-style swig wrappings can result in non-string attributes 82 | # e.g. ITK http://www.itk.org/ 83 | attributes = [attribute for attribute in attributes \ 84 | if type(attribute) == str] 85 | attributes.sort(key=lambda x: x.upper()) 86 | if not includeSingle: 87 | attributes = filter(lambda item: item[0]!='_' \ 88 | or item[1:2]=='_', attributes) 89 | if not includeDouble: 90 | attributes = filter(lambda item: item[:2]!='__', attributes) 91 | return attributes 92 | 93 | def hasattrAlwaysReturnsTrue(obj): 94 | return hasattr(obj, 'bogu5_123_aTTri8ute') 95 | 96 | def getAllAttributeNames(obj): 97 | """Return dict of all attributes, including inherited, for an object. 98 | 99 | Recursively walk through a class and all base classes. 100 | """ 101 | attrdict = {} # (object, technique, count): [list of attributes] 102 | # !!! 103 | # Do Not use hasattr() as a test anywhere in this function, 104 | # because it is unreliable with remote objects: xmlrpc, soap, etc. 105 | # They always return true for hasattr(). 106 | # !!! 107 | try: 108 | # This could(?) fail if the type is poorly defined without 109 | # even a name. 110 | key = type(obj).__name__ 111 | except Exception: 112 | key = 'anonymous' 113 | # Wake up sleepy objects - a hack for ZODB objects in "ghost" state. 114 | wakeupcall = dir(obj) 115 | del wakeupcall 116 | # Get attributes available through the normal convention. 117 | attributes = dir(obj) 118 | attrdict[(key, 'dir', len(attributes))] = attributes 119 | # Get attributes from the object's dictionary, if it has one. 120 | try: 121 | attributes = sorted(obj.__dict__.keys()) 122 | except Exception: # Must catch all because object might have __getattr__. 123 | pass 124 | else: 125 | attrdict[(key, '__dict__', len(attributes))] = attributes 126 | # For a class instance, get the attributes for the class. 127 | try: 128 | klass = obj.__class__ 129 | except: # Must catch all because object might have __getattr__. 130 | pass 131 | else: 132 | if klass is obj: 133 | # Break a circular reference. This happens with extension 134 | # classes. 135 | pass 136 | else: 137 | attrdict.update(getAllAttributeNames(klass)) 138 | # Also get attributes from any and all parent classes. 139 | try: 140 | bases = obj.__bases__ 141 | except: # Must catch all because object might have __getattr__. 142 | pass 143 | else: 144 | if isinstance(bases, tuple): 145 | for base in bases: 146 | if type(base) is type: 147 | # Break a circular reference. Happens in Python 2.2. 148 | pass 149 | else: 150 | attrdict.update(getAllAttributeNames(base)) 151 | return attrdict 152 | 153 | def getCallTip(command='', locals=None): 154 | """For a command, return a tuple of object name, argspec, tip text. 155 | 156 | The call tip information will be based on the locals namespace.""" 157 | calltip = ('', '', '') # object name, argspec, tip text. 158 | # Get the proper chunk of code from the command. 159 | root = getRoot(command, terminator='(') 160 | try: 161 | if locals is not None: 162 | obj = eval(root, locals) 163 | else: 164 | obj = eval(root) 165 | except: 166 | return calltip 167 | name = '' 168 | obj, dropSelf = getBaseObject(obj) 169 | try: 170 | name = obj.__name__ 171 | except AttributeError: 172 | pass 173 | tip1 = '' 174 | argspec = '' 175 | if inspect.isbuiltin(obj): 176 | # Builtin functions don't have an argspec that we can get. 177 | pass 178 | elif inspect.isfunction(obj): 179 | # tip1 is a string like: "getCallTip(command='', locals=None)" 180 | argspec = inspect.getfullargspec(obj) 181 | argspec = inspect.formatargspec(*argspec) 182 | if dropSelf: 183 | # The first parameter to a method is a reference to an 184 | # instance, usually coded as "self", and is usually passed 185 | # automatically by Python; therefore we want to drop it. 186 | temp = argspec.split(',') 187 | if len(temp) == 1: # No other arguments. 188 | argspec = '()' 189 | elif temp[0][:2] == '(*': # first param is like *args, not self 190 | pass 191 | else: # Drop the first argument. 192 | argspec = '(' + ','.join(temp[1:]).lstrip() 193 | tip1 = name + argspec 194 | doc = '' 195 | if callable(obj): 196 | try: 197 | doc = inspect.getdoc(obj) 198 | except: 199 | pass 200 | if doc: 201 | # tip2 is the first separated line of the docstring, like: 202 | # "Return call tip text for a command." 203 | # tip3 is the rest of the docstring, like: 204 | # "The call tip information will be based on ... 205 | firstline = doc.split('\n')[0].lstrip() 206 | if tip1 == firstline or firstline[:len(name)+1] == name+'(': 207 | tip1 = '' 208 | else: 209 | tip1 += '\n\n' 210 | docpieces = doc.split('\n\n') 211 | tip2 = docpieces[0] 212 | tip3 = '\n\n'.join(docpieces[1:]) 213 | tip = '%s%s\n\n%s' % (tip1, tip2, tip3) 214 | else: 215 | tip = tip1 216 | calltip = (name, argspec[1:-1], tip.strip()) 217 | return calltip 218 | 219 | def getRoot(command, terminator=None): 220 | """Return the rightmost root portion of an arbitrary Python command. 221 | 222 | Return only the root portion that can be eval()'d without side 223 | effects. The command would normally terminate with a '(' or 224 | '.'. The terminator and anything after the terminator will be 225 | dropped.""" 226 | command = command.split('\n')[-1] 227 | command = command.lstrip() 228 | command = rtrimTerminus(command, terminator) 229 | if terminator == '.': 230 | tokens = getTokens(command) 231 | if tokens and tokens[-1][0] is tokenize.ENDMARKER: 232 | # Remove the end marker. 233 | del tokens[-1] 234 | if tokens and tokens[-1][0] is tokenize.NEWLINE: 235 | # Remove newline. 236 | del tokens[-1] 237 | if not tokens: 238 | return '' 239 | if terminator == '.' and \ 240 | (tokens[-1][1] != '.' or tokens[-1][0] is not tokenize.OP): 241 | # Trap decimals in numbers, versus the dot operator. 242 | return '' 243 | 244 | # Strip off the terminator. 245 | if terminator and command.endswith(terminator): 246 | size = 0 - len(terminator) 247 | command = command[:size] 248 | 249 | command = command.rstrip() 250 | tokens = getTokens(command) 251 | tokens.reverse() 252 | line = '' 253 | start = None 254 | prefix = '' 255 | laststring = '.' 256 | lastline = '' 257 | emptyTypes = ('[]', '()', '{}') 258 | for token in tokens: 259 | tokentype = token[0] 260 | tokenstring = token[1] 261 | line = token[4] 262 | if tokentype in (tokenize.ENDMARKER, tokenize.NEWLINE): 263 | continue 264 | if tokentype is tokenize.ENCODING: 265 | line = lastline 266 | break 267 | if tokentype in (tokenize.NAME, tokenize.STRING, tokenize.NUMBER) \ 268 | and laststring != '.': 269 | # We've reached something that's not part of the root. 270 | if prefix and line[token[3][1]] != ' ': 271 | # If it doesn't have a space after it, remove the prefix. 272 | prefix = '' 273 | break 274 | if tokentype in (tokenize.NAME, tokenize.STRING, tokenize.NUMBER) \ 275 | or (tokentype is tokenize.OP and tokenstring == '.'): 276 | if prefix: 277 | # The prefix isn't valid because it comes after a dot. 278 | prefix = '' 279 | break 280 | else: 281 | # start represents the last known good point in the line. 282 | start = token[2][1] 283 | elif len(tokenstring) == 1 and tokenstring in ('[({])}'): 284 | # Remember, we're working backwords. 285 | # So prefix += tokenstring would be wrong. 286 | if prefix in emptyTypes and tokenstring in ('[({'): 287 | # We've already got an empty type identified so now we 288 | # are in a nested situation and we can break out with 289 | # what we've got. 290 | break 291 | else: 292 | prefix = tokenstring + prefix 293 | else: 294 | # We've reached something that's not part of the root. 295 | break 296 | laststring = tokenstring 297 | lastline = line 298 | if start is None: 299 | start = len(line) 300 | root = line[start:] 301 | if prefix in emptyTypes: 302 | # Empty types are safe to be eval()'d and introspected. 303 | root = prefix + root 304 | return root 305 | 306 | def getTokens(command): 307 | """Return list of token tuples for command.""" 308 | 309 | # In case the command is unicode try encoding it 310 | if isinstance(command, str): 311 | try: 312 | command = command.encode('utf-8') 313 | except UnicodeEncodeError: 314 | pass # otherwise leave it alone 315 | 316 | f = io.BytesIO(command) 317 | # tokens is a list of token tuples, each looking like: 318 | # (type, string, (srow, scol), (erow, ecol), line) 319 | tokens = [] 320 | # Can't use list comprehension: 321 | # tokens = [token for token in tokenize.generate_tokens(f.readline)] 322 | # because of need to append as much as possible before TokenError. 323 | try: 324 | for t in tokenize.tokenize(f.readline): 325 | tokens.append(t) 326 | except tokenize.TokenError: 327 | # This is due to a premature EOF, which we expect since we are 328 | # feeding in fragments of Python code. 329 | pass 330 | return tokens 331 | 332 | def rtrimTerminus(command, terminator=None): 333 | """Return command minus anything that follows the final terminator.""" 334 | if terminator: 335 | pieces = command.split(terminator) 336 | if len(pieces) > 1: 337 | command = terminator.join(pieces[:-1]) + terminator 338 | return command 339 | 340 | def getBaseObject(obj): 341 | """Return base object and dropSelf indicator for an object.""" 342 | if inspect.isbuiltin(obj): 343 | # Builtin functions don't have an argspec that we can get. 344 | dropSelf = 0 345 | elif inspect.ismethod(obj): 346 | # Get the function from the object otherwise 347 | # inspect.getargspec() complains that the object isn't a 348 | # Python function. 349 | try: 350 | if obj.__self__ is None: 351 | # This is an unbound method so we do not drop self 352 | # from the argspec, since an instance must be passed 353 | # as the first arg. 354 | dropSelf = 0 355 | else: 356 | dropSelf = 1 357 | obj = obj.__func__ 358 | except AttributeError: 359 | dropSelf = 0 360 | elif inspect.isclass(obj): 361 | # Get the __init__ method function for the class. 362 | constructor = getConstructor(obj) 363 | if constructor is not None: 364 | obj = constructor 365 | dropSelf = 1 366 | else: 367 | dropSelf = 0 368 | elif callable(obj): 369 | # Get the __call__ method instead. 370 | try: 371 | obj = obj.__call__.__func__ 372 | dropSelf = 1 373 | except AttributeError: 374 | dropSelf = 0 375 | else: 376 | dropSelf = 0 377 | return obj, dropSelf 378 | 379 | def getConstructor(obj): 380 | """Return constructor for class object, or None if there isn't one.""" 381 | try: 382 | return obj.__init__.__func__ 383 | except AttributeError: 384 | for base in obj.__bases__: 385 | constructor = getConstructor(base) 386 | if constructor is not None: 387 | return constructor 388 | return None 389 | -------------------------------------------------------------------------------- /pyPad/pyPadClient.py: -------------------------------------------------------------------------------- 1 | # 2 | # PyPadPlusPlus: Module running in Python subprocess 3 | # 4 | 5 | import sys, os 6 | import code, time 7 | from types import ModuleType 8 | from codeop import compile_command 9 | import traceback 10 | import textwrap 11 | import threading 12 | try: 13 | from . import introspect 14 | except: 15 | import introspect 16 | import queue 17 | 18 | stdout = sys.stdout 19 | 20 | def log(s): 21 | with open(r'C:\prog\Npp7.9_test\log.txt','a') as f: 22 | f.write(s) 23 | 24 | import sys, pickle, base64 25 | def receive(): return input() 26 | def send(obj): stdout.write(obj+'\n') 27 | def pack(obj): return base64.b64encode(pickle.dumps(obj)) 28 | def unpack(packetObj): return pickle.loads(base64.b64decode(packetObj)) 29 | def receiveObj(): return unpack(receive().encode('ascii')) 30 | def sendObj(obj): stdout.buffer.write(pack(obj)+b'\n') 31 | 32 | class bufferOut: 33 | def __init__(self): 34 | self.buffer = [] 35 | def clear(self): 36 | self.buffer = [] 37 | def write(self, text, isErr=False): 38 | self.buffer.append((isErr,text)) 39 | def read(self): 40 | buffer = self.buffer 41 | self.buffer = [] 42 | return buffer 43 | def flush(self): pass 44 | def empty(self): 45 | return len(self.buffer) == 0 46 | 47 | class PseudoFileOutBuffer: 48 | def __init__(self, buffer, isErr=False): 49 | self.buffer = buffer 50 | if isErr: 51 | self.write = self.writeStdErr 52 | else: 53 | self.write = self.writeStdOut 54 | 55 | def writeStdOut(self, s): 56 | self.buffer.write(s) 57 | 58 | def writeStdErr(self, s): 59 | self.buffer.write(s, True) 60 | 61 | def flush(self): pass 62 | 63 | pipedFunctions = {} 64 | def fromPipe(commandId): 65 | def decorator(func): 66 | global pipedFunctions 67 | pipedFunctions[commandId] = func 68 | return func 69 | return decorator 70 | 71 | class interpreter: 72 | def __init__(self): 73 | self.buffer = bufferOut() 74 | self.stdout = sys.stdout 75 | self.stderr = sys.stderr 76 | self.stdin = sys.stdin 77 | self.stdOutBuff = PseudoFileOutBuffer(self.buffer) 78 | self.stdErrBuff = PseudoFileOutBuffer(self.buffer, True) 79 | sys.stdout=self.stdOutBuff 80 | sys.stderr=self.stdErrBuff 81 | self.userLocals = {} 82 | self.interp = code.InteractiveInterpreter(self.userLocals) 83 | self.kernelBusy = threading.Event() 84 | os.chdir(os.path.expanduser("~")) 85 | 86 | def restartKernel(self): 87 | self.userLocals = {} 88 | self.interp = code.InteractiveInterpreter(self.userLocals) 89 | print("Kernel reset.") 90 | 91 | @fromPipe('A') 92 | def flush(self): 93 | err = False 94 | result = self.buffer.read() 95 | return err, result 96 | 97 | @fromPipe('B') 98 | def tryCode(self, iLineStart, filename, block): 99 | err = None 100 | code = None 101 | isValue = False 102 | requireMore = False 103 | try: 104 | block = block.encode('latin1').decode('utf8') 105 | except: 106 | pass 107 | try: 108 | code = compile_command('\n' * iLineStart + block, filename, 'eval') 109 | isValue = True 110 | except (OverflowError, SyntaxError, ValueError): 111 | try: 112 | code = compile_command('\n' * iLineStart + block + '\n', filename, 'exec') 113 | isValue = False 114 | except (OverflowError, SyntaxError, ValueError): 115 | self.interp.showsyntaxerror(filename) 116 | err = self.buffer.read() 117 | if not err: err = True 118 | requireMore = code is None and err is None 119 | if not requireMore: 120 | self.code = code 121 | 122 | return err, requireMore, isValue 123 | 124 | @fromPipe('C') 125 | def evaluate(self): 126 | try: 127 | object = eval(self.code, self.interp.locals) 128 | if object is not None: 129 | result = repr(object) 130 | if not self.buffer.empty(): 131 | result = ''.join([i for e,i in self.buffer.read() if not e]) + result 132 | else: 133 | result = None 134 | err = False 135 | except: 136 | err = True 137 | self.interp.showtraceback() 138 | result = self.buffer.read() 139 | return err, result 140 | 141 | @fromPipe('D') 142 | def execute(self, string=None, iLineStart=None, filename=None): 143 | try: 144 | if filename is not None: 145 | exec(compile('\n' * iLineStart + string + '\n',filename,'exec')) 146 | elif type(string) is str: 147 | # for non-user commands 148 | exec(string, globals()) 149 | else: 150 | # for user commands 151 | exec(self.code, self.interp.locals) 152 | err = False 153 | except: 154 | err = True 155 | self.interp.showtraceback() 156 | return err, self.buffer.read() 157 | 158 | @fromPipe('E') 159 | def maxCallTip(self, value): 160 | '''Truncates text to fit in a call tip window.''' 161 | nMax = 2000 # max length 162 | cMax = 112 # max colums 163 | lMax = 14 # max lines 164 | lines = [] 165 | for l in value[:nMax].split('\n'): 166 | lines += textwrap.wrap(l, cMax) 167 | value = '\n'.join(lines[:lMax]) + ('\n...' if len(lines) > lMax else '') 168 | return value 169 | 170 | @fromPipe('F') 171 | def getCallTip(self, line, var, truncate=True): 172 | if not line: 173 | element = var 174 | else: 175 | element = introspect.getRoot(line) 176 | if len(element) < len(var): return 177 | try: 178 | object = eval(element, self.interp.locals) 179 | except: 180 | return var, str(0), 'value error' 181 | if var in element: 182 | if line: 183 | try: 184 | funcName, funcParam, funcHelp = introspect.getCallTip(element, locals=self.interp.locals) 185 | except: 186 | funcHelp = '' 187 | else: 188 | funcHelp = '' 189 | typ = str(type(object)) 190 | if typ.startswith(""): 191 | typ = typ[7:-2] 192 | if funcHelp: 193 | textFull = funcHelp 194 | if truncate: funcHelp = self.maxCallTip(textFull) 195 | calltip = 'type: ', typ, '\ndoc: ', funcHelp 196 | else: 197 | textFull = str(object) 198 | if isinstance(object, ModuleType): 199 | try: 200 | textFull = textFull + '\nhelp:\n'+object.__doc__ 201 | except: pass 202 | value = textFull 203 | if truncate: value = self.maxCallTip(textFull) 204 | calltip = 'type: ', typ, '\nstr: ', ('\n' if '\n' in value else '') + value 205 | else: 206 | value = textFull 207 | if truncate: value = self.maxCallTip(textFull) 208 | try: 209 | l = len(object) 210 | if hasattr(object, 'shape') and type(object.shape) is tuple and len(object.shape) <= 4: 211 | calltip = 'type: ', typ + ', len: %i'%l, ', shape: %s'%str(tuple(int(i) for i in object.shape)), '\nstr: ', ('\n' if '\n' in value else '') + value 212 | else: 213 | calltip = 'type: ', typ + ', len: %i'%l, '\nstr: ', ('\n' if '\n' in value else '') + value 214 | except: 215 | calltip = 'type: ', typ, '\nstr: ', ('\n' if '\n' in value else '') + value 216 | self.fullCallTip = var, calltip[:-1] + (textFull,) 217 | nHighlight = 0 218 | for ct in calltip[:3]: 219 | nHighlight += len(ct) 220 | 221 | return element, str(nHighlight), calltip 222 | 223 | @fromPipe('G') 224 | def getFullCallTip(self): 225 | return self.fullCallTip 226 | 227 | @fromPipe('H') 228 | def autoCompleteObject(self, linePart): 229 | element = introspect.getRoot(linePart) 230 | try: 231 | autoCompleteList = dir(eval(element, self.interp.locals)) 232 | if len(autoCompleteList) > 0: 233 | #autoCompleteList = '\t'.join(sorted(autoCompleteList)) 234 | autoCompleteList = '\t'.join(sorted([i for i in autoCompleteList if not i.startswith('_')],\ 235 | key=lambda s: s.lower()) + sorted([i for i in autoCompleteList if i.startswith('_')])) 236 | except: 237 | autoCompleteList = None 238 | return autoCompleteList 239 | 240 | @fromPipe('I') 241 | def autoCompleteFunction(self, linePart): 242 | element = introspect.getRoot(linePart) 243 | funcName, funcParam, funcHelp = introspect.getCallTip(element, locals=self.interp.locals) 244 | self.fullCallTip = funcName, funcHelp 245 | callTip = self.maxCallTip(funcHelp) 246 | return len(funcName)-1, funcParam, callTip 247 | 248 | @fromPipe('J') 249 | def autoCompleteDict(self, linePart): 250 | element = introspect.getRoot(linePart) 251 | autoCompleteList = None 252 | try: 253 | object = eval(element, self.interp.locals) 254 | t = type(object) 255 | if t is dict or 'h5py.' in str(t): 256 | autoCompleteList = '\t'.join(sorted([repr(i) for i in object.keys()])) if len(object) < 1000 else None 257 | except: 258 | pass 259 | return autoCompleteList 260 | 261 | @fromPipe('K') 262 | def showtraceback(self): 263 | """Display the exception that just occurred.""" 264 | try: 265 | type, value, tb = sys.exc_info() 266 | sys.last_type = type 267 | sys.last_value = value 268 | sys.last_traceback = tb 269 | tblist = traceback.extract_tb(tb) 270 | #del tblist[:2] 271 | list = traceback.format_list(tblist) 272 | if list: 273 | list.insert(0, "Traceback (most recent call last):\n") 274 | list[len(list):] = traceback.format_exception_only(type, value) 275 | finally: 276 | tblist = tb = None 277 | map(sys.stderr, list) 278 | 279 | @fromPipe('L') 280 | def showtraceback(self): 281 | """Stops the kernel""" 282 | exit() 283 | 284 | def startLocalClient(): 285 | clientInterp = interpreter() 286 | dataQueueOut = queue.Queue() 287 | dataQueueIn = queue.Queue() 288 | 289 | def communicationLoop(): 290 | while True: 291 | # receive the id and input of the function 292 | try: 293 | commandId, dataIn = receiveObj() 294 | except: 295 | commandId, dataIn = 'Z', None 296 | # to queue for execution in main thread 297 | if commandId in 'CD': 298 | dataQueueIn.put((commandId, dataIn)) 299 | else: 300 | try: 301 | dataToPipe = pipedFunctions[commandId](clientInterp, *dataIn) 302 | except: 303 | dataToPipe = None 304 | dataQueueOut.put((commandId, dataToPipe)) 305 | 306 | # Send back answer from output queue 307 | answers = [] 308 | while not dataQueueOut.empty(): 309 | answers.append(dataQueueOut.get()) 310 | sendObj(answers) 311 | 312 | thread = threading.Thread(name='communicationLoop', target=communicationLoop, args=()) 313 | thread.start() 314 | 315 | def matplotlib_eventHandler(interval): 316 | backend = matplotlib.rcParams['backend'] 317 | if backend in _interactive_bk: 318 | figManager = _pylab_helpers.Gcf.get_active() 319 | if figManager: 320 | canvas = figManager.canvas 321 | if canvas.figure.stale: 322 | canvas.draw() 323 | canvas.start_event_loop(interval) 324 | time.sleep(interval) # In case no on-screen figure is active 325 | 326 | def wait(): 327 | if active_matplotlib_eventHandler: 328 | matplotlib_eventHandler(0.05) 329 | else: 330 | time.sleep(0.05) 331 | 332 | # endless loop in the client mode 333 | while thread.is_alive(): 334 | while dataQueueIn.empty(): 335 | wait() 336 | commandId, dataFromPipe = dataQueueIn.get() 337 | dataToPipe = pipedFunctions[commandId](clientInterp, *dataFromPipe) 338 | dataQueueOut.put((commandId, dataToPipe)) 339 | # 340 | # Main function for the pyPadClient to run inside the python subprocess. 341 | # 342 | if __name__ == '__main__': 343 | active_matplotlib_eventHandler = False 344 | startLocalClient() 345 | exit() 346 | -------------------------------------------------------------------------------- /pyPad/pyPadHost.py: -------------------------------------------------------------------------------- 1 | # 2 | # PyPadPlusPlus: pyPadHost, module to call Python in subprocess 3 | # 4 | import os, time 5 | import subprocess, threading, queue 6 | import multiprocessing.queues 7 | import pickle, base64 8 | 9 | queueOut = multiprocessing.Queue(maxsize=5) 10 | 11 | class quantizedChannel: 12 | def __init__(self, commandId, timeout=1): 13 | self.receiveQueue = multiprocessing.Queue(maxsize=1) 14 | self.timeout = timeout 15 | self.sendLock = threading.Lock() 16 | self.commandId = commandId 17 | 18 | def __call__(self, arg=None): 19 | if kernelAlive.isSet(): 20 | with self.sendLock: 21 | if self.receiveQueue.empty(): 22 | try: 23 | queueOut.put_nowait((self.commandId, arg)) 24 | except: 25 | print("Python kernel not responding.") 26 | kernelAlive.clear() 27 | return None 28 | try: 29 | ret = self.receiveQueue.get(block=True, timeout=self.timeout) 30 | except: 31 | return None 32 | return ret 33 | else: 34 | return None 35 | 36 | def clear(self): 37 | while not queueOut.empty(): 38 | queueOut.get_nowait() 39 | 40 | receiveChannels = {} 41 | receiveQueues = {} 42 | def toPipe(symbol, timeout=1): 43 | channel = quantizedChannel(symbol, timeout=timeout) 44 | receiveChannels[symbol] = channel 45 | receiveQueues[symbol] = channel.receiveQueue 46 | def decorator(func): 47 | def pipeWrapper(self, *param): 48 | return channel(param) 49 | return pipeWrapper 50 | return decorator 51 | 52 | class interpreter: 53 | def __init__(self, pythonPath='pythonw', outBuffer=None): 54 | global kernelAlive 55 | self.queueIn = queue.Queue() 56 | if not pythonPath.endswith('.exe'): 57 | if pythonPath.strip().endswith('pythonw'): 58 | pythonPath = pythonPath.strip() + '.exe' 59 | else: 60 | pythonPath = os.path.join(pythonPath.strip(),'pythonw.exe') 61 | assert os.path.exists(pythonPath), 'file pythonw.exe not found.' 62 | self.outBuffer = outBuffer 63 | clientPath = os.path.join(os.path.dirname(__file__), 'pyPadClient.py') 64 | self.StartCommand = pythonPath + ' -u ' + '"' + clientPath + '"' 65 | print("start kernel:", self.StartCommand) 66 | self.kernelActive = threading.Event() 67 | self.kernelAlive = kernelAlive = threading.Event() 68 | self.startNewKernel() 69 | self.thread = threading.Thread(name='communicationLoop', target=self.communicationLoop, args=()) 70 | self.thread.start() 71 | 72 | def active(self): 73 | return self.kernelActive.isSet() 74 | 75 | def startNewKernel(self): 76 | self.proc = subprocess.Popen(self.StartCommand, 77 | stdin=subprocess.PIPE, 78 | stdout=subprocess.PIPE, 79 | stderr=subprocess.STDOUT, 80 | universal_newlines=True) 81 | time.sleep(0.1) 82 | self.buffer = [] 83 | self.kernelAlive.set() 84 | 85 | def send(self, obj): print(obj, file=self.proc.stdin, flush=True) 86 | def receive(self): return self.proc.stdout.readline()[:-1] 87 | def pack(self, obj): return base64.b64encode(pickle.dumps(obj)) 88 | def unpack(self, packetObj): return pickle.loads(base64.b64decode(packetObj)) 89 | def sendObj(self, obj): self.send(self.pack(obj).decode('ascii')) 90 | def receiveObj(self): return self.unpack(self.proc.stdout.buffer.readline()) 91 | 92 | def restartKernel(self): 93 | self.kernelAlive.clear() 94 | self.kernelActive.set() 95 | #self.clearQueue() 96 | self.proc.terminate() 97 | time.sleep(0.1) 98 | self.startNewKernel() 99 | self.kernelActive.clear() 100 | print("Python kernel restarted.") 101 | 102 | def __del__(self): 103 | self.kernelAlive.clear() 104 | self.stopProcess() 105 | 106 | def pipeQueue(self, commandId, data=()): 107 | if self.kernelAlive.isSet(): 108 | queueOut.put((commandId, data)) 109 | return self.queueIn.get() 110 | else: 111 | return None 112 | 113 | def clearQueue(self): 114 | global queueOut 115 | queueOut.close() 116 | queueOut = multiprocessing.Queue(maxsize=5) 117 | self.queueIn.queue.clear() 118 | for k,i in receiveChannels.items(): 119 | i.clear() 120 | 121 | def communicationLoop(self): 122 | while True: 123 | self.kernelAlive.wait() 124 | 125 | # # only if the output queue is empty the flush thread should request data 126 | if queueOut.empty(): 127 | if self.kernelAlive.isSet(): 128 | self.kernelActive.clear() 129 | 130 | # from queue commandId and data of function 131 | commandId, dataToPipe = queueOut.get() 132 | 133 | if not self.kernelAlive.isSet(): continue 134 | 135 | # set communication loop to busy 136 | if commandId in "BCD": 137 | self.kernelActive.set() 138 | 139 | # write the commandId of the function 140 | try: 141 | # send data 142 | #self.proc.stdin.write(repr((commandId, dataToPipe))+'\n') 143 | self.sendObj((commandId, dataToPipe)) 144 | except: 145 | if self.kernelAlive: 146 | print("Python kernel not responding.") 147 | self.kernelAlive.clear() 148 | continue 149 | 150 | # flush channel for immidiate transfer 151 | #if self.kernelAlive.isSet(): 152 | # self.proc.stdin.flush() 153 | 154 | answers = self.receiveObj() 155 | 156 | #try: 157 | # answers = eval(unicode(self.proc.stdout.readline(),'latin1').encode('utf-8')) 158 | #except: 159 | # continue 160 | 161 | # answer to queue 162 | for commandId, dataFromPipe in answers: 163 | receiveQueues[commandId].put(dataFromPipe) 164 | if commandId in 'BCD': 165 | self.kernelActive.clear() 166 | 167 | @toPipe('A') 168 | def flush(self): pass 169 | 170 | @toPipe('B', timeout=None) 171 | def tryCode(self, iLineStart, filename, block): pass 172 | 173 | @toPipe('C', timeout=None) 174 | def evaluate(self): pass 175 | 176 | @toPipe('D', timeout=None) 177 | def execute(self, string=None, iLineStart=None, filename=None): pass 178 | 179 | @toPipe('E') 180 | def maxCallTip(self, value): pass 181 | 182 | @toPipe('F') 183 | def getCallTip(self, line, var, truncate=True): pass 184 | 185 | @toPipe('G') 186 | def getFullCallTip(self): pass 187 | 188 | @toPipe('H') 189 | def autoCompleteObject(self, linePart): pass 190 | 191 | @toPipe('I') 192 | def autoCompleteFunction(self, linePart): pass 193 | 194 | @toPipe('J') 195 | def autoCompleteDict(self, linePart): pass 196 | 197 | @toPipe('K') 198 | def showtraceback(self): pass 199 | 200 | @toPipe('L') 201 | def stopProcess(self): pass 202 | -------------------------------------------------------------------------------- /pyPadCalltip.py: -------------------------------------------------------------------------------- 1 | # 2 | # PyPadPlusPlus: Show calltip 3 | # 4 | # Shows the calltip of current variable below cursor. 5 | # Recommended is + + 6 | 7 | try: 8 | Npp.pypad.showCalltip() 9 | except: 10 | pass 11 | -------------------------------------------------------------------------------- /pyPadClear.py: -------------------------------------------------------------------------------- 1 | # 2 | # PyPadPlusPlus: Clear console 3 | # 4 | # Use this script for a shortcut to clear the console output 5 | # Recommended is + + 6 | 7 | try: Npp.pypad != None 8 | except: from pyPadStart import * 9 | 10 | Npp.console.show() 11 | Npp.editor.grabFocus() 12 | Npp.console.clear() 13 | Npp.console.editor.setReadOnly(0) -------------------------------------------------------------------------------- /pyPadExecute.py: -------------------------------------------------------------------------------- 1 | # 2 | # PyPadPlusPlus: Execute command 3 | # 4 | # Put a shortcut on this script to start the interactive programming. 5 | # Recommended is + 6 | 7 | try: Npp.pypad != None 8 | except: from pyPadStart import * 9 | 10 | Npp.pypad.runCodeAtCursor() 11 | -------------------------------------------------------------------------------- /pyPadExecuteFix.py: -------------------------------------------------------------------------------- 1 | # 2 | # PyPadPlusPlus: Execute command while cursor stays at position 3 | # 4 | # Put a shortcut on this script to start the interactive programming. 5 | # Recommended is + + 6 | 7 | try: Npp.pypad != None 8 | except: from pyPadStart import * 9 | 10 | Npp.pypad.runCodeAtCursor(moveCursor=False) 11 | -------------------------------------------------------------------------------- /pyPadRestart.py: -------------------------------------------------------------------------------- 1 | # 2 | # PyPadPlusPlus: Clear console 3 | # 4 | # Use this script for a shortcut to clear the console output 5 | # Recommended is - 6 | 7 | try: Npp.pypad.restartKernel() 8 | except: from pyPadStart import * 9 | -------------------------------------------------------------------------------- /pyPadStart.py: -------------------------------------------------------------------------------- 1 | # 2 | # PyPadPlusPlus: Startup script 3 | # 4 | 5 | # Set the path to the Python file or the folder that contains pythonw.exe, 6 | # e.g. "C:\\programs\\Anaconda3". If pythonPath is None, the internal Python 7 | # distribution of Notepad++ PythonScript is used. Kernel restart features is 8 | # only available for the external Python kernel. Python 2.x and 3.x 9 | # are supported. Make sure that the environment variables are set for the 10 | # loaded Python installation. 11 | # 12 | pythonPath = None 13 | 14 | # In case of problems with certain libraries (e.g. numpy, matplotlib, Qt) set 15 | # the required environment variables of your Python distribution manually by: 16 | # import os 17 | # os.environ['PATH'] = 18 | 19 | # To use multiple interactive matplotlib windows, pyPadPlusPlus 20 | # runs an internal matplotlib event handler during idle time. 21 | # If this cases any problems, set it to False. 22 | # The matplotlib event handler is activated when matplotlib 23 | # is imported. In case matplotlib is imported implicitly by 24 | # another module, you must add to a code line a comment that 25 | # contains the word "matplotlib". 26 | # 27 | matplotlib_eventHandler = True 28 | 29 | # Cell highlighter underlines comments starting with #%% to highlight 30 | # code cells. This can slowdown Notepad++ during heavy computational load. 31 | # 32 | cellHighlight = True 33 | 34 | # mouseDwellTime in milliseconds sets the time until a popup is shown 35 | # when mouse movement stops at a certain variable. 36 | # 37 | mouseDwellTime=200 38 | 39 | # When set to False popups appear only with mouse hover over selected variables. 40 | # 41 | popupForUnselectedVariable = False 42 | 43 | # Evaluates any selected expression with mouse hover. Be carefull with this 44 | # option set to true, since selected functions can be called unintentionally. 45 | # 46 | popupForSelectedExpression = False 47 | 48 | # The latter two options are recommended to be set to false to prevent unintentional 49 | # code execution. The two features are allways active for the defined keyboard shortcut 50 | # linked to script pyPadCalltip.py (e.g. + ). 51 | 52 | # Start pyPadPlusPlus 53 | import Npp, pyPad 54 | Npp.pypad = pyPad.pyPadPlusPlus( 55 | externalPython=pythonPath, 56 | matplotlib_eventHandler=matplotlib_eventHandler, 57 | cellHighlight=cellHighlight, 58 | popupForUnselectedVariable=popupForUnselectedVariable, 59 | popupForSelectedExpression=popupForSelectedExpression, 60 | mouseDwellTime=mouseDwellTime) 61 | --------------------------------------------------------------------------------