├── .gitignore ├── LICENSE ├── README.md ├── bin ├── pynt-embed └── pynt-serve ├── codebook ├── __init__.py ├── manager.py ├── node_transformers.py ├── syntax.py └── tests │ ├── __init__.py │ ├── pynt.json │ ├── test_node_transformers.py │ └── test_syntax.py ├── example ├── biz.py ├── foo.py ├── r.py └── rational.py ├── pynt.json ├── pynt └── pynt.el └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoint/ 2 | *.ipynb 3 | *.tar 4 | gts/ 5 | \#* 6 | archive-contents 7 | __pycache__/ 8 | 9 | -------------------------------------------------------------------------------- /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 | # PYNT (PYthon iNTeractive) 2 | 3 | Get your code into a jupyter notebook. Anytime. Anywhere. 4 | 5 | Check out my [SciPy 2018 talk](https://youtu.be/MfM_TijHNYE) for the motivation and a feature tour of pynt. 6 | 7 | [![MELPA](https://melpa.org/packages/pynt-badge.svg)](https://melpa.org/#/pynt) [![PyPI version](https://badge.fury.io/py/codebook.svg)](https://badge.fury.io/py/codebook) [![Built with Spacemacs](https://cdn.rawgit.com/syl20bnr/spacemacs/442d025779da2f62fc86c2082703697714db6514/assets/spacemacs-badge.svg)](http://spacemacs.org) 8 | 9 | ## Features 10 | 11 | ### Generate jupyter notebooks on the fly 12 | 13 | No more copy and pasting code into jupyter notebooks. Each line of code gets its own cell. 14 | 15 | ![Alt Text](https://github.com/ebanner/pynt-assets/blob/master/gif/generate-notebook.gif) 16 | 17 | ### Attach a jupyter notebook to a running process 18 | 19 | Run a command which hits the code in the notebook. Restart the notebook kernel to attach to that process. 20 | 21 | ![Alt Text](https://github.com/ebanner/pynt-assets/blob/master/gif/attach%20notebook.gif) 22 | 23 | ### Syntax transformations 24 | 25 | Unroll the first pass of loops for increased interactivity. 26 | 27 | ![Alt Text](https://github.com/ebanner/pynt-assets/blob/master/gif/loop%20unrolling.gif) 28 | 29 | ### Scroll the resulting jupyter notebook with the code buffer 30 | 31 | Never forget which cell a code line corresponds to. 32 | 33 | ![Alt Text](https://github.com/ebanner/pynt-assets/blob/master/gif/scroll-notebook.gif) 34 | 35 | ## Quick Start 36 | 37 | *Disclaimer: pynt is in beta. Make sure to back-up your code before using it!* 38 | 39 | Install the codebook module with [pip](https://pip.pypa.io/en/stable/). 40 | 41 | ``` 42 | $ pip install git+https://github.com/ebanner/pynt # latest version of codebook in github 43 | ``` 44 | 45 | Then install pynt in emacs through [MELPA](https://melpa.org/#/pynt). 46 | 47 | ``` 48 | M-x package-install RET pynt 49 | ``` 50 | 51 | The next time you visit a python file pynt mode will be active. 52 | 53 | ## What is pynt? 54 | 55 | pynt is an emacs minor mode for getting source code into jupyter notebooks so you can hack on it there. If you have access to source code and a command to call it with then you can get your code into a jupyter notebook. 56 | 57 | However, just pasting your code into one big jupyter notebook cell is not particularly useful. pynt also 58 | 59 | - splits up code into cells so it's easy to evaluate small bits 60 | - sets up the state required to run code (by allowing you to attach notebooks to external processes) 61 | - takes code previously buried in various namespaces (e.g. functions and loops) and exposes them to the global namespace so you can interact with them 62 | 63 | ## Using pynt 64 | 65 | It is highly recommended that you familiarize yourself with [Emacs IPython Notebook (EIN)](http://millejoh.github.io/emacs-ipython-notebook/) first as pynt, at its core, is a tool to make working with EIN easier. 66 | 67 | Once you have opened a python file and pynt mode is active, cursor over to the region of code you would like to dump into a notebook and hit `C-c C-s`. If you need to "re-dump" the code into the notebook then hit `C-c C-e`. 68 | 69 | If you want to attach a jupyter notebook to a running process, then run a command which hits the jupyter notebook code. Restart the jupyter notebook kernel with `C-c C-r` (`ein:notebook-restart-kernel-command`). When you see the message `ein: [info] Starting channels WS: ...` your notebook is attached! 70 | 71 | ## How pynt works 72 | 73 | pynt uses a [custom kernel manager](https://github.com/ebanner/extipy) for attaching to jupyter notebook kernels started via third-party processes. When pynt generates a jupyter notebook from a code region that code region is replaced with a IPython kernel breakpoint so that subsequent commands that hit it will start a jupyter kernel for the notebook to attach to. See [here](https://github.com/ebanner/pynt/wiki/Using-the-standalone-kernel-manager) for more information. 74 | 75 | pynt also makes heavy use of the [`ast`](https://docs.python.org/3/library/ast.html) module to parse your code into chunks which are then dumped into notebook cells. 76 | 77 | ## Related Projects 78 | 79 | pynt is a tool that truly [stands on the shoulders of giants](https://en.wikipedia.org/wiki/Standing_on_the_shoulders_of_giants). Here are some projects where if they had not existed, then pynt would not have been possible. 80 | 81 | - [Jupyter](http://jupyter.org/) 82 | - [Emacs IPython Notebook](http://millejoh.github.io/emacs-ipython-notebook/) 83 | - [Emacs](https://www.gnu.org/software/emacs/) 84 | - [Spacemacs](http://spacemacs.org/) 85 | - [Python](https://www.python.org/) 86 | - [SLIME](https://common-lisp.net/project/slime/) 87 | - [vim-slime](https://github.com/jpalardy/vim-slime) 88 | 89 | -------------------------------------------------------------------------------- /bin/pynt-embed: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """Embed a IPython kernel into a function 4 | 5 | Script for embedding a IPython kernel into a function so we can open a jupyter 6 | notebook and talk to it. 7 | 8 | """ 9 | 10 | import ast 11 | import logging 12 | import os 13 | import shutil 14 | import subprocess 15 | import tempfile 16 | 17 | import astor 18 | import jupyter_core 19 | import plac 20 | 21 | from codebook.node_transformers import IPythonEmbedder 22 | 23 | FORMAT = '\n============ %(message)s ============\n' 24 | logging.basicConfig(level=logging.INFO, format=FORMAT) 25 | 26 | 27 | @plac.annotations( 28 | namespace=('function to embed a kernel in', 'option', None, str), 29 | ) 30 | def main(namespace): 31 | """Embed a kernel in `fname` in `namespace` 32 | 33 | Args: 34 | namespace (str): function to embed a kernel in 35 | 36 | Returns: 37 | None 38 | 39 | `namespace` is of the form module.(class.)?[method|func] 40 | 41 | Examples: 42 | - my_module 43 | - my_module.my_func 44 | - my_module.MyClass.my_func 45 | 46 | >>> namespace = 'biz.bar' 47 | 48 | """ 49 | # Compute path to file 50 | dirname, ns = os.path.dirname(namespace), os.path.basename(namespace) 51 | module = '.'.join([ns.split('.')[0], 'py']) 52 | path = '/'.join([dirname, module]) if dirname else module 53 | 54 | # Read in Input File 55 | with open(path) as f: 56 | lines = f.readlines() 57 | code = ''.join(lines) 58 | 59 | # Embed an IPython Kernel into the Function 60 | tree = ast.parse(code) 61 | t = IPythonEmbedder(ns).visit(tree) 62 | code_ = astor.to_source(t) 63 | 64 | # Copy the Old File to a Temporary File 65 | t = tempfile.NamedTemporaryFile(delete=False) 66 | shutil.copyfile(path, t.name) 67 | 68 | # Dump New Code to `path` 69 | with open(path, 'w') as f: 70 | f.write(code_) 71 | 72 | # Write .pynt to runtime dir so a kernel (re)start will attach to this 73 | # kernel 74 | # runtime_dir = jupyter_core.paths.jupyter_runtime_dir() 75 | # open(f'{runtime_dir}/.pynt', 'a').close() 76 | 77 | 78 | if __name__ == '__main__': 79 | plac.call(main) 80 | -------------------------------------------------------------------------------- /bin/pynt-serve: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import epc.server 4 | 5 | import codebook.syntax 6 | 7 | """List of functions to expose to EPC client""" 8 | funcs = [ 9 | codebook.syntax.annotate, 10 | codebook.syntax.parse_namespaces, 11 | codebook.syntax.embed, 12 | codebook.syntax.annotate_toplevel, 13 | codebook.syntax.unpack, 14 | ] 15 | 16 | if __name__ == '__main__': 17 | # create server 18 | server = epc.server.EPCServer(('localhost', 0)) 19 | for func in funcs: 20 | server.register_function(func) 21 | 22 | # serve 23 | server.print_port() 24 | server.serve_forever() 25 | -------------------------------------------------------------------------------- /codebook/__init__.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import logging 3 | import traceback 4 | 5 | from IPython.core.ultratb import AutoFormattedTB 6 | 7 | from .manager import ExternalIPythonKernelManager 8 | 9 | 10 | def handle_exception(type, value, tb): 11 | # Print stack trace. 12 | info = traceback.format_exception(type, value, tb) 13 | logging.error(''.join(info)) 14 | 15 | # Get local variables. 16 | while True: 17 | if not tb.tb_next: 18 | break 19 | next_frame = traceback.extract_tb(tb)[1] 20 | if next_frame.filename.startswith('/'): # not our code 21 | break 22 | tb = tb.tb_next 23 | local_vars = tb.tb_frame.f_locals 24 | 25 | # Start kernel. 26 | import os 27 | pid = os.fork() 28 | if pid == 0: 29 | open(f"{os.environ['HOME']}/.pynt", 'a').close() 30 | import IPython 31 | IPython.start_kernel(user_ns=local_vars) 32 | os.waitpid(pid, 0) 33 | 34 | def register(): 35 | import sys 36 | sys.excepthook = handle_exception 37 | -------------------------------------------------------------------------------- /codebook/manager.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Kernel manager for connecting to a IPython kernel started outside of Jupyter. 4 | 5 | Use this kernel manager if you want to connect a Jupyter notebook to a IPython 6 | kernel started outside of Jupyter. 7 | 8 | """ 9 | 10 | import glob 11 | import os 12 | import os.path 13 | import re 14 | 15 | from notebook.services.kernels.kernelmanager import MappingKernelManager 16 | from tornado import gen 17 | from tornado.concurrent import Future 18 | from tornado.ioloop import IOLoop 19 | 20 | 21 | class ExternalIPythonKernelManager(MappingKernelManager): 22 | """A Kernel manager that connects to a IPython kernel started outside of Jupyter""" 23 | 24 | def _get_latest_kernel_id(self): 25 | """Return the ID of the most recent kernel that was launched 26 | 27 | This ID is assumed to be the ID of the kernel which was launched via an 28 | external IPython process. 29 | 30 | Args: 31 | runtime_dir (str): the directory where kernel files are stored 32 | 33 | Returns: 34 | kid (int): the ID of the kernel file which was modified most recently 35 | 36 | >>> self = ExternalIPythonKernelManager() 37 | 38 | """ 39 | conn_fnames = glob.glob(f'{self.connection_dir}/kernel-*.json') 40 | p = '.*kernel-(?P\d+).json' 41 | conn_fnames = [conn_fname for conn_fname in conn_fnames for m in [re.match(p, conn_fname)] if m] 42 | latest_conn_fname = max(conn_fnames, key=os.path.getctime) 43 | kid = re.match(p, latest_conn_fname).group('kid') 44 | return kid 45 | 46 | def _attach_to_latest_kernel(self, kernel_id): 47 | """Attch to the latest externally started IPython kernel 48 | 49 | Args: 50 | kernel_id (str): ID for this kernel_id 51 | 52 | >>> self = ExternalIPythonKernelManager() 53 | >>> self.connection_dir = '/Users/ebanner/Library/Jupyter/runtime' 54 | >>> self.start_kernel() 55 | >>> open(f'{self.connection_dir}/.pynt', 'a').close() 56 | >>> kernel_id, loop = next(iter(self._kernels.items())) 57 | 58 | """ 59 | self.log.info(f'Attaching {kernel_id} to an existing kernel...') 60 | kernel = self._kernels[kernel_id] 61 | port_names = ['shell_port', 'stdin_port', 'iopub_port', 'hb_port', 'control_port'] 62 | port_names = kernel._random_port_names if hasattr(kernel, '_random_port_names') else port_names 63 | for port_name in port_names: 64 | setattr(kernel, port_name, 0) 65 | 66 | # "Connect" to latest kernel started by an external python process 67 | kid = self._get_latest_kernel_id() 68 | connection_fname = f'{self.connection_dir}/kernel-{kid}.json' 69 | self.log.info(f'Latest kernel = {connection_fname} from dir = {self.connection_dir}') 70 | kernel.load_connection_file(connection_fname) 71 | os.remove(f'{os.environ["HOME"]}/.pynt') 72 | 73 | def _should_use_existing(self): 74 | return os.path.isfile(f'{os.environ["HOME"]}/.pynt') 75 | 76 | @gen.coroutine 77 | def start_kernel(self, **kwargs): 78 | """Maybe switch to the most recently started kernel 79 | 80 | Start a new kernel like normal. If `self.runtime_dir/.pynt` exists then 81 | attach to the most recently started kernel. 82 | 83 | Args: 84 | Arguments to pass to `MappingKernelManager.start_kernel()` 85 | 86 | >>> self = ExternalIPythonKernelManager() 87 | >>> self.connection_dir = '/Users/ebanner/Library/Jupyter/runtime' 88 | >>> __class__ = ExternalIPythonKernelManager 89 | >>> kwargs = {} 90 | 91 | """ 92 | kernel_id = super(ExternalIPythonKernelManager, self).start_kernel(**kwargs).result() 93 | if self._should_use_existing(): 94 | self._attach_to_latest_kernel(kernel_id) 95 | raise gen.Return(kernel_id) 96 | 97 | def restart_kernel(self, kernel_id): 98 | """Maybe switch to the most recently started kernel 99 | 100 | Restart the kernel like normal. If `self.runtime_dir/.pynt` exists then 101 | attach to the most recently started kernel. 102 | 103 | TODO Most of this code is copied straight from 104 | `MappingKernelManager.restart_kernel()`. Figure out what subset of it 105 | is needed for this to work. 106 | 107 | """ 108 | self._check_kernel_id(kernel_id) 109 | super(MappingKernelManager, self).restart_kernel(kernel_id) 110 | kernel = self.get_kernel(kernel_id) 111 | # return a Future that will resolve when the kernel has successfully restarted 112 | channel = kernel.connect_shell() 113 | future = Future() 114 | 115 | def finish(): 116 | """Common cleanup when restart finishes/fails for any reason.""" 117 | if not channel.closed(): 118 | channel.close() 119 | loop.remove_timeout(timeout) 120 | kernel.remove_restart_callback(on_restart_failed, 'dead') 121 | if self._should_use_existing(): 122 | self._attach_to_latest_kernel(kernel_id) 123 | 124 | def on_reply(msg): 125 | self.log.debug("Kernel info reply received: %s", kernel_id) 126 | finish() 127 | if not future.done(): 128 | future.set_result(msg) 129 | 130 | def on_timeout(): 131 | self.log.warning("Timeout waiting for kernel_info_reply: %s", kernel_id) 132 | finish() 133 | if not future.done(): 134 | future.set_exception(gen.TimeoutError("Timeout waiting for restart")) 135 | 136 | def on_restart_failed(): 137 | self.log.warning("Restarting kernel failed: %s", kernel_id) 138 | finish() 139 | if not future.done(): 140 | future.set_exception(RuntimeError("Restart failed")) 141 | 142 | kernel.add_restart_callback(on_restart_failed, 'dead') 143 | kernel.session.send(channel, "kernel_info_request") 144 | channel.on_recv(on_reply) 145 | loop = IOLoop.current() 146 | timeout = loop.add_timeout(loop.time() + 30, on_timeout) 147 | return future 148 | -------------------------------------------------------------------------------- /codebook/node_transformers.py: -------------------------------------------------------------------------------- 1 | """Node transformers for manipulating the abstract syntax tree 2 | 3 | Transformers for exploding functions, rewriting syntax, and adding annotations 4 | exist currently. 5 | 6 | """ 7 | 8 | import ast 9 | import copy 10 | import doctest 11 | import random 12 | import string 13 | 14 | import astor 15 | 16 | N = [] 17 | def __random_string__(): 18 | """Compute a random string 19 | 20 | Also cache them in the global stack `N` so we can get them out later. 21 | 22 | """ 23 | n = ''.join(random.choice(string.ascii_lowercase) for _ in range(10)) 24 | global N 25 | N.append(n) 26 | return n 27 | 28 | def upcase(s): 29 | """ 30 | 31 | >>> s = 'foo' 32 | 33 | """ 34 | u = f'{s[0].upper()}{s[1:]}' 35 | return u 36 | 37 | def make_annotation(node=None, buffer='outside', content=None, cell_type='code', lineno=None): 38 | """Return a ast.Expr that looks like 39 | 40 | ``` 41 | __cell__('make-cell', [content, buffer, cell_type]) 42 | ``` 43 | 44 | """ 45 | content = astor.to_source(node).strip() if node else content 46 | lineno = str(node.lineno) if hasattr(node, 'lineno') else str(-1) if not lineno else str(lineno) 47 | call = ast.Call( 48 | func=ast.Name(id='__cell__', ctx=ast.Load()), 49 | args=[ 50 | ast.Str(s=content), 51 | ast.Str(s=f'{buffer}'), 52 | ast.Str(s=cell_type), 53 | ast.Str(s=lineno), 54 | ], 55 | keywords=[] 56 | ) 57 | return ast.Expr(call) 58 | 59 | class ExpressionFinder(ast.NodeTransformer): 60 | """Find the expression which contains the line number""" 61 | 62 | def __init__(self, lineno): 63 | super(__class__, self).__init__() 64 | self.lineno = lineno 65 | self.target_node = None # found expr 66 | 67 | def generic_visit(self, node): 68 | """Catch-all for nodes that slip through 69 | 70 | Basically everything I haven't gotten around to writing a custom 71 | annotator for gets caught here and wrapped in an annotation. Currently 72 | the one that jumps to mind are context managers. 73 | 74 | This is necessary because some nodes we recursively call `self.visit()` 75 | on and we may run into expressions that we have not written a node 76 | tranformer for. 77 | 78 | """ 79 | # try: 80 | # c = astor.to_source(node) 81 | # print(c.strip()) 82 | # print(getattr(node, 'lineno', -1)) 83 | # print() 84 | # except: 85 | # pass 86 | # return super().generic_visit(node) 87 | if not self.target_node and (getattr(node, 'lineno', -1) == self.lineno): 88 | self.target_node = node 89 | return super().generic_visit(node) 90 | 91 | def visit_Module(self, module): 92 | """Search the module's top-level expressions 93 | 94 | >>> self = ExpressionFinder(lineno=4) 95 | >>> code = ''' 96 | ... 97 | ... foo() 98 | ... if 1: 99 | ... if 2: 100 | ... print(12) 101 | ... 102 | ... ''' 103 | >>> 104 | >>> module = ast.parse(code) 105 | 106 | """ 107 | self.generic_visit(module) 108 | module.body = [self.target_node] 109 | return module 110 | # for i, expr in enumerate(module.body): 111 | # if getattr(expr, 'lineno', -float('inf')) < self.lineno: 112 | # continue 113 | # elif expr.lineno == self.lineno: 114 | # module.body = [expr] 115 | # else: 116 | # assert expr.lineno > self.lineno 117 | # module.body = module.body[i-1:i] 118 | # break 119 | # else: 120 | # module.body = module.body[-1:] 121 | # return module 122 | 123 | class DefunFinder(ast.NodeTransformer): 124 | """Find the function or method which is defined at a particular line number""" 125 | 126 | def __init__(self, func_name, lineno): 127 | """ 128 | 129 | >>> self = DefunFinder.__new__(DefunFinder) 130 | >>> __class__ = DefunFinder 131 | >>> func_name = 'bar' 132 | >>> lineno = 5 133 | 134 | """ 135 | super(__class__, self).__init__() 136 | self.func_name = func_name 137 | self.lineno = lineno 138 | 139 | def visit_ClassDef(self, classdef): 140 | """Check the line number of each of the methods 141 | 142 | >>> self = DefunFinder(func_name='bar', lineno=4) 143 | >>> code = ''' 144 | ... 145 | ... class Foo: 146 | ... def bar(): 147 | ... \"\"\"function\"\"\" 148 | ... pass 149 | ... def biz(): 150 | ... \"\"\"function\"\"\" 151 | ... pass 152 | ... 153 | ... ''' 154 | >>> 155 | >>> tree = ast.parse(code) 156 | >>> classdef = tree.body[0] 157 | 158 | """ 159 | methods = [stmt for stmt in classdef.body if isinstance(stmt, ast.FunctionDef)] 160 | for method in methods: 161 | if method.name == self.func_name and method.lineno == self.lineno: 162 | raise Exception(f'{classdef.name}.{method.name}') 163 | return classdef 164 | 165 | def visit_FunctionDef(self, func): 166 | """Embed a `IPython.embed_kernel()` call into the function 167 | 168 | >>> self = DefunFinder(func_name='bar', lineno=4) 169 | >>> code = ''' 170 | ... 171 | ... class Foo: 172 | ... def bar(): 173 | ... \"\"\"function\"\"\" 174 | ... pass 175 | ... def biz(): 176 | ... \"\"\"function\"\"\" 177 | ... pass 178 | ... 179 | ... ''' 180 | >>> 181 | >>> tree = ast.parse(code) 182 | >>> classdef = tree.body[0] 183 | 184 | """ 185 | if func.name == self.func_name and func.lineno == self.lineno: 186 | raise Exception(func.name) 187 | return func 188 | 189 | class IPythonEmbedder(ast.NodeTransformer): 190 | """Replaces the body of a function with `IPython.embed_kernel()`. 191 | 192 | Specifically swap out the body of a function with a call to fork off the 193 | `IPython.embed_kernel()` call. 194 | 195 | """ 196 | def __init__(self, namespace): 197 | """ 198 | 199 | >>> self = IPythonEmbedder.__new__(IPythonEmbedder) 200 | >>> namespace = 'foo.bar' 201 | >>> __class__ = IPythonEmbedder 202 | 203 | """ 204 | super(__class__, self).__init__() 205 | self.namespace = namespace 206 | tokens = namespace.split('.') 207 | if len(tokens) == 1: 208 | self.module, = tokens 209 | self.func_type = 'module' 210 | elif len(tokens) == 2: 211 | self.module, self.func_name = tokens 212 | self.func_type = 'function' 213 | else: 214 | assert len(tokens) == 3 215 | self.module, self.class_name, self.func_name = tokens 216 | self.func_type = 'method' 217 | 218 | @staticmethod 219 | def get_kernel_embed(): 220 | """A list of kernel embed nodes 221 | 222 | Returns: 223 | nodes (list): AST nodes which form the following code. 224 | 225 | ``` 226 | import os 227 | pid = os.fork() 228 | if os.fork() == 0: 229 | open(f'{os.environ["HOME"]}/.pynt', 'a').close() 230 | import IPython 231 | IPython.start_kernel(user_ns={**locals(), **globals(), **vars()}) 232 | os.waitpid(pid, 0) 233 | ``` 234 | 235 | This is a purely functional method which always return the same thing. 236 | 237 | """ 238 | return [ 239 | ast.Import(names=[ast.alias(name='os', asname=None),]), 240 | ast.Assign(targets=[ast.Name(id='pid', ctx=ast.Store()),], value=ast.Call(func=ast.Attribute(value=ast.Name(id='os', ctx=ast.Load()), attr='fork', ctx=ast.Load()), args=[], keywords=[])), 241 | ast.If( 242 | test=ast.Compare(left=ast.Name(id='pid', ctx=ast.Load()), ops=[ast.Eq(),], comparators=[ast.Num(n=0),]), 243 | body=[ 244 | ast.Expr(value=ast.Call(func=ast.Attribute(value=ast.Call(func=ast.Name(id='open', ctx=ast.Load()), args=[ 245 | ast.JoinedStr(values=[ 246 | ast.FormattedValue(value=ast.Subscript(value=ast.Attribute(value=ast.Name(id='os', ctx=ast.Load()), attr='environ', ctx=ast.Load()), slice=ast.Index(value=ast.Str(s='HOME')), ctx=ast.Load()), conversion=-1, format_spec=None), 247 | ast.Str(s='/.pynt'), 248 | ]), 249 | ast.Str(s='a'), 250 | ], keywords=[]), attr='close', ctx=ast.Load()), args=[], keywords=[])), 251 | ast.Import(names=[ 252 | ast.alias(name='IPython', asname=None), 253 | ]), 254 | ast.Expr(value=ast.Call(func=ast.Attribute(value=ast.Name(id='IPython', ctx=ast.Load()), attr='start_kernel', ctx=ast.Load()), args=[], keywords=[ 255 | ast.keyword(arg='user_ns', value=ast.Dict(keys=[ 256 | None, 257 | None, 258 | None, 259 | ], values=[ 260 | ast.Call(func=ast.Name(id='locals', ctx=ast.Load()), args=[], keywords=[]), 261 | ast.Call(func=ast.Name(id='globals', ctx=ast.Load()), args=[], keywords=[]), 262 | ast.Call(func=ast.Name(id='vars', ctx=ast.Load()), args=[], keywords=[]), 263 | ])), 264 | ])), 265 | ], orelse=[]), 266 | ast.Expr(value=ast.Call(func=ast.Attribute(value=ast.Name(id='os', ctx=ast.Load()), attr='waitpid', ctx=ast.Load()), args=[ 267 | ast.Name(id='pid', ctx=ast.Load()), 268 | ast.Num(n=0), 269 | ], keywords=[])), 270 | ] 271 | 272 | def visit_Module(self, module): 273 | """Maybe replace the entire module with a kernel 274 | 275 | If namespace is targeting the top-level then we do it. 276 | 277 | >>> self = IPythonEmbedder(namespace='foo.foo') 278 | >>> code = ''' 279 | ... 280 | ... import random 281 | ... def foo(): 282 | ... pass 283 | ... 284 | ... ''' 285 | >>> module = ast.parse(code) 286 | 287 | """ 288 | if self.func_type == 'module': 289 | module.body = self.get_kernel_embed() 290 | else: 291 | module = self.generic_visit(module) 292 | return module 293 | 294 | def visit_ClassDef(self, classdef): 295 | """Embed a kernel into classdef.target` 296 | 297 | If either `self.func_type` is a function or `self.class_name` does not 298 | match this class then that means this is not the classdef you are 299 | looking for. 300 | 301 | >>> self = IPythonEmbedder(namespace='ast_server.Foo.biz') 302 | >>> code = ''' 303 | ... 304 | ... class Foo: 305 | ... def bar(): 306 | ... \"\"\"function\"\"\" 307 | ... pass 308 | ... def biz(): 309 | ... \"\"\"function\"\"\" 310 | ... pass 311 | ... 312 | ... ''' 313 | >>> 314 | >>> tree = ast.parse(code) 315 | >>> classdef = tree.body[0] 316 | 317 | """ 318 | if self.func_type == 'function': 319 | node = classdef 320 | elif not self.class_name == classdef.name: 321 | node = classdef 322 | else: 323 | assert classdef.name == self.class_name and self.func_type == 'method' 324 | methods = [stmt for stmt in classdef.body if isinstance(stmt, ast.FunctionDef)] 325 | [idx, method], = [(i, method) for i, method in enumerate(methods) if method.name == self.func_name] 326 | classdef.body[idx] = self.visit_FunctionDef(method) 327 | node = classdef 328 | return node 329 | 330 | def visit_FunctionDef(self, func): 331 | """Embed a `IPython.embed_kernel()` call into the function 332 | 333 | Recall the context this node visitor is running in is that we are 334 | embedding a function. Because of the existence of `visit_ClassDef()` 335 | the only time we will visit a method is when we are called directly on 336 | the method that needs to be embedded. Hence it is sufficient to just 337 | check that `func.name == self.func_name` with no risk that we will 338 | embed a method which has the same name as the target method but is in a 339 | different class. 340 | 341 | >>> self = IPythonEmbedder(namespace='ast_server.foo') 342 | >>> code = ''' 343 | ... 344 | ... x 345 | ... def foo(): 346 | ... x = 1 347 | ... y = 2 348 | ... z = x + y 349 | ... return z 350 | ... y 351 | ... 352 | ... ''' 353 | >>> tree = ast.parse(code) 354 | >>> func = tree.body[1] 355 | 356 | """ 357 | if not func.name == self.func_name: 358 | node = func 359 | else: 360 | func.body = self.get_kernel_embed() 361 | node = func 362 | return node 363 | 364 | class NamespacePromoter(ast.NodeTransformer): 365 | """Takes a body of a function and pushes it into the global namespace""" 366 | 367 | def __init__(self, buffer): 368 | super(__class__, self).__init__() 369 | self.buffer = buffer 370 | 371 | def visit_Return(self, return_): 372 | """Convert returns into assignment/exception pairs 373 | 374 | Since the body of this function will be in the global namespace we 375 | can't have any returns. An acceptable alternative is to set a variable 376 | called 'RETURN' and then immediately raise an exception. 377 | 378 | >>> self = NamespacePromoter(buffer='foo') 379 | >>> code = ''' 380 | ... 381 | ... return 5 382 | ... 383 | ... ''' 384 | >>> tree = ast.parse(code) 385 | >>> return_, = tree.body 386 | 387 | """ 388 | nodes = [ 389 | ast.Assign(targets=[ast.Name(id='RETURN', ctx=ast.Store())], value=return_.value, lineno=return_.lineno), 390 | ast.Raise(exc=ast.Call(func=ast.Name(id='Exception', ctx=ast.Load()), args=[ast.Str(s='return')], keywords=[]), cause=None), 391 | ] 392 | return nodes 393 | 394 | def visit_FunctionDef(self, func): 395 | """Roll out a function definition 396 | 397 | >>> self = NamespacePromoter(buffer='bar') 398 | >>> code = ''' 399 | ... 400 | ... x 401 | ... def foo(a=1, b=2): 402 | ... \"\"\"\Short description 403 | ... 404 | ... Longer description. 405 | ... 406 | ... >>> a = 1 407 | ... >>> b = 2 408 | ... 409 | ... "\"\" 410 | ... if True: 411 | ... return 1 412 | ... else: 413 | ... return 0 414 | ... y 415 | ... ''' 416 | >>> tree = ast.parse(code) 417 | >>> func = tree.body[1] 418 | 419 | """ 420 | # tranform returns 421 | func = self.generic_visit(func) 422 | 423 | # extract doctests 424 | docstring = ast.get_docstring(func, clean=True) 425 | if docstring: 426 | func.body = func.body[1:] 427 | parser = doctest.DocTestParser() 428 | results = parser.parse(docstring) 429 | docstring_prefix, docstring_examples = results[0].strip(), [result for result in results if isinstance(result, doctest.Example)] 430 | docstring_assigns = [example.source.strip() for example in docstring_examples] 431 | 432 | # insert function name and docstring san doctests 433 | exprs = [] 434 | exprs.append( 435 | make_annotation( 436 | buffer=self.buffer, 437 | content=f'`{func.name}`', 438 | cell_type='1', 439 | lineno=func.lineno 440 | ) 441 | ) 442 | if docstring: 443 | exprs.append(make_annotation(buffer=self.buffer, content=docstring_prefix, cell_type='markdown')) 444 | 445 | # keyword (default) values 446 | vars, values = reversed(func.args.args), reversed(func.args.defaults) 447 | for var, value in zip(vars, values): 448 | try_ = ast.Try( 449 | body=[ast.Expr(value=ast.Name(id=var.arg, ctx=ast.Load()))], 450 | handlers=[ 451 | ast.ExceptHandler( 452 | type=ast.Name(id='NameError', ctx=ast.Load()), 453 | name=None, 454 | body=[ast.Assign(targets=[ast.Name(id=var.arg, ctx=ast.Store())], value=value)]), 455 | ], 456 | orelse=[], 457 | finalbody=[] 458 | ) 459 | exprs.append(try_) 460 | 461 | # docstring values override keyword values 462 | if docstring: 463 | # exprs.append(make_annotation(buffer=self.buffer, content='Docstring Assignments', cell_type='1')) 464 | for assign_expr in docstring_assigns: 465 | tree = ast.parse(assign_expr) 466 | exprs.append(tree.body[0]) 467 | 468 | # final dump of all arguments 469 | exprs.append(make_annotation(buffer=self.buffer, content='Arguments', cell_type='1')) 470 | exprs.extend(ast.Expr(arg) for arg in func.args.args) 471 | 472 | exprs.append(make_annotation(buffer=self.buffer, content='Body', cell_type='1')) 473 | 474 | return exprs + func.body 475 | 476 | class UnpackTry(ast.NodeTransformer): 477 | def __init__(self, buffer, only_try): 478 | self.buffer = buffer 479 | self.only_try = only_try 480 | 481 | def visit_Try(self, tryexp): 482 | """Unpack a try/except line. 483 | 484 | >>> self = UnpackTry('foo', False) 485 | >>> code = ''' 486 | ... 487 | ... try: 488 | ... data = requests.get(url, stream=True).raw 489 | ... except: 490 | ... print('error') 491 | ... 492 | ... ''' 493 | >>> module = ast.parse(code) 494 | >>> tryexp, = module.body 495 | 496 | """ 497 | nodes = [] 498 | nodes.append(make_annotation(buffer=self.buffer, content='try', cell_type='2', lineno=tryexp.lineno)) 499 | nodes.extend(tryexp.body) 500 | if self.only_try: 501 | return nodes 502 | 503 | for handler in tryexp.handlers: 504 | handler_toks = ['except'] 505 | if handler.type: 506 | handler_type = astor.to_source(handler.type).strip() 507 | handler_toks.append(handler_type) 508 | if handler.name: 509 | handler_toks.extend(['as', handler.name]) 510 | handler_str = ' '.join(handler_toks) 511 | nodes.append(make_annotation(buffer=self.buffer, content=handler_str, cell_type='2', lineno=tryexp.lineno)) 512 | nodes.extend(handler.body) 513 | if tryexp.orelse: 514 | nodes.append(make_annotation(buffer=self.buffer, content='else', cell_type='2', lineno=tryexp.lineno)) 515 | nodes.extend(tryexp.orelse) 516 | if tryexp.finalbody: 517 | nodes.append(make_annotation(buffer=self.buffer, content='finally', cell_type='2', lineno=tryexp.lineno)) 518 | nodes.extend(tryexp.finalbody) 519 | return nodes 520 | 521 | class UnpackIf(ast.NodeTransformer): 522 | def __init__(self, buffer): 523 | self.buffer = buffer 524 | 525 | def visit_If(self, ifexp): 526 | """Pure syntax rewrite of a for loop 527 | 528 | Unroll only the first iteration through the loop. 529 | 530 | >>> self = FirstPassForSimple('foo') 531 | >>> code = ''' 532 | ... 533 | ... if 1: 534 | ... print(1) 535 | ... elif 2: 536 | ... print(2) 537 | ... elif 3: 538 | ... print(3) 539 | ... else: 540 | ... print(4) 541 | ... 542 | ... ''' 543 | >>> module = ast.parse(code) 544 | >>> ifexp, = module.body 545 | 546 | """ 547 | # ifexp = self.generic_visit(ifexp) 548 | nodes = [] 549 | content = f'if {astor.to_source(ifexp.test).strip()}' 550 | nodes.append(make_annotation(buffer=self.buffer, content=content, cell_type='2', lineno=ifexp.lineno)) 551 | nodes.extend([ifexp.test]) 552 | nodes.extend(ifexp.body) 553 | nodes.extend(ifexp.orelse) 554 | return nodes 555 | 556 | class FirstPassForSimple(ast.NodeTransformer): 557 | def __init__(self, buffer): 558 | self.buffer = buffer 559 | 560 | def visit_Continue(self, cont): 561 | """ 562 | 563 | >>> self = FirstPassForSimple('foo') 564 | >>> code = 'continue' 565 | >>> module = ast.parse(code) 566 | >>> cont, = module.body 567 | 568 | """ 569 | return ast.Pass() 570 | 571 | def visit_Break(self, broken): 572 | """ 573 | 574 | >>> self = FirstPassForSimple('foo') 575 | >>> code = 'break' 576 | >>> module = ast.parse(code) 577 | >>> broken, = module.body 578 | 579 | """ 580 | return ast.Pass() 581 | 582 | def visit_For(self, loop): 583 | """Pure syntax rewrite of a for loop 584 | 585 | Unroll only the first iteration through the loop. 586 | 587 | >>> self = FirstPassForSimple('foo') 588 | 589 | """ 590 | # loop = self.generic_visit(loop) 591 | 592 | # iter(loop.iter) 593 | iter_call = ast.Call( 594 | func=ast.Name(id='iter', ctx=ast.Load()), 595 | args=[ast.Name(id=loop.iter, ctx=ast.Load())], 596 | keywords=[] 597 | ) 598 | 599 | # i = next(iter(loop.iter)) 600 | get_first = ast.Assign( 601 | targets=[loop.target], 602 | value=ast.Call( 603 | func=ast.Name(id='next', ctx=ast.Load()), 604 | args=[iter_call], 605 | keywords=[] 606 | ) 607 | ) 608 | content = f'`for {astor.to_source(loop.target).strip()} in {astor.to_source(loop.iter).strip()} ...`' 609 | nodes = [] 610 | nodes.append(make_annotation(buffer=self.buffer, content=content, cell_type='2', lineno=loop.lineno)) 611 | nodes.append(ast.Expr(loop.iter)) 612 | nodes.append(get_first) 613 | nodes.extend(loop.body) 614 | return nodes 615 | 616 | class FirstPassFor(ast.NodeTransformer): 617 | """Performs pure syntax rewrites 618 | 619 | Currently the only syntax rewrite are for loops to while loops. Future 620 | rewrites include context managers and decorators. 621 | 622 | """ 623 | def __init__(self, buffer): 624 | self.buffer = buffer 625 | 626 | def visit_For(self, loop_): 627 | """ 628 | >>> self = FirstPassFor(buffer='foo') 629 | >>> code = ''' 630 | ... 631 | ... for i in range(5): 632 | ... for j in range(5): 633 | ... k = i + j 634 | ... print(k) 635 | ... 636 | ... ''' 637 | >>> tree = ast.parse(code) 638 | >>> loop_, = tree.body 639 | 640 | """ 641 | loop = self.generic_visit(loop_) 642 | var = ast.Name(id=__random_string__(), ctx=ast.Store()) 643 | assign = ast.Assign(targets=[var], value=ast.Call(func=ast.Name(id='iter', ctx=ast.Load()), args=[loop.iter], keywords=[])) 644 | first_pass = ast.Try( 645 | body=[ast.Assign(targets=[loop.target], value=ast.Call(func=ast.Name(id='next', ctx=ast.Load()), args=[ast.Name(id=var, ctx=ast.Load())], keywords=[]))], 646 | handlers=[ast.ExceptHandler(type=ast.Name(id='StopIteration', ctx=ast.Load()), name=None, body=[ast.Pass()])], 647 | orelse=loop.body, 648 | finalbody=[] 649 | ) 650 | content = f'`for {astor.to_source(loop.target).strip()} in {astor.to_source(loop.iter).strip()} ...`' 651 | return [ 652 | make_annotation(buffer=self.buffer, content=content, cell_type='2', lineno=loop.lineno), 653 | ast.Expr(loop.iter), 654 | assign, 655 | first_pass 656 | ] 657 | 658 | class RestIterableFor(ast.NodeTransformer): 659 | def __init__(self, buffer): 660 | self.buffer = buffer 661 | 662 | def visit_For(self, loop_): 663 | """ 664 | >>> self = RestIterableFor() 665 | >>> code = ''' 666 | ... 667 | ... for i in range(5): 668 | ... for j in range(5): 669 | ... k = i + j 670 | ... print(k) 671 | ... ''' 672 | >>> tree = ast.parse(code) 673 | >>> loop_, = tree.body 674 | >>> FirstPassFor().visit(copy.deepcopy(loop_)) 675 | 676 | """ 677 | loop = self.generic_visit(loop_) 678 | global N 679 | varname = N.pop(0) 680 | loop.iter = ast.Name(id=varname, ctx=ast.Store()) 681 | return loop 682 | 683 | class SyntaxRewriter(ast.NodeTransformer): 684 | """Performs pure syntax rewrites 685 | 686 | Currently the only syntax rewrite are for loops to while loops. Future 687 | rewrites include context managers and decorators. 688 | 689 | """ 690 | def __init__(self, buffer): 691 | super(__class__, self).__init__() 692 | self.buffer = buffer 693 | 694 | def visit_For(self, loop): 695 | """Rewrite for loops as while loops 696 | 697 | >>> self = SyntaxRewriter(buffer='foo') 698 | >>> code = ''' 699 | ... 700 | ... for i in range(5): 701 | ... for j in range(5): 702 | ... k = i + j 703 | ... print(k) 704 | ... 705 | ... ''' 706 | >>> tree = ast.parse(code) 707 | >>> loop, = tree.body 708 | 709 | """ 710 | first = FirstPassFor(self.buffer).visit(copy.deepcopy(loop)) 711 | rest = RestIterableFor(self.buffer).visit(copy.deepcopy(loop)) 712 | return first + [rest] 713 | 714 | class ShallowAnnotator(ast.NodeTransformer): 715 | """Does a shallow annotation on the code given to it 716 | 717 | Literally only do assignment rewrites. 718 | 719 | """ 720 | def __init__(self, buffer): 721 | super(__class__, self).__init__() 722 | self.buffer = buffer 723 | 724 | def visit_Assign(self, assign): 725 | """Append the targets to the assign code string""" 726 | assign_content, targets_content = astor.to_source(assign), astor.to_source(assign.targets[0]) 727 | content = assign_content + targets_content.strip() 728 | return make_annotation( 729 | buffer=self.buffer, 730 | content=content, 731 | lineno=assign.lineno if hasattr(assign, 'lineno') else None 732 | ) 733 | 734 | def visit_Expr(self, expr): 735 | """Don't double-annotate an annotation 736 | 737 | Even in `expr` is a `ast.Call` its `value` might be a `ast.Attribute` 738 | not a `ast.Name`. In this case we know it's not an annotation. Perhaps 739 | a more reliable way would be traversing the AST and looking for any 740 | node with a `id` of `__cell__` or perhaps tagging the node with a 741 | boolean flag called `is_annotation`. 742 | 743 | Annotations are only *maybe* here at this point because 744 | `NamespacePromoter` puts them in. 745 | 746 | """ 747 | if isinstance(getattr(expr, 'value', None), ast.Call) and getattr(expr.value.func, 'id', None) == '__cell__': 748 | return expr 749 | else: 750 | return make_annotation(expr, buffer=self.buffer) 751 | 752 | def generic_visit(self, node): 753 | if isinstance(node, ast.Module): 754 | return super().generic_visit(node) 755 | else: 756 | return make_annotation(node, buffer=self.buffer) 757 | 758 | 759 | class DeepAnnotator(ShallowAnnotator): 760 | """Annotates code with commands to create jupyter notebook cells""" 761 | 762 | def _annotate_nodes(self, nodes): 763 | """Make annotation on the nodes. 764 | 765 | If the node has a namespace then don't annotate it normally. 766 | Rather recursively call `visit()` on it. 767 | 768 | """ 769 | exprs = [] 770 | for node in nodes: 771 | new_nodes = self.visit(node) 772 | if isinstance(new_nodes, list): 773 | exprs.extend(new_nodes) 774 | else: 775 | exprs.append(new_nodes) 776 | return exprs 777 | 778 | def visit_If(self, iff): 779 | return [ 780 | make_annotation(buffer=self.buffer, content=f'`if {astor.to_source(iff.test).strip()} ...`', cell_type='2'), 781 | make_annotation(iff.test, buffer=self.buffer), 782 | ast.If( 783 | test=iff.test, 784 | body=self._annotate_nodes(iff.body), 785 | orelse=self._annotate_nodes(iff.orelse) 786 | ) 787 | ] 788 | 789 | def visit_Try(self, try_): 790 | handlers = [] 791 | for handler in try_.handlers: 792 | handlers.append( 793 | ast.ExceptHandler( 794 | type=handler.type, 795 | name=None, 796 | body=self._annotate_nodes(handler.body) 797 | ) 798 | ) 799 | return ast.Try( 800 | body=self._annotate_nodes(try_.body), 801 | handlers=handlers, 802 | orelse=self._annotate_nodes(try_.orelse), 803 | finalbody=self._annotate_nodes(try_.finalbody) 804 | ) 805 | 806 | 807 | def visit_Assign(self, assign): 808 | """Append the targets to the assign code string 809 | 810 | Do the same thing as `generic_visit()` otherwise. 811 | 812 | """ 813 | annotated_assign = super().visit_Assign(assign) 814 | return [assign, annotated_assign] 815 | 816 | def visit_Expr(self, expr): 817 | annotated_expr = super().visit_Expr(expr) 818 | if annotated_expr == expr: 819 | return expr 820 | else: 821 | return [annotated_expr, expr] 822 | 823 | def generic_visit(self, node): 824 | """Catch-all for nodes that slip through 825 | 826 | Basically everything I haven't gotten around to writing a custom 827 | annotator for gets caught here and wrapped in an annotation. Currently 828 | the one that jumps to mind are context managers. 829 | 830 | This is necessary because some nodes we recursively call `self.visit()` 831 | on and we may run into expressions that we have not written a node 832 | tranformer for. 833 | 834 | """ 835 | if isinstance(node, ast.Module): 836 | return super().generic_visit(node) 837 | else: 838 | return [make_annotation(node, buffer=self.buffer), node] 839 | -------------------------------------------------------------------------------- /codebook/syntax.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import ast 4 | 5 | import astor 6 | import codebook.node_transformers 7 | from codebook.node_transformers import (DeepAnnotator, DefunFinder, 8 | ExpressionFinder, FirstPassForSimple, 9 | IPythonEmbedder, NamespacePromoter, 10 | ShallowAnnotator, SyntaxRewriter, 11 | UnpackIf, UnpackTry) 12 | 13 | 14 | def find_func(module, namespace): 15 | """Filter away everything except the function 16 | 17 | Addionally rename the function for better readability. 18 | 19 | Args: 20 | module (ast.Module): the entire parsed code 21 | namespace (str): identifier for the function of interest 22 | 23 | `namspace` will be of the form . 24 | 25 | Returns: 26 | module (ast.Module): the original module but with everything filtered 27 | away except the function and the function with a more readable name 28 | 29 | """ 30 | module_name, func_name = namespace.split('.') 31 | funcs = [stmt for stmt in module.body if isinstance(stmt, ast.FunctionDef)] 32 | func, = [func for func in funcs if func.name == func_name] 33 | func.name = f'{module_name}.{func_name}' 34 | module.body = [func] 35 | return module 36 | 37 | def find_method(module, namespace): 38 | """Filter away everything except the method 39 | 40 | Promote the method up to the global namespace so that it is 41 | indistinguishable from a regular function. 42 | 43 | Arguments: 44 | module (ast.Module): the entire parsed source code 45 | namespace (str): identifier for the method of interest 46 | 47 | Returns: 48 | module (ast.Module): the original module but with everything filtered 49 | away except the method name but with the name `namespace` and promoted 50 | to the global (i.e. top) level 51 | 52 | """ 53 | module_name, class_name, method_name = namespace.split('.') 54 | classdefs = [stmt for stmt in module.body if isinstance(stmt, ast.ClassDef)] 55 | classdef, = [classdef for classdef in classdefs if classdef.name == class_name] 56 | methods = [stmt for stmt in classdef.body if isinstance(stmt, ast.FunctionDef)] 57 | for method in methods: 58 | if method.name == method_name: 59 | method.name = f'{module_name}.{class_name}.{method_name}' 60 | module.body = [method] 61 | return module 62 | 63 | def filter_away_except(tree, namespace): 64 | """Filter away everything except the namespace 65 | 66 | In the case that `namespace` is a method promote the method to the global 67 | (i.e. top) level. 68 | 69 | Arguments: 70 | tree (ast.Module): the entire parsed code from the code buffer 71 | namespace (str): the namespace (i.e. region of code) of interest 72 | 73 | Returns: 74 | small_tree (ast.Module): `tree` but everything filtered except the 75 | namespace region 76 | 77 | """ 78 | ns_tokens = namespace.split('.') 79 | if len(ns_tokens) == 1: # module-level 80 | tree.body = [stmt for stmt in tree.body if not isinstance(stmt, ast.FunctionDef) and not isinstance(stmt, ast.ClassDef)] 81 | e = codebook.node_transformers.make_annotation(buffer=namespace, content=f'`{namespace}`', cell_type='1') 82 | tree.body.insert(0, e) 83 | small_tree = tree 84 | elif len(ns_tokens) == 2: # function 85 | small_tree = find_func(tree, namespace) 86 | else: # method 87 | assert len(ns_tokens) == 3 88 | small_tree = find_method(tree, namespace) 89 | return small_tree 90 | 91 | def annotate(code, namespace, shallow=False): 92 | """Annotate region with code to make and eval cells 93 | 94 | Arguments: 95 | code (str): the code from the code buffer 96 | namespace (str): the namespace identifying the code region of interest 97 | 98 | `namespace` can take one of three forms depending on the type of code 99 | region of interest: 100 | 101 | - "" 102 | - "." 103 | - ".." 104 | 105 | """ 106 | tree = ast.parse(code) 107 | small_tree = filter_away_except(tree, namespace) 108 | shallow_tree = NamespacePromoter(buffer=namespace).visit(tree) 109 | 110 | if shallow: 111 | annotations = ShallowAnnotator(namespace).visit(shallow_tree) 112 | return unpack_annotations(annotations) 113 | else: 114 | annotations = DeepAnnotator(namespace).visit(shallow_tree) 115 | new_code = astor.to_source(annotations) 116 | return new_code 117 | 118 | def parse_namespaces(*region): 119 | """Parse namespaces out of the code 120 | 121 | Returns: 122 | namespaces (list): a list of 3-tuples = [ 123 | (namespace, start-line, end-line), 124 | (namespace, start-line, end-line), 125 | . 126 | . 127 | . 128 | (namespace, start-line, end-line), 129 | ] 130 | 131 | >>> s = ''' 132 | ... 133 | ... x 134 | ... class Foo: 135 | ... def bar(): 136 | ... \"\"\"function\"\"\" 137 | ... pass 138 | ... def biz(): 139 | ... \"\"\"function\"\"\" 140 | ... pass 141 | ... 142 | ... class Qux: 143 | ... def quux(): 144 | ... \"\"\"function\"\"\" 145 | ... pass 146 | ... def quuux(): 147 | ... \"\"\"function\"\"\" 148 | ... pass 149 | ... y 150 | ... 151 | ... ''' 152 | >>> region = [s, 'ast-server'] 153 | 154 | """ 155 | code, namespace = region 156 | tree = ast.parse(code) 157 | new_code = str() 158 | module_name = namespace 159 | funcs = [stmt for stmt in tree.body if isinstance(stmt, ast.FunctionDef)] 160 | methods = [] 161 | classdefs = [stmt for stmt in tree.body if isinstance(stmt, ast.ClassDef)] 162 | for classdef in classdefs: 163 | for expr in classdef.body: 164 | if not isinstance(expr, ast.FunctionDef): 165 | continue 166 | methods.append([classdef, expr]) 167 | namespaces = \ 168 | [(ns, ns, -1, -1) for ns in [f'{module_name}']] + \ 169 | [(ns, ns, func.lineno, func.body[-1].lineno) for func in funcs for ns in [f'{module_name}.{func.name}']] + \ 170 | [(ns, ns, method.lineno, method.body[-1].lineno) for classdef, method in methods for ns in [f'{module_name}.{classdef.name}.{method.name}']] 171 | return namespaces 172 | 173 | def embed(*region): 174 | """Replace the function or method with a call to `IPython.embed()` 175 | 176 | Args: 177 | s (str): the code 178 | ns (str): the namespace 179 | 180 | `ns` is of the form 181 | 182 | - . 183 | - .. 184 | 185 | region = [s, ns] 186 | 187 | >>> s = ''' 188 | ... 189 | ... x 190 | ... class Foo: 191 | ... def bar(): 192 | ... \"\"\"function\"\"\" 193 | ... pass 194 | ... def biz(): 195 | ... \"\"\"function\"\"\" 196 | ... pass 197 | ... 198 | ... class Qux: 199 | ... def quux(): 200 | ... \"\"\"function\"\"\" 201 | ... pass 202 | ... def quuux(): 203 | ... \"\"\"function\"\"\" 204 | ... pass 205 | ... y 206 | ... 207 | ... ''' 208 | >>> 209 | >>> namespace = 'ast_server.Qux.quux' 210 | >>> region = [s, namespace] 211 | 212 | """ 213 | code, namespace = region 214 | tree = ast.parse(code) 215 | embedded = IPythonEmbedder(namespace).visit(tree) 216 | c = astor.to_source(embedded) 217 | return c 218 | 219 | def find_namespace(code, func_name, lineno): 220 | """Compute the fully qualified namespace of `func_name` at `lineno` from `code` 221 | 222 | Args: 223 | code (str): the code 224 | func_name (str): the function name 225 | lineno (str): the line that `func_name` is defined at in `code` 226 | 227 | Returns: 228 | A namespace string 229 | 230 | - 231 | - . 232 | 233 | >>> code = ''' 234 | ... 235 | ... x 236 | ... class Foo: 237 | ... def bar(): 238 | ... \"\"\"function\"\"\" 239 | ... pass 240 | ... def biz(): 241 | ... \"\"\"function\"\"\" 242 | ... pass 243 | ... 244 | ... class Qux: 245 | ... def bar(): 246 | ... \"\"\"function\"\"\" 247 | ... pass 248 | ... def biz(): 249 | ... \"\"\"function\"\"\" 250 | ... pass 251 | ... y 252 | ... 253 | ... ''' 254 | >>> 255 | >>> func_name = 'bar' 256 | >>> lineno = 5 257 | 258 | """ 259 | namespace = None 260 | try: 261 | DefunFinder(func_name, lineno).visit(tree) 262 | except Exception as e: 263 | namespace, = e.args 264 | return namespace 265 | 266 | def promote_loop(*region): 267 | """ 268 | 269 | >>> code = ''' 270 | ... 271 | ... for i in range(5): 272 | ... for j in range(5): 273 | ... k = i = j 274 | ... print(k) 275 | ... 276 | ... ''' 277 | 278 | """ 279 | code, namespace = region 280 | tree = ast.parse(code) 281 | m = FirstPassForSimple(buffer=namespace).visit(tree) 282 | return astor.to_source(m) 283 | 284 | def annotate_toplevel(*region): 285 | """ 286 | 287 | >>> code = ''' 288 | ... 289 | ... for i in range(5): 290 | ... for j in range(5): 291 | ... k = i = j 292 | ... print(k) 293 | ... 294 | ... ''' 295 | >>> namespace = 'foo' 296 | >>> region = [code, namespace] 297 | 298 | """ 299 | code, namespace = region 300 | tree = ast.parse(code) 301 | annotated_tree = Annotator(buffer=namespace).visit(tree) 302 | return astor.to_source(annotated_tree) 303 | 304 | def unpack_annotations(annotations): 305 | """Extract the information out of a bunch of annotations 306 | 307 | >>> code = ''' 308 | ... 309 | ... __cell__('`foo.baz`', 'foo.baz', '1', '9') 310 | ... __cell__('Arguments', 'foo.baz', '1', '-1') 311 | ... __cell__('Body', 'foo.baz', '1', '-1') 312 | ... __cell__('pass', 'foo.baz', 'code', '10') 313 | ... 314 | ... ''' 315 | ... 316 | >>> annotations = ast.parse(code) 317 | 318 | """ 319 | info = [] 320 | m = astor.to_source(annotations) 321 | print(m) 322 | for annotation in annotations.body: 323 | content, namespace, cell_type, lineno = [arg.s for arg in annotation.value.args] 324 | info.append([content, namespace, cell_type, int(lineno)]) 325 | return info 326 | 327 | def unpack(code, namespace, lineno, only_first=True): 328 | """Extract the information out of a bunch of annotations 329 | 330 | Args: 331 | code (str) : the whole code buffer 332 | namespace (str) : identifier for the region of code 333 | lineno (int) : line number of the expression to unpack 334 | only_first (bool) : only consider the first branch 335 | 336 | >>> code = ''' 337 | ... 338 | ... if 1: 339 | ... if 2: 340 | ... print(12) 341 | ... 342 | ... ''' 343 | >>> 344 | >>> namespace = 'foo' 345 | >>> lineno = 3 346 | 347 | """ 348 | tree = ast.parse(code) 349 | small_tree = filter_away_except(tree, namespace) 350 | shallow_tree = NamespacePromoter(buffer=namespace).visit(small_tree) 351 | small_shallow_tree = ExpressionFinder(lineno).visit(shallow_tree) 352 | expr_type, = small_shallow_tree.body 353 | if isinstance(expr_type, ast.For): 354 | unpacked = FirstPassForSimple(namespace).visit(small_shallow_tree) 355 | elif isinstance(expr_type, ast.Try): 356 | unpacked = UnpackTry(namespace, only_first).visit(small_shallow_tree) 357 | else: 358 | assert isinstance(expr_type, ast.If) 359 | unpacked = UnpackIf(namespace).visit(small_shallow_tree) 360 | annotations = ShallowAnnotator(namespace).visit(unpacked) 361 | return unpack_annotations(annotations) 362 | -------------------------------------------------------------------------------- /codebook/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ebanner/pynt/86cf9ce78d34f92bfd0764c9cbb75427ebd429e6/codebook/tests/__init__.py -------------------------------------------------------------------------------- /codebook/tests/pynt.json: -------------------------------------------------------------------------------- 1 | { 2 | "test_node_transformers.TestSupport.test_upcase": [ 3 | "python -m unittest tests.test_node_transformers.TestSupport.test_upcase" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /codebook/tests/test_node_transformers.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from unittest import TestCase 3 | 4 | import astor 5 | 6 | import codebook.node_transformers 7 | 8 | 9 | class TestFirstPassForSimple(TestCase): 10 | def test_iter(self): 11 | code = """ 12 | 13 | for i in range(5): 14 | print(i) 15 | 16 | """ 17 | tree = ast.parse(code) 18 | m = codebook.node_transformers.FirstPassForSimple(buffer='foo').visit(tree) 19 | out = astor.to_source(m) 20 | self.assertIn('iter', out) 21 | 22 | def test_nested(self): 23 | code = """ 24 | 25 | for i in range(5): 26 | for j in range(5): 27 | k = i + j 28 | print(k) 29 | 30 | """ 31 | tree = ast.parse(code) 32 | m = codebook.node_transformers.FirstPassForSimple(buffer='foo').visit(tree) 33 | out = astor.to_source(m) 34 | self.assertIn('iter', out) 35 | 36 | def test_nobreak(self): 37 | code = """ 38 | 39 | for i in range(5): 40 | print(i) 41 | break 42 | 43 | """ 44 | tree = ast.parse(code) 45 | m = codebook.node_transformers.FirstPassForSimple(buffer='foo').visit(tree) 46 | out = astor.to_source(m) 47 | self.assertNotIn('break', out) 48 | self.assertIn('pass', out) 49 | 50 | class TestSupport(TestCase): 51 | def test_upcase(self): 52 | s = 'foo' 53 | output = codebook.node_transformers.upcase(s) 54 | expected = 'Foo' 55 | self.assertEqual(output, expected) 56 | 57 | class TestFilters(TestCase): 58 | def test_filter_class(self): 59 | code = """ 60 | 61 | class Foo: 62 | def bar(): 63 | pass 64 | 65 | class Bar: 66 | def biz(): 67 | pass 68 | 69 | """ 70 | tree = ast.parse(code) 71 | out = codebook.node_transformers.ClassFinder(class_name='Foo').visit(tree) 72 | c = astor.to_source(out) 73 | self.assertIn('Foo', c) 74 | self.assertNotIn('Bar', c) 75 | 76 | def test_filter_function(self): 77 | code = """ 78 | 79 | def foo(): 80 | pass 81 | 82 | def bar(): 83 | pass 84 | 85 | """ 86 | tree = ast.parse(code) 87 | out = codebook.node_transformers.FunctionFinder(func_name='foo').visit(tree) 88 | c = astor.to_source(out) 89 | self.assertIn('foo', c) 90 | self.assertNotIn('bar', c) 91 | 92 | class TestShallowAnnotator(TestCase): 93 | def test_simple(self): 94 | code = """ 95 | 96 | a = 3 97 | b = a + 2 98 | 99 | """ 100 | module = ast.parse(code) 101 | out = codebook.node_transformers.SimpleAnnotator(buffer='foo').visit(module) 102 | c = astor.to_source(out) 103 | self.assertIn('__cell__', c) 104 | 105 | class TestExpressionFinder(TestCase): 106 | def test_simple(self): 107 | code = """ 108 | 109 | a 110 | b 111 | c 112 | 113 | """ 114 | module = ast.parse(code) 115 | out = codebook.node_transformers.ExpressionFinder(lineno=4).visit(module) 116 | self.assertIsInstance(out, ast.Module) 117 | c = astor.to_source(out) 118 | self.assertIn('b', c) 119 | self.assertNotIn('a', c) 120 | self.assertNotIn('c', c) 121 | -------------------------------------------------------------------------------- /codebook/tests/test_syntax.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | import codebook.syntax 4 | 5 | 6 | class TestAnnotate(TestCase): 7 | def test_module(self): 8 | code = """ 9 | x 10 | def bar(): 11 | pass 12 | class Biz: 13 | def baz(self): 14 | pass 15 | def qux(): 16 | pass 17 | y""" 18 | namespace = 'foo' 19 | out = codebook.syntax.annotate(code, namespace) 20 | self.assertIn('x', out) 21 | self.assertIn('y', out) 22 | self.assertNotIn('bar', out) 23 | self.assertNotIn('Biz', out) 24 | self.assertNotIn('qux', out) 25 | 26 | def test_func(self): 27 | code = """ 28 | x 29 | def bar(): 30 | pass 31 | class Biz: 32 | def baz(self): 33 | pass 34 | def qux(): 35 | pass 36 | y""" 37 | namespace = 'foo.bar' 38 | out = codebook.syntax.annotate(code, namespace) 39 | self.assertIn('foo.bar', out) 40 | self.assertNotIn('Biz', out) 41 | self.assertNotIn('qux', out) 42 | self.assertNotIn('baz', out) 43 | -------------------------------------------------------------------------------- /example/biz.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | A small collection of functions. 4 | 5 | """ 6 | 7 | 8 | class Biz: 9 | def baz(f=5, g=6): 10 | h = f + g 11 | return h 12 | 13 | def foo(a=1, b=2): 14 | c = a + b 15 | return c 16 | 17 | def bar(d=3, e=4): 18 | print('Hello from biz.bar()!') 19 | return d 20 | 21 | if __name__ == '__main__': 22 | bar() 23 | -------------------------------------------------------------------------------- /example/foo.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import IPython 4 | 5 | EXISTING_KERNEL = True 6 | 7 | open(f'{os.environ["HOME"]}/.pynt', 'a').close() 8 | IPython.start_kernel(user_ns={**locals(), **globals(), **vars()}) 9 | -------------------------------------------------------------------------------- /example/r.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Class for rational numbers. 4 | 5 | A rational number is the ratio of two numbers. Examples of rational numbers 6 | include... 7 | 8 | - 3/2 9 | - 1/1 10 | - 4/6 11 | 12 | Rational numbers need not be normalized. 13 | 14 | """ 15 | 16 | import fractions 17 | 18 | 19 | class RationalNumber: 20 | def __init__(self, n, d): 21 | """Constructor 22 | 23 | >>> self = RationalNumber.__new__(RationalNumber) 24 | >>> n = 4 25 | >>> d = 2 26 | 27 | """ 28 | self.n = n 29 | self.d = d 30 | 31 | def __repr__(self): 32 | """Return a string representation 33 | 34 | >>> self = RationalNumber(n=4, d=2) 35 | 36 | """ 37 | r = f'{self.n}/{self.d}' 38 | return r 39 | 40 | def _normalize(self): 41 | """Return the fraction in simplied form 42 | 43 | >>> self = RationalNumber(n=4, d=2) 44 | 45 | """ 46 | gcd = fractions.gcd(self.n, self.d) 47 | n_ = int(self.n / gcd) 48 | d_ = int(self.d / gcd) 49 | r_ = RationalNumber(n_, d_) 50 | return r_ 51 | 52 | -------------------------------------------------------------------------------- /example/rational.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Class for rational numbers. 4 | 5 | A rational number is the ratio of two numbers. Examples of rational numbers 6 | include... 7 | 8 | - 3/2 9 | - 1/1 10 | - 4/6 11 | 12 | Rational numbers need not be normalized. 13 | 14 | """ 15 | 16 | import fractions 17 | 18 | 19 | class RationalNumber: 20 | def __init__(self, n, d): 21 | """Constructor 22 | 23 | >>> self = RationalNumber.__new__(RationalNumber) 24 | >>> n = 4 25 | >>> d = 2 26 | 27 | """ 28 | self.n = n 29 | self.d = d 30 | -------------------------------------------------------------------------------- /pynt.json: -------------------------------------------------------------------------------- 1 | { 2 | "tests": { 3 | "runner": "nosetests", 4 | "directory": "codebook/tests" 5 | }, 6 | "lazy-commands": { 7 | "codebook/node_transformers.IPythonEmbedder.get_kernel_embed": "ein:connect-run-or-eval-buffer", 8 | "codebook/syntax.promote_loop": "ein:connect-run-or-eval-buffer" 9 | }, 10 | "testable": [ 11 | "codebook/syntax.annotate", 12 | "codebook/node_transformers.FirstPassForSimple.visit_For" 13 | ], 14 | "module-commands": { 15 | "codebook/*": "ein:connect-run-or-eval-buffer", 16 | "bin/*": "ein:connect-run-or-eval-buffer" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /pynt/pynt.el: -------------------------------------------------------------------------------- 1 | ;;; pynt.el --- Generate and scroll EIN buffers from python code -*- lexical-binding: t -*- 2 | 3 | ;; Copyright (C) 2018 Free Software Foundation, Inc. 4 | 5 | ;; Author: Edward Banner 6 | ;; Version: 1.0 7 | ;; Package-Requires: ((emacs "24.4") (ein "0.13.1") (epc "0.1.1") (deferred "0.5.1")) 8 | ;; Keywords: convenience 9 | ;; URL: https://github.com/ebanner/pynt 10 | 11 | ;;; Commentary: 12 | 13 | ;; pynt is an Emacs minor mode for generating and interacting with EIN notebooks. 14 | ;; 15 | ;; Feature List 16 | ;; ------------ 17 | ;; - On-the-fly notebook creation 18 | ;; - Run the command `pynt-mode' on a python buffer and a new notebook will be created for you to interact with (provided you have set the variable `pynt-start-jupyter-server-on-startup' to t) 19 | ;; - Dump a region of python code into a EIN notebook 20 | ;; - Selectable regions include functions, methods, and code at the module level (i.e. outside of any function or class) 21 | ;; - Scroll the resulting EIN notebook with the code buffer 22 | ;; - Alignment between code and cells are preserved even when cells are added and deleted 23 | 24 | ;;; Code: 25 | 26 | (require 'seq) 27 | (require 'epc) 28 | (require 'epcs) 29 | (require 'ein-jupyter) 30 | 31 | (defgroup pynt nil 32 | "Customization group for pynt." 33 | :group 'applications) 34 | 35 | (defcustom pynt-epc-server-hostname "localhost" 36 | "The hostname of the EPC server. 37 | 38 | Usually set to \"localhost\" but if the jupyter kernel is running 39 | inside a docker container then this value should be 40 | \"docker.for.mac.localhost\" when on a mac. 41 | 42 | Using the value of a remote machine should be possible but is 43 | currently untested." 44 | :options '("localhost" "docker.for.mac.localhost")) 45 | 46 | (defcustom pynt-scroll t 47 | "Scroll the notebook buffer with the code buffer. " 48 | :options '(nil t)) 49 | 50 | (defcustom pynt-kernelspec "python3" "Kernelspec to create a notebook with.") 51 | 52 | (defcustom pynt-epc-port 9999 53 | "The port that the EPC server listens on. 54 | 55 | Every invocation of pynt mode increments this number so that pynt 56 | mode can run in multiple buffers.") 57 | 58 | (defcustom pynt-start-jupyter-server-on-startup t 59 | "Start a jupyter server on startup if t and do not otherwise. 60 | 61 | The jupyter server listens on the port defined by the variable 62 | `ein:url-or-port'.") 63 | 64 | (defcustom pynt-verbose nil 65 | "Log pynt debug information if t and do not otherwise.") 66 | 67 | (defvar pynt-init-code-template 68 | " 69 | 70 | %%matplotlib inline 71 | 72 | import time 73 | import IPython 74 | import epc.client 75 | 76 | epc_client = epc.client.EPCClient(('%s', %s), log_traceback=True) 77 | def __cell__(content, buffer_name, cell_type, line_number): 78 | epc_client.call_sync('make-cell', args=[content, buffer_name, cell_type, line_number]) 79 | time.sleep(0.01) 80 | 81 | %s # additional code 82 | " 83 | "Python code template which is evaluated early on. 84 | 85 | The value of `pynt-epc-server-hostname' and 86 | `pynt-epc-port' are used to complete this template. 87 | 88 | Having '__cell__()' and 'epc_client' defined in the associated 89 | IPython kernel allow the running python code to send code 90 | snippets to the EPC server.") 91 | 92 | (defvar pynt-epc-server nil 93 | "Emacs server. 94 | 95 | There only ever needs to be one EPC server, even across multiple 96 | pynt mode instances.") 97 | 98 | (defvar pynt-ast-server nil "Python AST server") 99 | 100 | (defvar-local pynt-code-buffer-file-name nil "The name of the file being visited.") 101 | 102 | (defvar-local pynt-namespace nil "The name current namespace.") 103 | 104 | (defvar-local pynt-line-to-cell-map nil 105 | "Map of source code lines to EIN cell(s). 106 | 107 | A source code line may be associated with more than one EIN 108 | cell (e.g. a line in the body of a for loop.") 109 | 110 | (defvar-local pynt-namespace-to-notebook-map nil 111 | "Map of namespaces to notebooks. 112 | 113 | Each namespace has its own indepenedent notebook.") 114 | 115 | (defvar-local pynt-notebook-files nil 116 | "List of EIN notebook files. 117 | 118 | Keep track of this so we delete all the notebooks when 119 | terminating pynt mode.") 120 | 121 | (defvar-local pynt-namespace-to-kernel-pid-map nil 122 | "Map of namespaces to kernel PIDs. 123 | 124 | Every time one sets up the state of a notebook by jacking in a 125 | subprocess is started which starts the kernel. These add up after 126 | a while and it is in our interest to kill those processes when 127 | their associated kernels can no longer be interacted with.") 128 | 129 | (defvar-local pynt-namespace-to-region-map nil 130 | "Map of namespace names to start and end lines. 131 | 132 | This map is used to produce a visual indication of which 133 | namespace corresponds to which code. It was originally part of a 134 | feature that was purely intended for making video demos prettier 135 | but does serve as a way to intuitively select a region of code. 136 | 137 | This map is used after a user changes the active namespace via 138 | the command `pynt-choose-namespace'.") 139 | 140 | (defun pynt-log (&rest args) 141 | "Log the message when the variable `pynt-verbose' is t. 142 | 143 | Optional argument ARGS the arguments you would normally pass to the function `message'." 144 | (when pynt-verbose 145 | (apply 'message args))) 146 | 147 | (defun pynt-toggle-debug () 148 | "Toggle pynt development mode. 149 | 150 | In pynt development mode we set the print-* variables to values 151 | so that when we try and print EIN deeply nested and recursive 152 | data structures they print and do not lock up emacs." 153 | (interactive) 154 | (setq pynt-verbose (not pynt-verbose) 155 | print-level (if print-level nil 1) 156 | print-length (if print-length nil 1) 157 | print-circle (not print-circle)) 158 | (if ein:debug 159 | (ein:dev-stop-debug) 160 | (ein:dev-start-debug))) 161 | 162 | (defun pynt-toggle-scroll () 163 | "Toggle notebook scrolling. 164 | 165 | Flips the value of the variable `pynt-scroll'." 166 | (interactive) 167 | (setq pynt-scroll (not pynt-scroll))) 168 | 169 | (defun pynt-notebook (&optional namespace) 170 | "Get the current notebook." 171 | (gethash (or namespace pynt-namespace) pynt-namespace-to-notebook-map)) 172 | 173 | (defun pynt-notebook-buffer (&optional namespace) 174 | "Get the buffer of the notebook." 175 | (ein:notebook-buffer (pynt-notebook (or namespace pynt-namespace)))) 176 | 177 | (defun pynt-notebook-window (&optional namespace) 178 | "Get the notebook window." 179 | (get-buffer-window (ein:notebook-buffer (pynt-notebook (or namespace pynt-namespace))))) 180 | 181 | (defun pynt-notebook-kernel (&optional namespace) 182 | (ein:$notebook-kernel (pynt-notebook (or namespace pynt-namespace)))) 183 | 184 | (defun pynt-module-name () 185 | "Extract the module-level name of the pynt code buffer. 186 | 187 | If the buffer is associated with a python file then chop off the 188 | '.py' suffix. Otherwise (e.g. if this is a *scratch* buffer) then 189 | just return the buffer name. 190 | 191 | Throw an error if the buffer name has a period in it because that 192 | will mess with the namespace naming convention that pynt uses." 193 | (let* ((script-name (file-name-nondirectory pynt-code-buffer-file-name))) 194 | (file-name-sans-extension script-name))) 195 | 196 | (defun pynt-recover-notebook-window (&optional detach) 197 | "Recover the notebook window. 198 | 199 | Use the function `python-info-current-defun' primarily. Handle 200 | the case where we are outside any defun." 201 | (interactive "p") 202 | (let* ((defun-at-point (python-info-current-defun)) 203 | (namespace-at-point (if defun-at-point 204 | (concat (pynt-module-name) "." defun-at-point) 205 | (pynt-module-name)))) 206 | (pynt-switch-or-init namespace-at-point detach))) 207 | 208 | (defun pynt-dump-namespace () 209 | "Dump the code in `pynt-active-namespace' into its EIN worksheet buffer. 210 | 211 | This is done by sending the code region out to the AST server 212 | where it is annotated with EPC calls and then the resulting code 213 | is sent to the IPython kernel to be executed." 214 | (interactive) 215 | (with-current-buffer pynt-code-buffer 216 | (pynt-offload-to-scratch-worksheet)) 217 | (let ((code (buffer-substring-no-properties (point-min) (point-max)))) 218 | (deferred:$ 219 | (epc:call-deferred pynt-ast-server 'annotate `(,code ,pynt-namespace ,t)) 220 | (deferred:nextc it 221 | (lambda (cells) 222 | (with-current-buffer pynt-code-buffer 223 | (dolist (cell cells) 224 | (apply 'pynt-make-cell cell)))))))) 225 | 226 | (defun pynt-goto-next-cell-line () 227 | "Move the point to the next line with a cell. 228 | 229 | Helps you get to where you want to get quicker." 230 | (interactive) 231 | (setq line-number (1+ (line-number-at-pos)) 232 | max-line-number (seq-max (map-keys pynt-line-to-cell-map))) 233 | (while (and (< line-number max-line-number) (not (gethash line-number pynt-line-to-cell-map))) 234 | (setq line-number (1+ line-number))) 235 | (when (gethash line-number pynt-line-to-cell-map) 236 | (goto-line line-number))) 237 | 238 | (defun pynt-goto-prev-cell-line () 239 | "Move the point to the next line with a cell. 240 | 241 | Helps you get to where you want to get quicker." 242 | (interactive) 243 | (setq line-number (1- (line-number-at-pos)) 244 | min-line-number (seq-min (map-keys pynt-line-to-cell-map))) 245 | (while (and (> line-number min-line-number) (not (gethash line-number pynt-line-to-cell-map))) 246 | (setq line-number (1- line-number))) 247 | (when (gethash line-number pynt-line-to-cell-map) 248 | (goto-line line-number))) 249 | 250 | (defun pynt-trace-namespace () 251 | "Dump the code in `pynt-active-namespace' into its notebook. 252 | 253 | FIXME this is experimental and not currently used." 254 | (interactive) 255 | (pynt-offload-to-scratch-worksheet) 256 | (let ((code (buffer-substring-no-properties (point-min) (point-max)))) 257 | (deferred:$ 258 | (epc:call-deferred pynt-ast-server 'annotate `(,code ,pynt-namespace)) 259 | (deferred:nextc it 260 | (lambda (annotated-code) 261 | (ein:connect-eval-buffer) 262 | (pynt-log "Annotated code = %s" annotated-code) 263 | (ein:shared-output-eval-string annotated-code)))))) 264 | 265 | (defun pynt-unpack (only-first) 266 | "Unpack an experession. 267 | 268 | Applies to the cell corresponding to the line at point. Pass the 269 | universal prefix argument to set TAKE-FIRST to t if you just want 270 | the first branch of the expression. Only try exps are currently 271 | supported." 272 | (interactive "P") 273 | (let* ((code (buffer-substring-no-properties (point-min) (point-max))) 274 | (only-first (if only-first 1 0))) 275 | (deferred:$ 276 | (message "Making deferred call!") 277 | (epc:call-deferred pynt-ast-server 'unpack `(,code ,pynt-namespace ,(line-number-at-pos) ,only-first)) 278 | (deferred:nextc it 279 | (lambda (cells) 280 | (with-current-buffer (pynt-notebook-buffer) 281 | (call-interactively 'ein:worksheet-kill-cell) 282 | (if (not (pynt-last-cell-p)) 283 | (call-interactively 'ein:worksheet-goto-prev-input))) 284 | (dolist (cell cells) 285 | (apply 'pynt-make-cell (add-to-list 'cell :at-point :append)))))))) 286 | 287 | (defun pynt-last-cell-p () 288 | "Return t if you are at the last cell in a notebook. 289 | 290 | Expects to be called in a notebook buffer." 291 | (let ((start (point))) 292 | (condition-case nil 293 | (save-excursion 294 | (call-interactively 'ein:worksheet-goto-next-input)) 295 | (error nil t)))) 296 | 297 | (defun pynt-scroll-cell-window () 298 | "Scroll the EIN worksheet buffer with the code buffer. 299 | 300 | Do it so the cell which corresponds to the line of code the point 301 | is on goes to the top. Make sure the cell we're about to jump to 302 | is is indeed the active buffer. 303 | 304 | Wrap the main logic in a condition case because it could be the 305 | case that the cell that did correspond to a line has since been 306 | deleted. Basically there is a bunch of data invalidation that I 307 | don't want to worry about at this time." 308 | (interactive) 309 | (when pynt-scroll 310 | (save-selected-window 311 | (let ((entry (gethash (line-number-at-pos) pynt-line-to-cell-map))) 312 | (when entry 313 | (condition-case exception 314 | (multiple-value-bind (namespace cell) entry 315 | (if (string= namespace pynt-namespace) 316 | (let* ((cell-marker (ein:cell-location cell :input)) 317 | (point-line (count-screen-lines (window-start) (point)))) 318 | (when cell-marker 319 | (select-window (pynt-notebook-window)) 320 | (widen) 321 | (goto-char cell-marker) 322 | (recenter point-line))) 323 | (pynt-switch-to-namespace namespace))) 324 | ('error))))))) 325 | 326 | (defun pynt-pop-up-notebook-buffer (buffer) 327 | "Pop up the notebook window. 328 | 329 | Always try and display the notebook to the right of the code 330 | buffer. This makes it so we can have multiple code buffers on top 331 | of each other and their notebooks to the right." 332 | (condition-case nil 333 | (save-selected-window 334 | (windmove-right) 335 | (switch-to-buffer buffer)) 336 | (error nil (with-selected-window (split-window-horizontally) 337 | (switch-to-buffer buffer))))) 338 | 339 | (defun pynt-rename-notebook () 340 | "Rename the notebook to the current namespace. 341 | 342 | TODO I've tried to get this working twice and it leads to weird 343 | errors each time. It would be very nice to get working eventually!" 344 | (interactive) 345 | (let* ((relative-path (replace-regexp-in-string (expand-file-name "~/") "" pynt-code-buffer-file-name)) 346 | (relative-dir (file-name-directory relative-path)) 347 | (notebook-path (concat relative-dir pynt-namespace ".ipynb"))) 348 | (condition-case nil 349 | (delete-file (file-name-nondirectory notebook-path)) 350 | (error nil)) 351 | (with-current-buffer (pynt-notebook-buffer) 352 | (message "Attempting rename to %s..." notebook-path) 353 | (let* ((old-notebook-path (ein:$notebook-notebook-path ein:%notebook%)) 354 | (old-notebook-name (file-name-nondirectory old-notebook-path))) 355 | (ein:notebook-rename-command notebook-path) 356 | (delete-file old-notebook-name))))) 357 | 358 | (defun pynt-setup-notebook (&rest -ignore-) 359 | "Default callback for `ein:notebook-open'. 360 | 361 | Create a notebook for the module-level namespace. In the future 362 | maybe do this for all the namespaces in the beginning!" 363 | ;; Possibly pop up the notebook. 364 | (when pynt-pop-up-notebook 365 | (pynt-pop-up-notebook-buffer (current-buffer))) 366 | (setq pynt-pop-up-notebook nil) 367 | 368 | (setq notebook ein:%notebook%) 369 | (with-current-buffer pynt-code-buffer 370 | (pynt-log "Putting %s into hash..." pynt-namespace) 371 | (puthash pynt-namespace notebook pynt-namespace-to-notebook-map) 372 | (add-to-list 'pynt-notebook-files (ein:notebook-name notebook)) 373 | 374 | (with-current-buffer (pynt-notebook-buffer) 375 | (ein:notebook-worksheet-insert-next ein:%notebook% ein:%worksheet% :render nil)) 376 | 377 | (pynt-dump-namespace) 378 | 379 | (pynt-connect-to-notebook-buffer (pynt-notebook-buffer)))) 380 | 381 | (defun pynt-new-notebook (&optional pop-up-notebook) 382 | "Create a new EIN notebook and bring it up side-by-side. 383 | 384 | Make sure the new notebook is created in the same directory as 385 | the python file so that relative imports in the code work fine. 386 | 387 | Set the pynt code buffer name because this function will jump the 388 | point to another window. In general buffer names are not to be 389 | relied on remember!" 390 | (interactive) 391 | (multiple-value-bind (url-or-port token) (ein:jupyter-server-conn-info) 392 | (let* ((nb-dir (replace-regexp-in-string (or ein:jupyter-default-notebook-directory 393 | (expand-file-name "~/")) 394 | "" 395 | default-directory))) 396 | (with-current-buffer (ein:notebooklist-get-buffer url-or-port) 397 | (setq pynt-pop-up-notebook pop-up-notebook) 398 | (ein:notebooklist-new-notebook url-or-port 399 | (ein:get-kernelspec url-or-port pynt-kernelspec) 400 | (string-trim-right nb-dir "/") 401 | 'pynt-setup-notebook))))) 402 | 403 | (defun pynt-start-epc-server () 404 | "Start the EPC server and register its associated handlers. 405 | 406 | Exit if there is already an EPC server." 407 | (when (not pynt-epc-server) 408 | 409 | ;; Handlers. 410 | (defun handle-make-cell (&rest args) 411 | (multiple-value-bind (expr namespace cell-type line-number) args 412 | (pynt-make-cell expr namespace cell-type (string-to-number line-number)) 413 | nil)) 414 | 415 | ;; Views. 416 | (let ((connect-function 417 | (lambda (mngr) 418 | (let ((mngr mngr)) 419 | (epc:define-method mngr 'make-cell 'handle-make-cell))))) 420 | 421 | ;; Server. 422 | (setq pynt-epc-server (epcs:server-start connect-function pynt-epc-port))))) 423 | 424 | 425 | (defun pynt-make-cell (expr namespace cell-type line-number &optional at-point) 426 | "Make a new EIN cell and evaluate it. 427 | 428 | Insert a new code cell with contents EXPR into the worksheet 429 | buffer NAMESPACE with cell type CELL-TYPE at the end of the 430 | worksheet and evaluate it. 431 | 432 | This function is called from python code running in a jupyter 433 | kernel via RPC. 434 | 435 | LINE-NUMBER is the line number in the code that the cell 436 | corresponds and is used during pynt scroll mode. If LINE-NUMBER 437 | is -1 then that means the cell has no corresponding line. This 438 | happens with certain markdown cells which are generated. 439 | 440 | Since the variable `pynt-line-to-cell-map' is buffer-local we 441 | have to take special care to not access it while we're over in 442 | the worksheet buffer. Instead we save the variable we wish to 443 | append to `pynt-line-to-cell-map' into a temporary variable and 444 | then add it to `pynt-line-to-cell-map' when we're back in the 445 | code buffer. 446 | 447 | If AT-POINT is t then insert the cell at the point." 448 | (pynt-log "(pytn-make-cell %S %S %S %S)..." expr namespace cell-type line-number) 449 | 450 | ;; These variables are buffer local so we need to grab them before switching 451 | ;; over to the worksheet buffer. 452 | (setq new-cell nil) ; new cell to be added 453 | (with-current-buffer (pynt-notebook-buffer) 454 | (when (not at-point) 455 | (end-of-buffer)) 456 | (call-interactively 'ein:worksheet-insert-cell-below) 457 | (insert expr) 458 | (let ((cell (ein:get-cell-at-point)) 459 | (ws (ein:worksheet--get-ws-or-error))) 460 | (cond ((string= cell-type "code") (ein:cell-set-autoexec cell t)) 461 | ((string= cell-type "markdown") (ein:worksheet-change-cell-type ws cell "markdown")) 462 | (t (ein:worksheet-change-cell-type ws cell "heading" (string-to-number cell-type)))) 463 | (setq new-cell cell))) 464 | (when (and (not at-point) (pynt-notebook-window)) 465 | (with-selected-window (pynt-notebook-window) 466 | (beginning-of-buffer))) 467 | (when (not (eq line-number -1)) 468 | (puthash line-number (list namespace new-cell) pynt-line-to-cell-map))) 469 | 470 | (defun pynt-start-ast-server () 471 | "Start python AST server." 472 | (when (not pynt-ast-server) 473 | (setq pynt-ast-server (epc:start-epc "pynt-serve" nil)))) 474 | 475 | (defun pynt-init-epc-client (additional-code &optional callback cbargs) 476 | "Initialize the EPC client for the EIN notebook. 477 | 478 | This needs to be done so python can send commands to Emacs to 479 | create code cells. Use the variables 480 | `pynt-epc-server-hostname' and `pynt-epc-port' to define 481 | the communication channels for the EPC client. 482 | 483 | Argument CALLBACK is a function to call afterwards." 484 | (pynt-log "Initiating EPC cient...") 485 | 486 | (deferred:$ 487 | ;; Poll until kernel is live and then connect code buffer to notebook. 488 | (deferred:next 489 | (deferred:lambda () 490 | (with-current-buffer pynt-code-buffer 491 | (if (ein:kernel-live-p (pynt-notebook-kernel)) 492 | (progn 493 | (pynt-log "Kernel is live!") 494 | 'kernel-is-live) 495 | (pynt-log "Kernel not live...") 496 | (deferred:nextc (deferred:wait 500) self))))) 497 | 498 | ;; Evaluate init code. 499 | (deferred:nextc it 500 | (lambda (msg) 501 | (let ((pynt-init-code (format pynt-init-code-template pynt-epc-server-hostname pynt-epc-port additional-code))) 502 | (pynt-log "Evaluating initial code!") 503 | (ein:shared-output-eval-string pynt-init-code)) 504 | nil)) 505 | 506 | ;; Run callback. 507 | (deferred:nextc it 508 | (lambda (msg) 509 | (when callback (apply callback cbargs)))))) 510 | 511 | (defun pynt-intercept-ein-notebook-name (old-function buffer-or-name) 512 | "Advice to add around `ein:connect-to-notebook-buffer'. 513 | 514 | So pynt mode can grab the buffer name of the main worksheet. 515 | 516 | Argument OLD-FUNCTION the function we are wrapping. 517 | Argument BUFFER-OR-NAME the name of the notebook we are connecting to." 518 | (pynt-log "Setting main worksheet name = %S" buffer-or-name) 519 | (apply old-function (list buffer-or-name))) 520 | 521 | (defun pynt-offload-to-scratch-worksheet () 522 | "Move cells from the main notebook to the scratch notebook." 523 | (with-current-buffer (pynt-notebook-buffer) 524 | (beginning-of-buffer) 525 | (push-mark (point-max)) 526 | (activate-mark) 527 | (condition-case nil ; worksheet may be empty 528 | (progn 529 | (call-interactively 'ein:worksheet-kill-cell) 530 | (let ((worksheets (ein:$notebook-worksheets ein:%notebook%))) 531 | (with-current-buffer (ein:worksheet-buffer (nth 1 worksheets)) 532 | (beginning-of-buffer) 533 | (call-interactively 'ein:worksheet-yank-cell)))) 534 | (error nil)))) 535 | 536 | (defun pynt-run-all-cells-above () 537 | "Execute all cells above and including the cell at point. 538 | 539 | This is a convenience function meant to be used by users of 540 | pynt (and EIN)." 541 | (interactive) 542 | (save-excursion 543 | (let ((end-cell (ein:get-cell-at-point))) 544 | (beginning-of-buffer) 545 | (setq cell (ein:get-cell-at-point)) 546 | (while (not (eq cell end-cell)) 547 | (call-interactively 'ein:worksheet-execute-cell-and-goto-next) 548 | (setq cell (ein:get-cell-at-point))) 549 | (call-interactively 'ein:worksheet-execute-cell)))) 550 | 551 | (defun pynt-project-root () 552 | "Get the project root. 553 | 554 | Ask projectile for the project root. If not in a project then 555 | just return the current directory." 556 | (condition-case nil 557 | (projectile-project-root) 558 | (error (file-name-directory pynt-code-buffer-file-name)))) 559 | 560 | (defun pynt-jupyter-server-start () 561 | "Start a jupyter notebook server. 562 | 563 | Start it in the user's home directory and use the 564 | `ExternalIPythonKernelManager' so we can attach to external 565 | IPython kernels. 566 | 567 | Only start a jupyter notebook server if one has not already been 568 | started." 569 | (interactive) 570 | (condition-case nil 571 | (ein:jupyter-server-conn-info) 572 | (error nil 573 | (let* ((extipy-args '("--NotebookApp.kernel_manager_class=codebook.ExternalIPythonKernelManager" 574 | "--Session.key=b'\"\"'")) 575 | (ein:jupyter-server-args (append ein:jupyter-server-args extipy-args))) 576 | (ein:jupyter-server-start (executable-find ein:jupyter-default-server-command) 577 | (or ein:jupyter-default-notebook-directory 578 | (expand-file-name "~/"))))))) 579 | 580 | (defun pynt-reattach-save-detach (f &rest args) 581 | (if (not (called-interactively-p 'interactive)) 582 | (apply f args) 583 | (if (not pynt-mode) 584 | (apply f args) 585 | (write-file pynt-code-buffer-file-name) 586 | (apply f args) 587 | (when pynt-namespace 588 | (pynt-detach-from-underlying-file))))) 589 | 590 | (defun pynt-switch-to-namespace (namespace) 591 | "Switch to NAMESPACE. 592 | 593 | This involves switching out the active notebook and also 594 | attaching the code buffer to it. 595 | 596 | The function `pynt-pop-up-notebook-buffer' calls `display-buffer' 597 | which will run the `pynt-rebalance-on-window-change' hook which 598 | will run this function again and we will get into an infinite 599 | loop. Hence we set this lock so that the buffer and window hooks 600 | won't run until this finishes." 601 | (pynt-log "Switching to namespace = %s..." namespace) 602 | (setq pynt-namespace namespace) 603 | (pynt-pop-up-notebook-buffer (pynt-notebook-buffer)) 604 | (deferred:$ 605 | (deferred:next 606 | (lambda () 607 | (with-current-buffer pynt-code-buffer 608 | (pynt-log "Connecting to code buffer to notebook...") 609 | (pynt-connect-to-notebook-buffer (pynt-notebook-buffer)) 610 | (pynt-detach-from-underlying-file)))))) 611 | 612 | (defun pynt-connect-to-notebook-buffer (notebook-buffer) 613 | (ein:connect-to-notebook-buffer notebook-buffer) 614 | (when (not (slot-value ein:%connect% 'autoexec)) 615 | (ein:connect-toggle-autoexec))) 616 | 617 | (defun pynt-switch-or-init (namespace &optional detach) 618 | "Switch to NAMESPACE. 619 | 620 | Initialize it if it has not been initialized. 621 | 622 | This function is necessary because of the way we can create 623 | notebooks. When we run the command `pynt-switch-namespace' if the 624 | selected namespace has not been created then we create it. It's 625 | like launching pynt mode for the very first time. Otherwise if it 626 | exists we just switch to it." 627 | (if (gethash namespace pynt-namespace-to-notebook-map) 628 | (pynt-switch-to-namespace namespace) 629 | (pynt-init namespace :pop-up-notebook detach))) 630 | 631 | (defun pynt-invalidate-scroll-map (&optional a b c) 632 | (pynt-log "Invalidating scroll map!") 633 | (setq pynt-line-to-cell-map (make-hash-table :test 'equal))) 634 | 635 | (defun pynt-detach-from-underlying-file () 636 | "Replace namespace in underlying file with a kernel breakpoint. 637 | 638 | Save the buffer first. Then detach from the underlying file." 639 | (write-file pynt-code-buffer-file-name) 640 | (save-buffer) 641 | (set-visited-file-name nil) 642 | (start-process "*pynt embed*" 643 | "*pynt embed*" 644 | "pynt-embed" 645 | "-namespace" pynt-namespace)) 646 | 647 | (defun pynt-init (namespace &optional pop-up detach) 648 | "Initialize a namespace. 649 | 650 | This involves creating a notebook if we haven't created one yet." 651 | 652 | ;; Locals. 653 | (setq pynt-namespace namespace 654 | pynt-code-buffer (buffer-name)) 655 | 656 | ;; Detach from visited file and replace file with kernel break point. 657 | (when detach 658 | (pynt-detach-from-underlying-file)) 659 | 660 | ;; Create new notebook. 661 | (pynt-new-notebook pop-up)) 662 | 663 | (defun pynt-mode-deactivate (&optional buffer) 664 | "Deactivate pynt mode." 665 | 666 | ;; Remove hooks. 667 | (advice-remove 'ein:connect-to-notebook-buffer 'pynt-intercept-ein-notebook-name) 668 | (remove-hook 'after-change-functions 'pynt-invalidate-scroll-map :local) 669 | (remove-hook 'post-command-hook 'pynt-scroll-cell-window :local) 670 | 671 | ;; I suspect the call to the function 672 | ;; `ein:notebook-kill-kernel-then-close-command' pops us into another buffer 673 | ;; unexpectedly. Save the code buffer here and force each command to execute 674 | ;; from within the code buffer. 675 | (setq code-buffer (or buffer (current-buffer))) 676 | 677 | ;; Delete notebook window. 678 | (condition-case nil 679 | (with-current-buffer code-buffer 680 | (when (pynt-notebook-window) 681 | (delete-window (pynt-notebook-window)))) 682 | (error nil)) 683 | 684 | ;; Kill kernels. Sometimes EIN deletes the notebooks before we can get here. 685 | ;; Hence the function `pynt-notebook-buffer' sometimes returns nil. But this 686 | ;; may be only when the notebook is deemed "modified" by EIN (or not). In any 687 | ;; event do our best to clean up. 688 | (condition-case nil 689 | (with-current-buffer code-buffer 690 | (dolist (namespace (map-keys pynt-namespace-to-notebook-map)) 691 | (with-current-buffer (pynt-notebook-buffer namespace) 692 | (call-interactively 'ein:notebook-kill-kernel-then-close-command)))) 693 | (error nil)) 694 | 695 | ;; Reattach to underlying file and save to disk. Save the file for real. Don't 696 | ;; detach from it. But also don't disable this for other buffers using pynt 697 | ;; mode. 698 | (with-current-buffer code-buffer 699 | (write-file pynt-code-buffer-file-name) 700 | (advice-remove 'save-buffer 'pynt-reattach-save-detach) 701 | (save-buffer) 702 | (advice-add 'save-buffer :around 'pynt-reattach-save-detach)) 703 | 704 | ;; Delete all the notebook files. 705 | (with-current-buffer code-buffer 706 | (dolist (notebook-file pynt-notebook-files) 707 | (delete-file notebook-file)) 708 | (message (format "Deleted %s" pynt-notebook-files))) 709 | 710 | ;; Disable ein connect mode. 711 | (ein:connect-mode -1)) 712 | 713 | (defun pynt-deactivate-buffers () 714 | "Clean up pynt mode from all the buffers." 715 | (dolist (buffer (buffer-list)) 716 | (with-current-buffer buffer 717 | (when pynt-mode 718 | (pynt-mode-deactivate buffer))))) 719 | 720 | (defvar pynt-mode-map 721 | (let ((map (make-sparse-keymap))) 722 | (define-key map (kbd "C-c C-e") 'pynt-dump-namespace) 723 | (define-key map (kbd "C-c C-s") 'pynt-recover-notebook-window) 724 | (define-key map (kbd "C-c C-k") 'pynt-unpack) 725 | (define-key map (kbd "C-c C-n") 'pynt-goto-next-cell-line) 726 | (define-key map (kbd "C-c C-p") 'pynt-goto-prev-cell-line) 727 | (define-key map (kbd "") 'pynt-next-cell-instance) 728 | (define-key map (kbd "") 'pynt-prev-cell-instance) 729 | map)) 730 | 731 | ;;;###autoload 732 | (define-minor-mode pynt-mode 733 | "Minor mode for generating and interacting with jupyter notebooks via EIN 734 | 735 | \\{pynt-mode-map}" 736 | :keymap pynt-mode-map 737 | :lighter "pynt" 738 | (if pynt-mode 739 | (progn 740 | 741 | ;; Variables. 742 | (setq pynt-namespace-to-notebook-map (make-hash-table :test 'equal) 743 | pynt-namespace-to-kernel-pid-map (make-hash-table :test 'equal) 744 | pynt-line-to-cell-map (make-hash-table :test 'equal) 745 | pynt-code-buffer-file-name (buffer-file-name) 746 | pynt-code-buffer (current-buffer)) 747 | 748 | ;; Initialize servers. 749 | (pynt-start-epc-server) 750 | (pynt-start-ast-server) 751 | (pynt-jupyter-server-start) 752 | 753 | ;; Hooks. 754 | (add-hook 'after-change-functions 'pynt-invalidate-scroll-map nil :local) 755 | (add-hook 'post-command-hook 'pynt-scroll-cell-window nil :local) 756 | (add-hook 'kill-emacs-hook 'pynt-deactivate-buffers) 757 | (add-hook 'kill-buffer-hook 'pynt-mode-deactivate nil :local) 758 | (advice-add 'save-buffer :around 'pynt-reattach-save-detach)) 759 | 760 | (pynt-mode-deactivate))) 761 | 762 | ;;;###autoload 763 | (add-hook 'python-mode-hook 764 | (lambda () 765 | (when (not (string-match-p (regexp-quote "ein:") (buffer-name))) 766 | (pynt-mode)))) 767 | 768 | (provide 'pynt) 769 | ;;; pynt.el ends here 770 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | 4 | setup( 5 | name='codebook', 6 | version='1.1.0', 7 | description='Emacs minor mode for generating and interacting with jupyter notebooks', 8 | long_description=open('README.md').read(), 9 | long_description_content_type="text/markdown", 10 | url='http://github.com/ebanner/pynt', 11 | classifiers=[ 12 | 'Development Status :: 3 - Alpha', 13 | 'Environment :: MacOS X', 14 | 'Programming Language :: Python :: 3.6', 15 | 'Framework :: IPython', 16 | 'Framework :: Jupyter', 17 | 'Intended Audience :: Developers', 18 | 'Intended Audience :: Developers', 19 | 'Intended Audience :: Education', 20 | 'License :: OSI Approved :: MIT License', 21 | 'Natural Language :: English', 22 | 'Operating System :: MacOS', 23 | 'Topic :: Education', 24 | 'Topic :: Software Development', 25 | 'Topic :: Software Development :: Code Generators', 26 | 'Topic :: Software Development :: Debuggers', 27 | 'Topic :: Software Development :: Documentation', 28 | 'Topic :: Text Editors', 29 | 'Topic :: Text Editors :: Emacs', 30 | 'Topic :: Text Editors :: Integrated Development Environments (IDE)' 31 | ], 32 | keywords='interactive programming jupyter ipython emacs', 33 | author='Edward Banner', 34 | author_email='edward.banner@gmail.com', 35 | license='MIT', 36 | packages=['codebook'], 37 | scripts=[ 38 | 'bin/pynt-embed', 39 | 'bin/pynt-serve', 40 | ], 41 | install_requires=[ 42 | 'jupyter', 43 | 'astor', 44 | 'plac', 45 | 'epc' 46 | ], 47 | test_suite='nose.collector', 48 | tests_require=['nose'], 49 | include_package_data=True, 50 | zip_safe=False, 51 | ) 52 | --------------------------------------------------------------------------------