/usr/lib/python2.7/dist-packages/notebook/static/notebook/js/notebook.js is in python-notebook 5.2.2-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/**
* @module notebook
*/
"use strict";
define([
'jquery',
'base/js/namespace',
'underscore',
'base/js/utils',
'base/js/i18n',
'base/js/dialog',
'./cell',
'./textcell',
'./codecell',
'moment',
'services/config',
'services/sessions/session',
'./celltoolbar',
'components/marked/lib/marked',
'codemirror/lib/codemirror',
'codemirror/addon/runmode/runmode',
'./mathjaxutils',
'base/js/keyboard',
'./tooltip',
'./celltoolbarpresets/default',
'./celltoolbarpresets/rawcell',
'./celltoolbarpresets/slideshow',
'./celltoolbarpresets/attachments',
'./celltoolbarpresets/tags',
'./scrollmanager',
'./commandpalette',
'./shortcuteditor',
], function (
$,
IPython,
_,
utils,
i18n,
dialog,
cellmod,
textcell,
codecell,
moment,
configmod,
session,
celltoolbar,
marked,
CodeMirror,
runMode,
mathjaxutils,
keyboard,
tooltip,
default_celltoolbar,
rawcell_celltoolbar,
slideshow_celltoolbar,
attachments_celltoolbar,
tags_celltoolbar,
scrollmanager,
commandpalette,
shortcuteditor
) {
var ShortcutEditor = shortcuteditor.ShortcutEditor;
var _SOFT_SELECTION_CLASS = 'jupyter-soft-selected';
function soft_selected(cell){
return cell.element.hasClass(_SOFT_SELECTION_CLASS);
}
/**
* Contains and manages cells.
* @class Notebook
* @param {string} selector
* @param {object} options - Dictionary of keyword arguments.
* @param {jQuery} options.events - selector of Events
* @param {KeyboardManager} options.keyboard_manager
* @param {Contents} options.contents
* @param {SaveWidget} options.save_widget
* @param {object} options.config
* @param {string} options.base_url
* @param {string} options.notebook_path
* @param {string} options.notebook_name
*/
function Notebook(selector, options) {
this.config = options.config;
this.config.loaded.then(this.validate_config.bind(this))
this.class_config = new configmod.ConfigWithDefaults(this.config,
Notebook.options_default, 'Notebook');
this.base_url = options.base_url;
this.notebook_path = options.notebook_path;
this.notebook_name = options.notebook_name;
this.events = options.events;
this.keyboard_manager = options.keyboard_manager;
this.contents = options.contents;
this.save_widget = options.save_widget;
this.tooltip = new tooltip.Tooltip(this.events);
this.ws_url = options.ws_url;
this._session_starting = false;
this.last_modified = null;
// debug 484
this._last_modified = 'init';
// Firefox workaround
this._ff_beforeunload_fired = false;
// Create default scroll manager.
this.scroll_manager = new scrollmanager.ScrollManager(this);
// TODO: This code smells (and the other `= this` line a couple lines down)
// We need a better way to deal with circular instance references.
this.keyboard_manager.notebook = this;
this.save_widget.notebook = this;
mathjaxutils.init();
if (marked) {
marked.setOptions({
gfm : true,
tables: true,
// FIXME: probably want central config for CodeMirror theme when we have js config
langPrefix: "cm-s-ipython language-",
highlight: function(code, lang, callback) {
if (!lang) {
// no language, no highlight
if (callback) {
callback(null, code);
return;
} else {
return code;
}
}
utils.requireCodeMirrorMode(lang, function (spec) {
var el = document.createElement("div");
var mode = CodeMirror.getMode({}, spec);
if (!mode) {
console.log("No CodeMirror mode: " + lang);
callback(null, code);
return;
}
try {
CodeMirror.runMode(code, spec, el);
callback(null, el.innerHTML);
} catch (err) {
console.log("Failed to highlight " + lang + " code", err);
callback(err, code);
}
}, function (err) {
console.log("No CodeMirror mode: " + lang);
console.log("Require CodeMirror mode error: " + err);
callback(null, code);
});
}
});
}
this.element = $(selector);
this.element.scroll();
this.element.data("notebook", this);
this.session = null;
this.kernel = null;
this.kernel_busy = false;
this.clipboard = null;
this.clipboard_attachments = null;
this.undelete_backup_stack = [];
this.paste_enabled = false;
this.paste_attachments_enabled = false;
this.writable = false;
// It is important to start out in command mode to match the intial mode
// of the KeyboardManager.
this.mode = 'command';
this.set_dirty(false);
this.metadata = {};
this._checkpoint_after_save = false;
this.last_checkpoint = null;
this.checkpoints = [];
this.autosave_interval = 0;
this.autosave_timer = null;
// autosave *at most* every two minutes
this.minimum_autosave_interval = 120000;
this.notebook_name_blacklist_re = /[\/\\:]/;
this.nbformat = 4; // Increment this when changing the nbformat
this.nbformat_minor = this.current_nbformat_minor = 1; // Increment this when changing the nbformat
this.codemirror_mode = 'text';
this.create_elements();
this.bind_events();
this.kernel_selector = null;
this.dirty = null;
this.trusted = null;
this._changed_on_disk_dialog = null;
this._fully_loaded = false;
// Trigger cell toolbar registration.
default_celltoolbar.register(this);
rawcell_celltoolbar.register(this);
slideshow_celltoolbar.register(this);
attachments_celltoolbar.register(this);
tags_celltoolbar.register(this);
var that = this;
Object.defineProperty(this, 'line_numbers', {
get: function() {
var d = that.config.data || {};
var cmc = (d['Cell'] || {}) ['cm_config'] || {};
return cmc['lineNumbers'] || false;
},
set: function(value) {
that.config.update({
'Cell': {
'cm_config': {
'lineNumbers':value
}
}
});
}
});
Object.defineProperty(this, 'header', {
get: function() {
return that.class_config.get_sync('Header');
},
set: function(value) {
that.class_config.set('Header', value);
}
});
Object.defineProperty(this, 'toolbar', {
get: function() {
return that.class_config.get_sync('Toolbar');
},
set: function(value) {
that.class_config.set('Toolbar', value);
}
});
this.class_config.get('Header').then(function(header) {
if (header === false) {
that.keyboard_manager.actions.call('jupyter-notebook:hide-header');
}
});
this.class_config.get('Toolbar').then(function(toolbar) {
if (toolbar === false) {
that.keyboard_manager.actions.call('jupyter-notebook:hide-toolbar');
}
});
// prevent assign to miss-typed properties.
Object.seal(this);
};
Notebook.options_default = {
// can be any cell type, or the special values of
// 'above', 'below', or 'selected' to get the value from another cell.
default_cell_type: 'code',
Header: true,
Toolbar: true
};
Notebook.prototype.validate_config = function() {
var code_cell = this.config.data['CodeCell'] || {};
var cm_keymap = (code_cell['cm_config'] || {})['keyMap'];
if (cm_keymap && CodeMirror.keyMap[cm_keymap] === undefined) {
console.warn('CodeMirror keymap not found, ignoring: ' + cm_keymap);
delete code_cell.cm_config.keyMap;
}
};
/**
* Create an HTML and CSS representation of the notebook.
*/
Notebook.prototype.create_elements = function () {
var that = this;
this.element.attr('tabindex','-1');
this.container = $("<div/>").addClass("container").attr("id", "notebook-container");
// We add this end_space div to the end of the notebook div to:
// i) provide a margin between the last cell and the end of the notebook
// ii) to prevent the div from scrolling up when the last cell is being
// edited, but is too low on the page, which browsers will do automatically.
var end_space = $('<div/>')
.addClass('end_space');
end_space.dblclick(function (e) {
var ncells = that.ncells();
that.insert_cell_below('code',ncells-1);
});
this.element.append(this.container);
this.container.after(end_space);
};
/**
* Bind JavaScript events: key presses and custom Jupyter events.
*/
Notebook.prototype.bind_events = function () {
var that = this;
this.events.on('set_next_input.Notebook', function (event, data) {
if (data.replace) {
data.cell.set_text(data.text);
if (data.clear_output !== false) {
// default (undefined) is true to preserve prior behavior
data.cell.clear_output();
}
} else {
var index = that.find_cell_index(data.cell);
var new_cell = that.insert_cell_below('code',index);
new_cell.set_text(data.text);
}
that.dirty = true;
});
this.events.on('unrecognized_cell.Cell', function () {
that.warn_nbformat_minor();
});
this.events.on('unrecognized_output.OutputArea', function () {
that.warn_nbformat_minor();
});
this.events.on('set_dirty.Notebook', function (event, data) {
that.dirty = data.value;
});
this.events.on('trust_changed.Notebook', function (event, trusted) {
that.trusted = trusted;
});
this.events.on('select.Cell', function (event, data) {
var index = that.find_cell_index(data.cell);
that.select(index, !data.extendSelection);
});
this.events.on('edit_mode.Cell', function (event, data) {
that.handle_edit_mode(data.cell);
});
this.events.on('command_mode.Cell', function (event, data) {
that.handle_command_mode(data.cell);
});
this.events.on('spec_changed.Kernel', function(event, data) {
var existing_spec = that.metadata.kernelspec;
that.metadata.kernelspec = {
name: data.name,
display_name: data.spec.display_name,
language: data.spec.language,
};
if (!existing_spec || ! _.isEqual(existing_spec, that.metadata.kernelspec)) {
that.set_dirty(true);
}
// start a new session
that.start_session(data.name);
});
this.events.on('kernel_ready.Kernel', function(event, data) {
var kinfo = data.kernel.info_reply;
if (!kinfo.language_info) {
delete that.metadata.language_info;
return;
}
var existing_info = that.metadata.language_info;
var langinfo = kinfo.language_info;
that.metadata.language_info = langinfo;
if (!existing_info || ! _.isEqual(existing_info, langinfo)) {
that.set_dirty(true);
}
// Mode 'null' should be plain, unhighlighted text.
var cm_mode = langinfo.codemirror_mode || langinfo.name || 'null';
that.set_codemirror_mode(cm_mode);
});
this.events.on('kernel_idle.Kernel', function () {
that.kernel_busy = false;
});
this.events.on('kernel_busy.Kernel', function () {
that.kernel_busy = true;
});
var collapse_time = function (time) {
var app_height = $('#ipython-main-app').height(); // content height
var splitter_height = $('div#pager_splitter').outerHeight(true);
var new_height = app_height - splitter_height;
that.element.animate({height : new_height + 'px'}, time);
};
this.element.bind('collapse_pager', function (event, extrap) {
var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
collapse_time(time);
});
var expand_time = function (time) {
var app_height = $('#ipython-main-app').height(); // content height
var splitter_height = $('div#pager_splitter').outerHeight(true);
var pager_height = $('div#pager').outerHeight(true);
var new_height = app_height - pager_height - splitter_height;
that.element.animate({height : new_height + 'px'}, time);
};
this.element.bind('expand_pager', function (event, extrap) {
var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
expand_time(time);
});
// Firefox 22 broke $(window).on("beforeunload")
// I'm not sure why or how.
window.onbeforeunload = function (e) {
// TODO: Make killing the kernel configurable.
var kill_kernel = false;
if (kill_kernel) {
that.session.delete();
}
if ( utils.browser[0] === "Firefox") {
// Workaround ancient Firefox bug showing beforeunload twice: https://bugzilla.mozilla.org/show_bug.cgi?id=531199
if (that._ff_beforeunload_fired) {
return; // don't show twice on FF
}
that._ff_beforeunload_fired = true;
// unset flag immediately after dialog is dismissed
setTimeout(function () {
that._ff_beforeunload_fired = false;
}, 1);
}
// if we are autosaving, trigger an autosave on nav-away.
// still warn, because if we don't the autosave may fail.
if (that.dirty) {
if ( that.autosave_interval ) {
// schedule autosave in a timeout
// this gives you a chance to forcefully discard changes
// by reloading the page if you *really* want to.
// the timer doesn't start until you *dismiss* the dialog.
setTimeout(function () {
if (that.dirty) {
that.save_notebook();
}
}, 1000);
return i18n.msg._("Autosave in progress, latest changes may be lost.");
} else {
return i18n.msg._("Unsaved changes will be lost.");
}
}
// if the kernel is busy, prompt the user if he’s sure
if (that.kernel_busy) {
return i18n.msg._("The Kernel is busy, outputs may be lost.");
}
// IE treats null as a string. Instead just return which will avoid the dialog.
return;
};
};
Notebook.prototype.show_command_palette = function() {
var x = new commandpalette.CommandPalette(this);
};
Notebook.prototype.show_shortcuts_editor = function() {
new ShortcutEditor(this);
};
/**
* Trigger a warning dialog about missing functionality from newer minor versions
*/
Notebook.prototype.warn_nbformat_minor = function (event) {
var v = 'v' + this.nbformat + '.';
var orig_vs = v + this.nbformat_minor;
var this_vs = v + this.current_nbformat_minor;
var msg = i18n.msg.sprintf(i18n.msg._("This notebook is version %1$s, but we only fully support up to %2$s."),
orig_vs,this_vs) + " " +
i18n.msg._("You can still work with this notebook, but cell and output types introduced in later notebook versions will not be available.");
// This statement is used simply so that message extraction
// will pick up the strings. The actual setting of the text
// for the button is in dialog.js.
var button_labels = [
i18n.msg._("OK"),
i18n.msg._("Restart and Run All Cells"),
i18n.msg._("Restart and Clear All Outputs"),
i18n.msg._("Restart"),
i18n.msg._("Continue Running"),
i18n.msg._("Reload"),
i18n.msg._("Cancel"),
i18n.msg._("Overwrite"),
i18n.msg._("Trust"),
i18n.msg._("Revert")];
dialog.modal({
notebook: this,
keyboard_manager: this.keyboard_manager,
title : i18n.msg._("Newer Notebook"),
body : msg,
buttons : {
OK : {
"class" : "btn-danger"
}
}
});
};
/**
* Set the dirty flag, and trigger the set_dirty.Notebook event
*/
Notebook.prototype.set_dirty = function (value) {
if (value === undefined) {
value = true;
}
if (this.dirty === value) {
return;
}
this.events.trigger('set_dirty.Notebook', {value: value});
};
/**
* Scroll the top of the page to a given cell.
*
* @param {integer} index - An index of the cell to view
* @param {integer} time - Animation time in milliseconds
* @return {integer} Pixel offset from the top of the container
*/
Notebook.prototype.scroll_to_cell = function (index, time) {
return this.scroll_cell_percent(index, 0, time);
};
/**
* Scroll the middle of the page to a given cell.
*
* @param {integer} index - An index of the cell to view
* @param {integer} percent - 0-100, the location on the screen to scroll.
* 0 is the top, 100 is the bottom.
* @param {integer} time - Animation time in milliseconds
* @return {integer} Pixel offset from the top of the container
*/
Notebook.prototype.scroll_cell_percent = function (index, percent, time) {
var cells = this.get_cells();
time = time || 0;
percent = percent || 0;
index = Math.min(cells.length-1,index);
index = Math.max(0 ,index);
var sme = this.scroll_manager.element;
var h = sme.height();
var st = sme.scrollTop();
var t = sme.offset().top;
var ct = cells[index].element.offset().top;
var scroll_value = st + ct - (t + 0.01 * percent * h);
this.scroll_manager.element.animate({scrollTop:scroll_value}, time);
return scroll_value;
};
/**
* Scroll to the bottom of the page.
*/
Notebook.prototype.scroll_to_bottom = function () {
this.scroll_manager.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0);
};
/**
* Scroll to the top of the page.
*/
Notebook.prototype.scroll_to_top = function () {
this.scroll_manager.element.animate({scrollTop:0}, 0);
};
// Edit Notebook metadata
/**
* Display a dialog that allows the user to edit the Notebook's metadata.
*/
Notebook.prototype.edit_metadata = function () {
var that = this;
dialog.edit_metadata({
md: this.metadata,
callback: function (md) {
that.metadata = md;
},
name: 'Notebook',
notebook: this,
keyboard_manager: this.keyboard_manager});
};
// Cell indexing, retrieval, etc.
/**
* Get all cell elements in the notebook.
*
* @return {jQuery} A selector of all cell elements
*/
Notebook.prototype.get_cell_elements = function () {
var container = this.container || $('#notebook-container')
return container.find(".cell").not('.cell .cell');
};
/**
* Get a particular cell element.
*
* @param {integer} index An index of a cell to select
* @return {jQuery} A selector of the given cell.
*/
Notebook.prototype.get_cell_element = function (index) {
var result = null;
var e = this.get_cell_elements().eq(index);
if (e.length !== 0) {
result = e;
}
return result;
};
/**
* Try to get a particular cell by msg_id.
*
* @param {string} msg_id A message UUID
* @return {Cell} Cell or null if no cell was found.
*/
Notebook.prototype.get_msg_cell = function (msg_id) {
return codecell.CodeCell.msg_cells[msg_id] || null;
};
/**
* Count the cells in this notebook.
*
* @return {integer} The number of cells in this notebook
*/
Notebook.prototype.ncells = function () {
return this.get_cell_elements().length;
};
/**
* Get all Cell objects in this notebook.
*
* @return {Array} This notebook's Cell objects
*/
Notebook.prototype.get_cells = function () {
// TODO: we are often calling cells as cells()[i], which we should optimize
// to cells(i) or a new method.
return this.get_cell_elements().toArray().map(function (e) {
return $(e).data("cell");
});
};
/**
* Get a Cell objects from this notebook.
*
* @param {integer} index - An index of a cell to retrieve
* @return {Cell} Cell or null if no cell was found.
*/
Notebook.prototype.get_cell = function (index) {
var result = null;
var ce = this.get_cell_element(index);
if (ce !== null) {
result = ce.data('cell');
}
return result;
};
/**
* Get the cell below a given cell.
*
* @param {Cell} cell
* @return {Cell} the next cell or null if no cell was found.
*/
Notebook.prototype.get_next_cell = function (cell) {
var result = null;
var index = this.find_cell_index(cell);
if (this.is_valid_cell_index(index+1)) {
result = this.get_cell(index+1);
}
return result;
};
/**
* Toggles the display of line numbers in all cells.
*/
Notebook.prototype.toggle_all_line_numbers = function () {
this.line_numbers = !this.line_numbers;
};
/**
* Get the cell above a given cell.
*
* @param {Cell} cell
* @return {Cell} The previous cell or null if no cell was found.
*/
Notebook.prototype.get_prev_cell = function (cell) {
var result = null;
var index = this.find_cell_index(cell);
if (index !== null && index > 0) {
result = this.get_cell(index-1);
}
return result;
};
/**
* Get the numeric index of a given cell.
*
* @param {Cell} cell
* @return {integer} The cell's numeric index or null if no cell was found.
*/
Notebook.prototype.find_cell_index = function (cell) {
var result = null;
this.get_cell_elements().filter(function (index) {
if ($(this).data("cell") === cell) {
result = index;
}
});
return result;
};
/**
* Return given index if defined, or the selected index if not.
*
* @param {integer} [index] - A cell's index
* @return {integer} cell index
*/
Notebook.prototype.index_or_selected = function (index) {
var i;
if (index === undefined || index === null) {
i = this.get_selected_index();
if (i === null) {
i = 0;
}
} else {
i = index;
}
return i;
};
Notebook.prototype.get_selected_cells = function () {
return this.get_cells().filter(function(cell, index){ return cell.selected || soft_selected(cell) || cell.anchor;});
};
Notebook.prototype.get_selected_cells_indices = function () {
var result = [];
this.get_cells().filter(function (cell, index) {
if (cell.selected || soft_selected(cell) || cell.anchor) {
result.push(index);
}
});
return result;
};
/**
* Get the currently selected cell.
*
* @return {Cell} The selected cell
*/
Notebook.prototype.get_selected_cell = function () {
var index = this.get_selected_index();
return this.get_cell(index);
};
/**
* Check whether a cell index is valid.
*
* @param {integer} index - A cell index
* @return True if the index is valid, false otherwise
*/
Notebook.prototype.is_valid_cell_index = function (index) {
if (index !== null && index >= 0 && index < this.ncells()) {
return true;
} else {
return false;
}
};
/**
* Returns the index of the cell that the selection is currently anchored on.
*
* @return {integer} Index of first cell selected in selection
*/
Notebook.prototype.get_anchor_index = function () {
var result = null;
this.get_cell_elements().filter(function (index) {
if ($(this).data("cell").anchor === true) {
result = index;
}
});
return result;
};
/**
* Get the index of the currently selected cell.
*
* @return {integer} The selected cell's numeric index
*/
Notebook.prototype.get_selected_index = function () {
var result = null;
this.get_cell_elements().filter(function (index) {
if ($(this).data("cell").selected === true) {
result = index;
}
});
return result;
};
// Cell selection.
Notebook.prototype.extend_selection_by = function(delta) {
var index = this.get_selected_index();
// do not move anchor
return this.select(index+delta, false);
};
Notebook.prototype.update_soft_selection = function(){
var i1 = this.get_selected_index();
var i2 = this.get_anchor_index();
var low = Math.min(i1, i2);
var high = Math.max(i1, i2);
this.get_cells().map(function(cell, index, all){
if( low <= index && index <= high && low !== high){
cell.element.addClass(_SOFT_SELECTION_CLASS);
} else {
cell.element.removeClass(_SOFT_SELECTION_CLASS);
}
});
};
Notebook.prototype._contract_selection = function(){
var i = this.get_selected_index();
this.select(i, true);
};
/**
* Programmatically select a cell.
*
* @param {integer} index - A cell's index
* @param {bool} moveanchor – whether to move the selection
* anchor, default to true.
* @return {Notebook} This notebook
*/
Notebook.prototype.select = function (index, moveanchor) {
moveanchor = (moveanchor===undefined)? true : moveanchor;
if (this.is_valid_cell_index(index)) {
var sindex = this.get_selected_index();
if (sindex !== null && index !== sindex) {
// If we are about to select a different cell, make sure we are
// first in command mode.
if (this.mode !== 'command') {
this.command_mode();
}
this.get_cell(sindex).unselect(moveanchor);
}
if(moveanchor){
this.get_cell(this.get_anchor_index()).unselect(moveanchor);
}
var cell = this.get_cell(index);
cell.select(moveanchor);
this.update_soft_selection();
if (cell.cell_type === 'heading') {
this.events.trigger('selected_cell_type_changed.Notebook',
{'cell_type':cell.cell_type, level:cell.level}
);
} else {
this.events.trigger('selected_cell_type_changed.Notebook',
{'cell_type':cell.cell_type}
);
}
}
return this;
};
/**
* Programmatically select the next cell.
*
* @param {bool} moveanchor – whether to move the selection
* anchor, default to true.
* @return {Notebook} This notebook
*/
Notebook.prototype.select_next = function (moveanchor) {
var index = this.get_selected_index();
this.select(index+1, moveanchor);
return this;
};
/**
* Programmatically select the previous cell.
*
* @return {Notebook} This notebook
*/
Notebook.prototype.select_prev = function (moveanchor) {
var index = this.get_selected_index();
this.select(index-1, moveanchor);
return this;
};
// Edit/Command mode
/**
* Gets the index of the cell that is in edit mode.
*
* @return {integer} index
*/
Notebook.prototype.get_edit_index = function () {
var result = null;
this.get_cell_elements().filter(function (index) {
if ($(this).data("cell").mode === 'edit') {
result = index;
}
});
return result;
};
/**
* Handle when a a cell blurs and the notebook should enter command mode.
*
* @param {Cell} [cell] - Cell to enter command mode on.
*/
Notebook.prototype.handle_command_mode = function (cell) {
if (this.mode !== 'command') {
cell.command_mode();
this.mode = 'command';
this.events.trigger('command_mode.Notebook');
this.keyboard_manager.command_mode();
}
};
/**
* Make the notebook enter command mode.
*/
Notebook.prototype.command_mode = function () {
var cell = this.get_cell(this.get_edit_index());
if (cell && this.mode !== 'command') {
// We don't call cell.command_mode, but rather blur the CM editor
// which will trigger the call to handle_command_mode.
cell.code_mirror.getInputField().blur();
}
};
/**
* Handle when a cell fires it's edit_mode event.
*
* @param {Cell} [cell] Cell to enter edit mode on.
*/
Notebook.prototype.handle_edit_mode = function (cell) {
this._contract_selection();
if (cell && this.mode !== 'edit') {
cell.edit_mode();
this.mode = 'edit';
this.events.trigger('edit_mode.Notebook');
this.keyboard_manager.edit_mode();
}
};
/**
* Make a cell enter edit mode.
*/
Notebook.prototype.edit_mode = function () {
this._contract_selection();
var cell = this.get_selected_cell();
if (cell && this.mode !== 'edit') {
cell.unrender();
cell.focus_editor();
}
};
/**
* Ensure either cell, or codemirror is focused. Is none
* is focused, focus the cell.
*/
Notebook.prototype.ensure_focused = function(){
var cell = this.get_selected_cell();
if (cell === null) {return;} // No cell is selected
cell.ensure_focused();
};
/**
* Focus the currently selected cell.
*/
Notebook.prototype.focus_cell = function () {
var cell = this.get_selected_cell();
if (cell === null) {return;} // No cell is selected
cell.focus_cell();
};
// Cell movement
/**
* Move the current selection up, keeping the same cells selected
* No op if the selection is at the beginning of the notebook
*/
Notebook.prototype.move_selection_up = function(){
// actually will move the cell before the selection, after the selection
var indices = this.get_selected_cells_indices();
var first = indices[0];
var last = indices[indices.length - 1];
var selected = this.get_selected_index();
var anchored = this.get_anchor_index();
if (first === 0){
return;
}
var tomove = this.get_cell_element(first - 1);
var pivot = this.get_cell_element(last);
tomove.detach();
pivot.after(tomove);
this.get_cell(selected-1).focus_cell();
this.select(anchored - 1);
this.select(selected - 1, false);
};
/**
* Move the current selection down, keeping the same cells selected.
* No op if the selection is at the end of the notebook
*/
Notebook.prototype.move_selection_down = function(){
// actually will move the cell after the selection, before the selection
var indices = this.get_selected_cells_indices();
var first = indices[0];
var last = indices[indices.length - 1];
var selected = this.get_selected_index();
var anchored = this.get_anchor_index();
if(!this.is_valid_cell_index(last + 1)){
return;
}
var tomove = this.get_cell_element(last + 1);
var pivot = this.get_cell_element(first);
tomove.detach();
pivot.before(tomove);
this.get_cell(selected+1).focus_cell();
this.select(first);
this.select(anchored + 1);
this.select(selected + 1, false);
};
/**
* Move given (or selected) cell up and select it.
*
* @param {integer} [index] - cell index
* @return {Notebook} This notebook
*/
Notebook.prototype.move_cell_up = function (index) {
console.warn('Notebook.move_cell_up is deprecated as of v4.1 and will be removed in v5.0');
if(index === undefined){
this.move_selection_up();
return this;
}
var i = this.index_or_selected(index);
if (this.is_valid_cell_index(i) && i > 0) {
var pivot = this.get_cell_element(i-1);
var tomove = this.get_cell_element(i);
if (pivot !== null && tomove !== null) {
tomove.detach();
pivot.before(tomove);
this.select(i-1);
var cell = this.get_selected_cell();
cell.focus_cell();
}
this.set_dirty(true);
}
return this;
};
/**
* Move given (or selected) cell down and select it.
*
* @param {integer} [index] - cell index
* @return {Notebook} This notebook
*/
Notebook.prototype.move_cell_down = function (index) {
console.warn('Notebook.move_cell_down is deprecated as of v4.1 and will be removed in v5.0');
if(index === undefined){
this.move_selection_down();
return this;
}
var i = this.index_or_selected(index);
if (this.is_valid_cell_index(i) && this.is_valid_cell_index(i+1)) {
var pivot = this.get_cell_element(i+1);
var tomove = this.get_cell_element(i);
if (pivot !== null && tomove !== null) {
tomove.detach();
pivot.after(tomove);
this.select(i+1);
var cell = this.get_selected_cell();
cell.focus_cell();
}
}
this.set_dirty();
return this;
};
// Insertion, deletion.
/**
* Delete a cell from the notebook without any precautions
* Needed to reload checkpoints and other things like that.
*
* @param {integer} [index] - cell's numeric index
* @return {Notebook} This notebook
*/
Notebook.prototype._unsafe_delete_cell = function (index) {
var i = this.index_or_selected(index);
var cell = this.get_cell(i);
$('#undelete_cell').addClass('disabled');
if (this.is_valid_cell_index(i)) {
var old_ncells = this.ncells();
var ce = this.get_cell_element(i);
ce.remove();
this.set_dirty(true);
}
return this;
};
/**
* Delete cells from the notebook
*
* @param {Array} [indices] - the numeric indices of cells to delete.
* @return {Notebook} This notebook
*/
Notebook.prototype.delete_cells = function(indices) {
if (indices === undefined) {
indices = this.get_selected_cells_indices();
}
var undelete_backup = {
cells: [],
below: false,
index: 0,
};
var cursor_ix_before = this.get_selected_index();
var deleting_before_cursor = 0;
for (var i=0; i < indices.length; i++) {
if (!this.get_cell(indices[i]).is_deletable()) {
// If any cell is marked undeletable, cancel
return this;
}
if (indices[i] < cursor_ix_before) {
deleting_before_cursor++;
}
}
// If we started deleting cells from the top, the later indices would
// get offset. We sort them into descending order to avoid that.
indices.sort(function(a, b) {return b-a;});
for (i=0; i < indices.length; i++) {
var cell = this.get_cell(indices[i]);
undelete_backup.cells.push(cell.toJSON());
this.get_cell_element(indices[i]).remove();
this.events.trigger('delete.Cell', {'cell': cell, 'index': indices[i]});
}
var new_ncells = this.ncells();
// Always make sure we have at least one cell.
if (new_ncells === 0) {
this.insert_cell_below('code');
new_ncells = 1;
}
var cursor_ix_after = this.get_selected_index();
if (cursor_ix_after === null) {
// Selected cell was deleted
cursor_ix_after = cursor_ix_before - deleting_before_cursor;
if (cursor_ix_after >= new_ncells) {
cursor_ix_after = new_ncells - 1;
undelete_backup.below = true;
}
this.select(cursor_ix_after);
}
// Check if the cells were after the cursor
for (i=0; i < indices.length; i++) {
if (indices[i] > cursor_ix_before) {
undelete_backup.below = true;
}
}
// This will put all the deleted cells back in one location, rather than
// where they came from. It will do until we have proper undo support.
undelete_backup.index = cursor_ix_after;
$('#undelete_cell').removeClass('disabled');
this.undelete_backup_stack.push(undelete_backup);
this.set_dirty(true);
return this;
};
/**
* Delete a cell from the notebook.
*
* @param {integer} [index] - cell's numeric index
* @return {Notebook} This notebook
*/
Notebook.prototype.delete_cell = function (index) {
if (index === undefined) {
return this.delete_cells();
} else {
return this.delete_cells([index]);
}
};
/**
* Restore the most recently deleted cells.
*/
Notebook.prototype.undelete_cell = function() {
if (this.undelete_backup_stack.length > 0) {
var undelete_backup = this.undelete_backup_stack.pop();
var i, cell_data, new_cell, insert;
if (undelete_backup.below) {
insert = $.proxy(this.insert_cell_below, this);
} else {
insert = $.proxy(this.insert_cell_above, this);
}
for (i=0; i < undelete_backup.cells.length; i++) {
cell_data = undelete_backup.cells[i];
new_cell = insert(cell_data.cell_type, undelete_backup.index);
new_cell.fromJSON(cell_data);
}
this.set_dirty(true);
}
if (this.undelete_backup_stack.length === 0) {
$('#undelete_cell').addClass('disabled');
}
};
/**
* Insert a cell so that after insertion the cell is at given index.
*
* If cell type is not provided, it will default to the type of the
* currently active cell.
*
* Similar to insert_above, but index parameter is mandatory.
*
* Index will be brought back into the accessible range [0,n].
*
* @param {string} [type] - in ['code','markdown', 'raw'], defaults to 'code'
* @param {integer} [index] - a valid index where to insert cell
* @return {Cell|null} created cell or null
*/
Notebook.prototype.insert_cell_at_index = function(type, index){
var ncells = this.ncells();
index = Math.min(index, ncells);
index = Math.max(index, 0);
var cell = null;
type = type || this.class_config.get_sync('default_cell_type');
if (type === 'above') {
if (index > 0) {
type = this.get_cell(index-1).cell_type;
} else {
type = 'code';
}
} else if (type === 'below') {
if (index < ncells) {
type = this.get_cell(index).cell_type;
} else {
type = 'code';
}
} else if (type === 'selected') {
type = this.get_selected_cell().cell_type;
}
if (ncells === 0 || this.is_valid_cell_index(index) || index === ncells) {
var cell_options = {
events: this.events,
config: this.config,
keyboard_manager: this.keyboard_manager,
notebook: this,
tooltip: this.tooltip
};
switch(type) {
case 'code':
cell = new codecell.CodeCell(this.kernel, cell_options);
cell.set_input_prompt();
break;
case 'markdown':
cell = new textcell.MarkdownCell(cell_options);
break;
case 'raw':
cell = new textcell.RawCell(cell_options);
break;
default:
console.log("Unrecognized cell type: ", type, cellmod);
cell = new cellmod.UnrecognizedCell(cell_options);
}
if(this._insert_element_at_index(cell.element,index)) {
cell.render();
this.events.trigger('create.Cell', {'cell': cell, 'index': index});
cell.refresh();
// We used to select the cell after we refresh it, but there
// are now cases were this method is called where select is
// not appropriate. The selection logic should be handled by the
// caller of the the top level insert_cell methods.
this.set_dirty(true);
}
}
return cell;
};
/**
* Insert an element at given cell index.
*
* @param {HTMLElement} element - a cell element
* @param {integer} [index] - a valid index where to inser cell
* @returns {boolean} success
*/
Notebook.prototype._insert_element_at_index = function(element, index){
if (element === undefined){
return false;
}
var ncells = this.ncells();
if (ncells === 0) {
// special case append if empty
this.container.append(element);
} else if ( ncells === index ) {
// special case append it the end, but not empty
this.get_cell_element(index-1).after(element);
} else if (this.is_valid_cell_index(index)) {
// otherwise always somewhere to append to
this.get_cell_element(index).before(element);
} else {
return false;
}
this.undelete_backup_stack.map(function (undelete_backup) {
if (index < undelete_backup.index) {
undelete_backup.index += 1;
}
});
this.set_dirty(true);
return true;
};
/**
* Insert a cell of given type above given index, or at top
* of notebook if index smaller than 0.
*
* @param {string} [type] - cell type
* @param {integer} [index] - defaults to the currently selected cell
* @return {Cell|null} handle to created cell or null
*/
Notebook.prototype.insert_cell_above = function (type, index) {
if (index === null || index === undefined) {
index = Math.min(this.get_selected_index(index), this.get_anchor_index());
}
return this.insert_cell_at_index(type, index);
};
/**
* Insert a cell of given type below given index, or at bottom
* of notebook if index greater than number of cells
*
* @param {string} [type] - cell type
* @param {integer} [index] - defaults to the currently selected cell
* @return {Cell|null} handle to created cell or null
*/
Notebook.prototype.insert_cell_below = function (type, index) {
if (index === null || index === undefined) {
index = Math.max(this.get_selected_index(index), this.get_anchor_index());
}
return this.insert_cell_at_index(type, index+1);
};
/**
* Insert cell at end of notebook
*
* @param {string} type - cell type
* @return {Cell|null} handle to created cell or null
*/
Notebook.prototype.insert_cell_at_bottom = function (type){
var len = this.ncells();
return this.insert_cell_below(type,len-1);
};
/**
* Turn one or more cells into code.
*
* @param {Array} indices - cell indices to convert
*/
Notebook.prototype.cells_to_code = function (indices) {
if (indices === undefined){
indices = this.get_selected_cells_indices();
}
for (var i=0; i <indices.length; i++){
this.to_code(indices[i]);
}
};
/**
* Turn a cell into a code cell.
*
* @param {integer} [index] - cell index
*/
Notebook.prototype.to_code = function (index) {
var i = this.index_or_selected(index);
if (this.is_valid_cell_index(i)) {
var source_cell = this.get_cell(i);
if (!(source_cell instanceof codecell.CodeCell)) {
var target_cell = this.insert_cell_below('code',i);
var text = source_cell.get_text();
if (text === source_cell.placeholder) {
text = '';
}
//metadata
target_cell.metadata = source_cell.metadata;
// attachments (we transfer them so they aren't lost if the
// cell is turned back into markdown)
target_cell.attachments = source_cell.attachments;
target_cell.set_text(text);
// make this value the starting point, so that we can only undo
// to this state, instead of a blank cell
target_cell.code_mirror.clearHistory();
source_cell.element.remove();
this.select(i);
var cursor = source_cell.code_mirror.getCursor();
target_cell.code_mirror.setCursor(cursor);
this.set_dirty(true);
}
}
};
/**
* Turn one or more cells into Markdown.
*
* @param {Array} indices - cell indices to convert
*/
Notebook.prototype.cells_to_markdown = function (indices) {
if (indices === undefined) {
indices = this.get_selected_cells_indices();
}
for(var i=0; i < indices.length; i++) {
this.to_markdown(indices[i]);
}
};
/**
* Turn a cell into a Markdown cell.
*
* @param {integer} [index] - cell index
*/
Notebook.prototype.to_markdown = function (index) {
var i = this.index_or_selected(index);
if (this.is_valid_cell_index(i)) {
var source_cell = this.get_cell(i);
if (!(source_cell instanceof textcell.MarkdownCell)) {
var target_cell = this.insert_cell_below('markdown',i);
var text = source_cell.get_text();
if (text === source_cell.placeholder) {
text = '';
}
// metadata
target_cell.metadata = source_cell.metadata;
target_cell.attachments = source_cell.attachments;
// We must show the editor before setting its contents
target_cell.unrender();
target_cell.set_text(text);
// make this value the starting point, so that we can only undo
// to this state, instead of a blank cell
target_cell.code_mirror.clearHistory();
source_cell.element.remove();
this.select(i);
if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
target_cell.render();
}
var cursor = source_cell.code_mirror.getCursor();
target_cell.code_mirror.setCursor(cursor);
this.set_dirty(true);
}
}
};
/**
* Turn one or more cells into a raw text cell.
*
* @param {Array} indices - cell indices to convert
*/
Notebook.prototype.cells_to_raw = function (indices) {
if (indices === undefined) {
indices = this.get_selected_cells_indices();
}
for(var i=0; i < indices.length; i++) {
this.to_raw(indices[i]);
}
};
/**
* Turn a cell into a raw text cell.
*
* @param {integer} [index] - cell index
*/
Notebook.prototype.to_raw = function (index) {
var i = this.index_or_selected(index);
if (this.is_valid_cell_index(i)) {
var target_cell = null;
var source_cell = this.get_cell(i);
if (!(source_cell instanceof textcell.RawCell)) {
target_cell = this.insert_cell_below('raw',i);
var text = source_cell.get_text();
if (text === source_cell.placeholder) {
text = '';
}
//metadata
target_cell.metadata = source_cell.metadata;
// attachments (we transfer them so they aren't lost if the
// cell is turned back into markdown)
target_cell.attachments = source_cell.attachments;
// We must show the editor before setting its contents
target_cell.unrender();
target_cell.set_text(text);
// make this value the starting point, so that we can only undo
// to this state, instead of a blank cell
target_cell.code_mirror.clearHistory();
source_cell.element.remove();
this.select(i);
var cursor = source_cell.code_mirror.getCursor();
target_cell.code_mirror.setCursor(cursor);
this.set_dirty(true);
}
}
};
/**
* Warn about heading cell support removal.
*/
Notebook.prototype._warn_heading = function () {
dialog.modal({
notebook: this,
keyboard_manager: this.keyboard_manager,
title : i18n.msg._("Use markdown headings"),
body : $("<p/>").text(
i18n.msg._('Jupyter no longer uses special heading cells. ' +
'Instead, write your headings in Markdown cells using # characters:')
).append($('<pre/>').text(
i18n.msg._('## This is a level 2 heading')
)),
buttons : {
"OK" : {}
}
});
};
/**
* Turn a cell into a heading containing markdown cell.
*
* @param {integer} [index] - cell index
* @param {integer} [level] - heading level (e.g., 1 for h1)
*/
Notebook.prototype.to_heading = function (index, level) {
this.to_markdown(index);
level = level || 1;
var i = this.index_or_selected(index);
if (this.is_valid_cell_index(i)) {
var cell = this.get_cell(i);
cell.set_heading_level(level);
this.set_dirty(true);
}
};
// Cut/Copy/Paste
/**
* Enable the UI elements for pasting cells.
*/
Notebook.prototype.enable_paste = function () {
var that = this;
if (!this.paste_enabled) {
$('#paste_cell_replace').removeClass('disabled')
.on('click', function () {that.keyboard_manager.actions.call(
'jupyter-notebook:paste-cell-replace');});
$('#paste_cell_above').removeClass('disabled')
.on('click', function () {that.keyboard_manager.actions.call(
'jupyter-notebook:paste-cell-above');});
$('#paste_cell_below').removeClass('disabled')
.on('click', function () {that.keyboard_manager.actions.call(
'jupyter-notebook:paste-cell-below');});
this.paste_enabled = true;
}
};
/**
* Disable the UI elements for pasting cells.
*/
Notebook.prototype.disable_paste = function () {
if (this.paste_enabled) {
$('#paste_cell_replace').addClass('disabled').off('click');
$('#paste_cell_above').addClass('disabled').off('click');
$('#paste_cell_below').addClass('disabled').off('click');
this.paste_enabled = false;
}
};
/**
* Cut a cell.
*/
Notebook.prototype.cut_cell = function () {
this.copy_cell();
this.delete_cell();
};
/**
* Copy cells.
*/
Notebook.prototype.copy_cell = function () {
var cells = this.get_selected_cells();
if (cells.length === 0) {
cells = [this.get_selected_cell()];
}
this.clipboard = [];
var cell_json;
for (var i=0; i < cells.length; i++) {
cell_json = cells[i].toJSON();
if (cell_json.metadata.deletable !== undefined) {
delete cell_json.metadata.deletable;
}
this.clipboard.push(cell_json);
}
this.enable_paste();
};
/**
* Replace the selected cell with the cells in the clipboard.
*/
Notebook.prototype.paste_cell_replace = function () {
if (!(this.clipboard !== null && this.paste_enabled)) {
return;
}
var selected = this.get_selected_cells_indices();
var insertion_index = selected[0];
this.delete_cells(selected);
for (var i=this.clipboard.length-1; i >= 0; i--) {
var cell_data = this.clipboard[i];
var new_cell = this.insert_cell_at_index(cell_data.cell_type, insertion_index);
new_cell.fromJSON(cell_data);
}
this.select(insertion_index+this.clipboard.length-1);
};
/**
* Paste cells from the clipboard above the selected cell.
*/
Notebook.prototype.paste_cell_above = function () {
if (this.clipboard !== null && this.paste_enabled) {
var first_inserted = null;
for (var i=0; i < this.clipboard.length; i++) {
var cell_data = this.clipboard[i];
var new_cell = this.insert_cell_above(cell_data.cell_type);
new_cell.fromJSON(cell_data);
if (first_inserted === null) {
first_inserted = new_cell;
}
}
first_inserted.focus_cell();
}
};
/**
* Paste cells from the clipboard below the selected cell.
*/
Notebook.prototype.paste_cell_below = function () {
if (this.clipboard !== null && this.paste_enabled) {
var first_inserted = null;
for (var i = this.clipboard.length-1; i >= 0; i--) {
var cell_data = this.clipboard[i];
var new_cell = this.insert_cell_below(cell_data.cell_type);
new_cell.fromJSON(cell_data);
if (first_inserted === null) {
first_inserted = new_cell;
}
}
first_inserted.focus_cell();
}
};
/**
* Re-render the output of a CodeCell.
*/
Notebook.prototype.render_cell_output = function (code_cell) {
var cell_data = code_cell.toJSON();
var cell_index = this.find_cell_index(code_cell);
var trusted = code_cell.output_area.trusted;
this.clear_output(cell_index);
code_cell.output_area.trusted = trusted;
code_cell.fromJSON(cell_data);
};
// Split/merge
/**
* Split the selected cell into two cells.
*/
Notebook.prototype.split_cell = function () {
var cell = this.get_selected_cell();
if (cell.is_splittable()) {
var texta = cell.get_pre_cursor();
var textb = cell.get_post_cursor();
// current cell becomes the second one
// so we don't need to worry about selection
cell.set_text(textb);
// create new cell with same type
var new_cell = this.insert_cell_above(cell.cell_type);
// Unrender the new cell so we can call set_text.
new_cell.unrender();
new_cell.set_text(texta);
// duplicate metadata
new_cell.metadata = JSON.parse(JSON.stringify(cell.metadata));
}
};
/**
* Merge a series of cells into one
*
* @param {Array} indices - the numeric indices of the cells to be merged
* @param {bool} into_last - merge into the last cell instead of the first
*/
Notebook.prototype.merge_cells = function(indices, into_last) {
if (indices.length <= 1) {
return;
}
// Check if trying to merge above on topmost cell or wrap around
// when merging above, see #330
if (indices.filter(function(item) {return item < 0;}).length > 0) {
return;
}
for (var i=0; i < indices.length; i++) {
if (!this.get_cell(indices[i]).is_mergeable()) {
return;
}
}
var target = this.get_cell(into_last ? indices.pop() : indices.shift());
// Get all the cells' contents
var contents = [];
for (i=0; i < indices.length; i++) {
contents.push(this.get_cell(indices[i]).get_text());
}
if (into_last) {
contents.push(target.get_text());
} else {
contents.unshift(target.get_text());
}
// Update the contents of the target cell
if (target instanceof codecell.CodeCell) {
target.set_text(contents.join('\n\n'));
} else {
var was_rendered = target.rendered;
target.unrender(); // Must unrender before we set_text.
target.set_text(contents.join('\n\n'));
if (was_rendered) {
// The rendered state of the final cell should match
// that of the original selected cell;
target.render();
}
}
// Delete the other cells
this.delete_cells(indices);
// Reset the target cell's undo history
target.code_mirror.clearHistory();
this.select(this.find_cell_index(target));
};
/**
* Merge the selected range of cells
*/
Notebook.prototype.merge_selected_cells = function() {
this.merge_cells(this.get_selected_cells_indices());
};
/**
* Merge the selected cell into the cell above it.
*/
Notebook.prototype.merge_cell_above = function () {
var index = this.get_selected_index();
this.merge_cells([index-1, index], true);
};
/**
* Merge the selected cell into the cell below it.
*/
Notebook.prototype.merge_cell_below = function () {
var index = this.get_selected_index();
this.merge_cells([index, index+1], false);
};
// Attachments handling
/**
* Shows a dialog letting the user pick an image from her computer and
* insert it into the edited markdown cell
*/
Notebook.prototype.insert_image = function () {
var that = this;
var cell = this.get_selected_cell();
// The following should not happen as the menu item is greyed out
// when those conditions are not fullfilled (see MarkdownCell
// unselect/select/unrender handlers)
if (cell.cell_type != 'markdown') {
console.log('Error: insert_image called on non-markdown cell');
return;
}
if (cell.rendered) {
console.log('Error: insert_image called on rendered cell');
return;
}
dialog.insert_image({
callback: function(file) {
cell.edit_mode();
cell.insert_inline_image_from_blob(file);
},
notebook: this,
keyboard_manager: this.keyboard_manager
});
};
/**
* Cut the attachments of a cell
*/
Notebook.prototype.cut_cell_attachments = function() {
var cell = this.get_selected_cell();
if (cell.attachments !== undefined) {
this.clipboard_attachments = cell.attachments;
this.enable_attachments_paste();
delete cell.attachments;
cell.unrender();
cell.render();
}
};
/**
* Copy the attachments of a cell
*/
Notebook.prototype.copy_cell_attachments = function() {
var cell = this.get_selected_cell();
if (cell.attachments !== undefined) {
// Do a deep copy of attachments to avoid subsequent modification
// to the cell to modify the clipboard
this.clipboard_attachments = $.extend(true, {}, cell.attachments);
this.enable_attachments_paste();
}
};
/**
* Paste the attachments in the clipboard into the currently selected
* cell
*/
Notebook.prototype.paste_cell_attachments = function() {
if (this.clipboard_attachments !== null &&
this.paste_attachments_enabled) {
var cell = this.get_selected_cell();
if (cell.attachments === undefined) {
cell.attachments = {};
}
// Do a deep copy so we can paste multiple times
$.extend(true, cell.attachments, this.clipboard_attachments);
cell.unrender();
cell.render();
}
};
/**
* Disable the "Paste Cell Attachments" menu item
*/
Notebook.prototype.disable_attachments_paste = function () {
if (this.paste_attachments_enabled) {
$('#paste_cell_attachments').addClass('disabled');
this.paste_attachments_enabled = false;
}
};
/**
* Enable the "Paste Cell Attachments" menu item
*/
Notebook.prototype.enable_attachments_paste = function () {
var that = this;
if (!this.paste_attachments_enabled) {
$('#paste_cell_attachments').removeClass('disabled');
this.paste_attachments_enabled = true;
}
};
/**
* Enable/disable the "Insert image" menu item
*/
Notebook.prototype.set_insert_image_enabled = function(enabled) {
if (enabled) {
$('#insert_image').removeClass('disabled');
} else {
$('#insert_image').addClass('disabled');
}
};
// Cell collapsing and output clearing
/**
* Hide a cell's output.
*
* @param {integer} index - cell index
*/
Notebook.prototype.collapse_output = function (index) {
var i = this.index_or_selected(index);
var cell = this.get_cell(i);
if (cell !== null && (cell instanceof codecell.CodeCell)) {
cell.collapse_output();
this.set_dirty(true);
}
};
/**
* Hide each code cell's output area.
*/
Notebook.prototype.collapse_all_output = function () {
this.get_cells().map(function (cell, i) {
if (cell instanceof codecell.CodeCell) {
cell.collapse_output();
}
});
// this should not be set if the `collapse` key is removed from nbformat
this.set_dirty(true);
};
/**
* Show a cell's output.
*
* @param {integer} index - cell index
*/
Notebook.prototype.expand_output = function (index) {
var i = this.index_or_selected(index);
var cell = this.get_cell(i);
if (cell !== null && (cell instanceof codecell.CodeCell)) {
cell.expand_output();
this.set_dirty(true);
}
};
/**
* Expand each code cell's output area, and remove scrollbars.
*/
Notebook.prototype.expand_all_output = function () {
this.get_cells().map(function (cell, i) {
if (cell instanceof codecell.CodeCell) {
cell.expand_output();
}
});
// this should not be set if the `collapse` key is removed from nbformat
this.set_dirty(true);
};
/**
* Clear the selected CodeCell's output area.
*
* @param {integer} index - cell index
*/
Notebook.prototype.clear_output = function (index) {
var i = this.index_or_selected(index);
var cell = this.get_cell(i);
if (cell !== null && (cell instanceof codecell.CodeCell)) {
cell.clear_output();
this.set_dirty(true);
}
};
/**
* Clear multiple selected CodeCells' output areas.
*
*/
Notebook.prototype.clear_cells_outputs = function(indices) {
if (!indices) {
indices = this.get_selected_cells_indices();
}
for (var i = 0; i < indices.length; i++){
this.clear_output(indices[i]);
}
};
/**
* Clear each code cell's output area.
*/
Notebook.prototype.clear_all_output = function () {
this.get_cells().map(function (cell, i) {
if (cell instanceof codecell.CodeCell) {
cell.clear_output();
}
});
this.set_dirty(true);
};
/**
* Scroll the selected CodeCell's output area.
*
* @param {integer} index - cell index
*/
Notebook.prototype.scroll_output = function (index) {
var i = this.index_or_selected(index);
var cell = this.get_cell(i);
if (cell !== null && (cell instanceof codecell.CodeCell)) {
cell.scroll_output();
this.set_dirty(true);
}
};
/**
* Expand each code cell's output area and add a scrollbar for long output.
*/
Notebook.prototype.scroll_all_output = function () {
this.get_cells().map(function (cell, i) {
if (cell instanceof codecell.CodeCell) {
cell.scroll_output();
}
});
// this should not be set if the `collapse` key is removed from nbformat
this.set_dirty(true);
};
/**
* Toggle whether a cell's output is collapsed or expanded.
*
* @param {integer} index - cell index
*/
Notebook.prototype.toggle_output = function (index) {
var i = this.index_or_selected(index);
var cell = this.get_cell(i);
if (cell !== null && (cell instanceof codecell.CodeCell)) {
cell.toggle_output();
this.set_dirty(true);
}
};
/**
* Toggle whether all selected cells' outputs are collapsed or expanded.
*
* @param {integer} indices - the indices of the cells to toggle
*/
Notebook.prototype.toggle_cells_outputs = function(indices) {
if (!indices) {
indices = this.get_selected_cells_indices();
}
for (var i = 0; i < indices.length; i++){
this.toggle_output(indices[i]);
}
};
/**
* Toggle the output of all cells.
*/
Notebook.prototype.toggle_all_output = function () {
this.get_cells().map(function (cell, i) {
if (cell instanceof codecell.CodeCell) {
cell.toggle_output();
}
});
// this should not be set if the `collapse` key is removed from nbformat
this.set_dirty(true);
};
/**
* Toggle a scrollbar for long cell outputs.
*
* @param {integer} index - cell index
*/
Notebook.prototype.toggle_output_scroll = function (index) {
var i = this.index_or_selected(index);
var cell = this.get_cell(i);
if (cell !== null && (cell instanceof codecell.CodeCell)) {
cell.toggle_output_scroll();
this.set_dirty(true);
}
};
/**
* Toggle a scrollbar for selected long cells' outputs.
*
* @param {integer} indices - the indices of the cells to toggle
*/
Notebook.prototype.toggle_cells_outputs_scroll = function(indices) {
if (!indices) {
indices = this.get_selected_cells_indices();
}
for (var i = 0; i < indices.length; i++){
this.toggle_output_scroll(indices[i]);
}
};
/**
* Toggle the scrolling of long output on all cells.
*/
Notebook.prototype.toggle_all_output_scroll = function () {
this.get_cells().map(function (cell, i) {
if (cell instanceof codecell.CodeCell) {
cell.toggle_output_scroll();
}
});
// this should not be set if the `collapse` key is removed from nbformat
this.set_dirty(true);
};
// Other cell functions: line numbers, ...
/**
* Toggle line numbers in the selected cell's input area.
*/
Notebook.prototype.cell_toggle_line_numbers = function() {
this.get_selected_cells().map(function(cell, i){cell.toggle_line_numbers();});
};
//dispatch codemirror mode to all cells.
Notebook.prototype._dispatch_mode = function(spec, newmode){
this.codemirror_mode = newmode;
codecell.CodeCell.options_default.cm_config.mode = newmode;
this.get_cells().map(function(cell, i) {
if (cell.cell_type === 'code'){
cell.code_mirror.setOption('mode', spec);
// This is currently redundant, because cm_config ends up as
// codemirror's own .options object, but I don't want to
// rely on that.
cell._options.cm_config.mode = spec;
}
});
};
// roughly try to check mode equality
var _mode_equal = function(mode1, mode2){
return ((mode1||{}).name||mode1)===((mode2||{}).name||mode2);
};
/**
* Set the codemirror mode for all code cells, including the default for
* new code cells.
* Set the mode to 'null' (no highlighting) if it can't be found.
*/
Notebook.prototype.set_codemirror_mode = function(newmode){
// if mode is the same don't reset,
// to avoid n-time re-highlighting.
if (_mode_equal(newmode, this.codemirror_mode)) {
return;
}
var that = this;
utils.requireCodeMirrorMode(newmode, function (spec) {
that._dispatch_mode(spec, newmode);
}, function(){
// on error don't dispatch the new mode as re-setting it later will not work.
// don't either set to null mode if it has been changed in the meantime
if( _mode_equal(newmode, this.codemirror_mode) ){
that._dispatch_mode('null','null');
}
});
};
// Session related things
/**
* Start a new session and set it on each code cell.
*/
Notebook.prototype.start_session = function (kernel_name) {
if (this._session_starting) {
throw new session.SessionAlreadyStarting();
}
this._session_starting = true;
var options = {
base_url: this.base_url,
ws_url: this.ws_url,
notebook_path: this.notebook_path,
notebook_name: this.notebook_name,
kernel_name: kernel_name,
notebook: this
};
var success = $.proxy(this._session_started, this);
var failure = $.proxy(this._session_start_failed, this);
if (this.session && this.session.kernel) {
this.session.restart(options, success, failure);
} else {
this.session = new session.Session(options);
this.session.start(success, failure);
}
};
/**
* Once a session is started, link the code cells to the kernel and pass the
* comm manager to the widget manager.
*/
Notebook.prototype._session_started = function (){
this._session_starting = false;
this.kernel = this.session.kernel;
var ncells = this.ncells();
for (var i=0; i<ncells; i++) {
var cell = this.get_cell(i);
if (cell instanceof codecell.CodeCell) {
cell.set_kernel(this.session.kernel);
}
}
};
/**
* Called when the session fails to start.
*/
Notebook.prototype._session_start_failed = function(jqxhr, status, error){
this._session_starting = false;
utils.log_ajax_error(jqxhr, status, error);
};
/**
* Prompt the user to restart the kernel and re-run everything.
* if options.confirm === false, no confirmation dialog is shown.
*/
Notebook.prototype.restart_run_all = function (options) {
var that = this;
var restart_options = {};
restart_options.confirm = (options || {}).confirm;
restart_options.dialog = {
notebook: that,
keyboard_manager: that.keyboard_manager,
title : i18n.msg._("Restart kernel and re-run the whole notebook?"),
body : $("<p/>").text(
i18n.msg._('Are you sure you want to restart the current kernel and re-execute the whole notebook? All variables and outputs will be lost.')
),
buttons : {
"Restart and Run All Cells" : {
"class" : "btn-danger",
"click" : function () {
that.execute_all_cells();
},
},
}
};
return this._restart_kernel(restart_options);
};
/**
* Prompt the user to restart the kernel and clear output.
* if options.confirm === false, no confirmation dialog is shown.
*/
Notebook.prototype.restart_clear_output = function (options) {
var that = this;
var restart_options = {};
restart_options.confirm = (options || {}).confirm;
restart_options.dialog = {
notebook: that,
keyboard_manager: that.keyboard_manager,
title : i18n.msg._("Restart kernel and clear all output?"),
body : $("<p/>").text(
i18n.msg._('Do you want to restart the current kernel and clear all output? All variables and outputs will be lost.')
),
buttons : {
"Restart and Clear All Outputs" : {
"class" : "btn-danger",
"click" : function (){
that.clear_all_output();
},
},
}
};
return this._restart_kernel(restart_options);
};
/**
* Prompt the user to restart the kernel.
* if options.confirm === false, no confirmation dialog is shown.
*/
Notebook.prototype.shutdown_kernel = function (options) {
var that = this;
var shutdown_options = {};
shutdown_options.confirm = (options || {}).confirm;
shutdown_options.dialog = {
title : "Shutdown kernel?",
body : $("<p/>").text(
'Do you want to shutdown the current kernel? All variables will be lost.'
),
buttons : {
"Shutdown" : {
"class" : "btn-danger",
"click" : function () {},
},
}
};
shutdown_options.kernel_action = function() {
that.session.delete();
};
return this._restart_kernel(shutdown_options);
};
Notebook.prototype.restart_kernel = function (options) {
var that = this;
var restart_options = {};
restart_options.confirm = (options || {}).confirm;
restart_options.dialog = {
title : i18n.msg._("Restart kernel?"),
body : $("<p/>").text(
i18n.msg._('Do you want to restart the current kernel? All variables will be lost.')
),
buttons : {
"Restart" : {
"class" : "btn-danger",
"click" : function () {},
},
}
};
return this._restart_kernel(restart_options);
};
// inner implementation of restart dialog & promise
Notebook.prototype._restart_kernel = function (options) {
var that = this;
options = options || {};
var resolve_promise, reject_promise;
var promise = new Promise(function (resolve, reject){
resolve_promise = resolve;
reject_promise = reject;
});
function restart_and_resolve () {
that.kernel.restart(function () {
// resolve when the kernel is *ready* not just started
that.events.one('kernel_ready.Kernel', resolve_promise);
}, reject_promise);
}
var do_kernel_action = options.kernel_action || restart_and_resolve;
// no need to confirm if the kernel is not connected
if (options.confirm === false || !that.kernel.is_connected()) {
var default_button = options.dialog.buttons[Object.keys(options.dialog.buttons)[0]];
promise.then(default_button.click);
do_kernel_action();
return promise;
}
options.dialog.notebook = this;
options.dialog.keyboard_manager = this.keyboard_manager;
// add 'Continue running' cancel button
var buttons = {
"Continue Running": {},
};
// hook up button.click actions after restart promise resolves
Object.keys(options.dialog.buttons).map(function (key) {
var button = buttons[key] = options.dialog.buttons[key];
var click = button.click;
button.click = function () {
promise.then(click);
do_kernel_action();
};
});
options.dialog.buttons = buttons;
dialog.modal(options.dialog);
return promise;
};
/**
* Execute cells corresponding to the given indices.
*
* @param {list} indices - indices of the cells to execute
*/
Notebook.prototype.execute_cells = function (indices) {
if (indices.length === 0) {
return;
}
var cell;
for (var i = 0; i < indices.length; i++) {
cell = this.get_cell(indices[i]);
cell.execute();
}
this.select(indices[indices.length - 1]);
this.command_mode();
this.set_dirty(true);
};
/**
* Execute or render cell outputs and go into command mode.
*/
Notebook.prototype.execute_selected_cells = function () {
this.execute_cells(this.get_selected_cells_indices());
};
/**
* Alias for execute_selected_cells, for backwards compatibility --
* previously, doing "Run Cell" would only ever run a single cell (hence
* `execute_cell`), but now it runs all marked cells, so that's the
* preferable function to use. But it is good to keep this function to avoid
* breaking existing extensions, etc.
*/
Notebook.prototype.execute_cell = function () {
this.execute_selected_cells();
};
/**
* Execute or render cell outputs and insert a new cell below.
*/
Notebook.prototype.execute_cell_and_insert_below = function () {
var indices = this.get_selected_cells_indices();
var cell_index;
if (indices.length > 1) {
this.execute_cells(indices);
cell_index = Math.max.apply(Math, indices);
} else {
var cell = this.get_selected_cell();
cell_index = this.find_cell_index(cell);
cell.execute();
}
// If we are at the end always insert a new cell and return
if (cell_index === (this.ncells()-1)) {
this.command_mode();
this.insert_cell_below();
this.select(cell_index+1);
this.edit_mode();
this.scroll_to_bottom();
this.set_dirty(true);
return;
}
this.command_mode();
this.insert_cell_below();
this.select(cell_index+1);
this.edit_mode();
this.set_dirty(true);
};
/**
* Execute or render cell outputs and select the next cell.
*/
Notebook.prototype.execute_cell_and_select_below = function () {
var indices = this.get_selected_cells_indices();
var cell_index;
if (indices.length > 1) {
this.execute_cells(indices);
cell_index = Math.max.apply(Math, indices);
} else {
var cell = this.get_selected_cell();
cell_index = this.find_cell_index(cell);
cell.execute();
}
// If we are at the end always insert a new cell and return
if (cell_index === (this.ncells()-1)) {
this.command_mode();
this.insert_cell_below();
this.select(cell_index+1);
this.edit_mode();
this.scroll_to_bottom();
this.set_dirty(true);
return;
}
this.command_mode();
this.select(cell_index+1);
this.focus_cell();
this.set_dirty(true);
};
/**
* Execute all cells below the selected cell.
*/
Notebook.prototype.execute_cells_below = function () {
this.execute_cell_range(this.get_selected_index(), this.ncells());
this.scroll_to_bottom();
};
/**
* Execute all cells above the selected cell.
*/
Notebook.prototype.execute_cells_above = function () {
this.execute_cell_range(0, this.get_selected_index());
};
/**
* Execute all cells.
*/
Notebook.prototype.execute_all_cells = function () {
this.execute_cell_range(0, this.ncells());
this.scroll_to_bottom();
};
/**
* Execute a contiguous range of cells.
*
* @param {integer} start - index of the first cell to execute (inclusive)
* @param {integer} end - index of the last cell to execute (exclusive)
*/
Notebook.prototype.execute_cell_range = function (start, end) {
this.command_mode();
var indices = [];
for (var i=start; i<end; i++) {
indices.push(i);
}
this.execute_cells(indices);
};
// Persistance and loading
/**
* Getter method for this notebook's name.
*
* @return {string} This notebook's name (excluding file extension)
*/
Notebook.prototype.get_notebook_name = function () {
var nbname = utils.splitext(this.notebook_name)[0];
return nbname;
};
/**
* Setter method for this notebook's name.
*
* @param {string} name
*/
Notebook.prototype.set_notebook_name = function (name) {
var parent = utils.url_path_split(this.notebook_path)[0];
this.notebook_name = name;
this.notebook_path = utils.url_path_join(parent, name);
};
/**
* Check that a notebook's name is valid.
*
* @param {string} nbname - A name for this notebook
* @return {boolean} True if the name is valid, false if invalid
*/
Notebook.prototype.test_notebook_name = function (nbname) {
nbname = nbname || '';
if (nbname.length>0 && !this.notebook_name_blacklist_re.test(nbname)) {
return true;
} else {
return false;
}
};
/**
Move the unused attachments garbage collection logic to TextCell.toJSON.
* Load a notebook from JSON (.ipynb).
*
* @param {object} data - JSON representation of a notebook
*/
Notebook.prototype.fromJSON = function (data) {
var content = data.content;
var ncells = this.ncells();
var i;
for (i=0; i<ncells; i++) {
// Always delete cell 0 as they get renumbered as they are deleted.
this._unsafe_delete_cell(0);
}
// Save the metadata and name.
this.metadata = content.metadata;
this.notebook_name = data.name;
this.notebook_path = data.path;
var trusted = true;
// Set the codemirror mode from language_info metadata
if (this.metadata.language_info !== undefined) {
var langinfo = this.metadata.language_info;
// Mode 'null' should be plain, unhighlighted text.
var cm_mode = langinfo.codemirror_mode || langinfo.name || 'null';
this.set_codemirror_mode(cm_mode);
}
var new_cells = content.cells;
ncells = new_cells.length;
var cell_data = null;
var new_cell = null;
for (i=0; i<ncells; i++) {
cell_data = new_cells[i];
new_cell = this.insert_cell_at_index(cell_data.cell_type, i);
new_cell.fromJSON(cell_data);
if (new_cell.cell_type === 'code' && !new_cell.output_area.trusted) {
trusted = false;
}
}
if (trusted !== this.trusted) {
this.trusted = trusted;
this.events.trigger("trust_changed.Notebook", trusted);
}
};
/**
* Dump this notebook into a JSON-friendly object.
*
* @return {object} A JSON-friendly representation of this notebook.
*/
Notebook.prototype.toJSON = function () {
// remove the conversion indicator, which only belongs in-memory
delete this.metadata.orig_nbformat;
delete this.metadata.orig_nbformat_minor;
var cells = this.get_cells();
var ncells = cells.length;
var cell_array = new Array(ncells);
var trusted = true;
for (var i=0; i<ncells; i++) {
var cell = cells[i];
if (cell.cell_type === 'code' && !cell.output_area.trusted) {
trusted = false;
}
cell_array[i] = cell.toJSON(true);
}
var data = {
cells: cell_array,
metadata: this.metadata,
nbformat: this.nbformat,
nbformat_minor: this.nbformat_minor
};
if (trusted !== this.trusted) {
this.trusted = trusted;
this.events.trigger("trust_changed.Notebook", trusted);
}
return data;
};
/**
* Start an autosave timer which periodically saves the notebook.
*
* @param {integer} interval - the autosave interval in milliseconds
*/
Notebook.prototype.set_autosave_interval = function (interval) {
var that = this;
// clear previous interval, so we don't get simultaneous timers
if (this.autosave_timer) {
clearInterval(this.autosave_timer);
}
if (!this.writable) {
// disable autosave if not writable
interval = 0;
}
this.autosave_interval = this.minimum_autosave_interval = interval;
if (interval) {
this.autosave_timer = setInterval(function() {
if (that.dirty) {
that.save_notebook();
}
}, interval);
this.events.trigger("autosave_enabled.Notebook", interval);
} else {
this.autosave_timer = null;
this.events.trigger("autosave_disabled.Notebook");
}
};
/**
* Save this notebook on the server. This becomes a notebook instance's
* .save_notebook method *after* the entire notebook has been loaded.
*
*/
Notebook.prototype.save_notebook = function (check_last_modified) {
if (check_last_modified === undefined) {
check_last_modified = true;
}
var error;
if (!this._fully_loaded) {
error = new Error("Load failed, save is disabled");
this.events.trigger('notebook_save_failed.Notebook', error);
return Promise.reject(error);
} else if (!this.writable) {
error = new Error("Notebook is read-only");
this.events.trigger('notebook_save_failed.Notebook', error);
return Promise.reject(error);
}
// Trigger an event before save, which allows listeners to modify
// the notebook as needed.
this.events.trigger('before_save.Notebook');
// Create a JSON model to be sent to the server.
var model = {
type : "notebook",
content : this.toJSON()
};
// time the ajax call for autosave tuning purposes.
var start = new Date().getTime();
var that = this;
var _save = function () {
return that.contents.save(that.notebook_path, model).then(
$.proxy(that.save_notebook_success, that, start),
function (error) {
that.events.trigger('notebook_save_failed.Notebook', error);
}
);
};
if (check_last_modified) {
return this.contents.get(this.notebook_path, {content: false}).then(
function (data) {
var last_modified = new Date(data.last_modified);
// We want to check last_modified (disk) > that.last_modified (our last save)
// In some cases the filesystem reports an inconsistent time,
// so we allow 0.5 seconds difference before complaining.
if ((last_modified.getTime() - that.last_modified.getTime()) > 500) { // 500 ms
console.warn("Last saving was done on `"+that.last_modified+"`("+that._last_modified+"), "+
"while the current file seem to have been saved on `"+data.last_modified+"`");
if (that._changed_on_disk_dialog !== null) {
// update save callback on the confirmation button
that._changed_on_disk_dialog.find('.save-confirm-btn').click(_save);
// redisplay existing dialog
that._changed_on_disk_dialog.modal('show');
} else {
// create new dialog
that._changed_on_disk_dialog = dialog.modal({
notebook: that,
keyboard_manager: that.keyboard_manager,
title: i18n.msg._("Notebook changed"),
body: i18n.msg._("The notebook file has changed on disk since the last time we opened or saved it. "
+ "Do you want to overwrite the file on disk with the version open here, or load "
+ "the version on disk (reload the page)?"),
buttons: {
Reload: {
class: 'btn-warning',
click: function() {
window.location.reload();
}
},
Cancel: {},
Overwrite: {
class: 'btn-danger save-confirm-btn',
click: function () {
_save();
}
},
}
});
}
} else {
return _save();
}
}, function (error) {
// maybe it has been deleted or renamed? Go ahead and save.
return _save();
}
);
} else {
return _save();
}
};
/**
* Success callback for saving a notebook.
*
* @param {integer} start - Time when the save request start
* @param {object} data - JSON representation of a notebook
*/
Notebook.prototype.save_notebook_success = function (start, data) {
this.set_dirty(false);
this.last_modified = new Date(data.last_modified);
// debug 484
this._last_modified = 'save-success:'+data.last_modified;
if (data.message) {
// save succeeded, but validation failed.
var body = $("<div>");
var title = i18n.msg._("Notebook validation failed");
body.append($("<p>").text(
i18n.msg._("The save operation succeeded," +
" but the notebook does not appear to be valid." +
" The validation error was:")
)).append($("<div>").addClass("validation-error").append(
$("<pre>").text(data.message)
));
dialog.modal({
notebook: this,
keyboard_manager: this.keyboard_manager,
title: title,
body: body,
buttons : {
OK : {
"class" : "btn-primary"
}
}
});
}
this.events.trigger('notebook_saved.Notebook');
this._update_autosave_interval(start);
if (this._checkpoint_after_save) {
this.create_checkpoint();
this._checkpoint_after_save = false;
}
};
/**
* Update the autosave interval based on the duration of the last save.
*
* @param {integer} timestamp - when the save request started
*/
Notebook.prototype._update_autosave_interval = function (start) {
var duration = (new Date().getTime() - start);
if (this.autosave_interval) {
// new save interval: higher of 10x save duration or parameter (default 30 seconds)
var interval = Math.max(10 * duration, this.minimum_autosave_interval);
// ceil to 10 seconds, otherwise we will be setting a new interval too often
// do not round or anything below 5000ms will desactivate saving.
interval = 10000 * Math.ceil(interval / 10000);
// set new interval, if it's changed
if (interval !== this.autosave_interval) {
this.set_autosave_interval(interval);
}
}
};
/**
* Explicitly trust the output of this notebook.
*/
Notebook.prototype.trust_notebook = function () {
var body = $("<div>").append($("<p>")
.text(i18n.msg._("A trusted Jupyter notebook may execute hidden malicious code when you open it. " +
"Selecting trust will immediately reload this notebook in a trusted state. " +
"For more information, see the Jupyter security documentation: "))
.append($("<a>").attr("href", "https://jupyter-notebook.readthedocs.io/en/latest/security.html")
.text(i18n.msg._("here"))
)
);
var nb = this;
dialog.modal({
notebook: this,
keyboard_manager: this.keyboard_manager,
title: i18n.msg._("Trust this notebook?"),
body: body,
buttons: {
Cancel : {},
Trust : {
class : "btn-danger",
click : function () {
var cells = nb.get_cells();
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
if (cell.cell_type === 'code') {
cell.output_area.trusted = true;
}
}
// If its write only and dirty, save before
// trusting
var pr;
if(nb.writable && nb.dirty) {
pr = nb.save_notebook();
}
else {
pr = Promise.resolve();
}
return pr.then(function() {
nb.contents.trust(nb.notebook_path)
.then(function(res) {
nb.events.trigger("trust_changed.Notebook", true);
window.location.reload();
}, function(err) {
console.log(err);
});
});
}
}
}
});
};
/**
* Make a copy of the current notebook.
* If the notebook has unsaved changes, it is saved first.
*/
Notebook.prototype.copy_notebook = function () {
var that = this;
var base_url = this.base_url;
var w = window.open('', IPython._target);
var parent = utils.url_path_split(this.notebook_path)[0];
var p;
if (this.dirty && this.writable) {
p = this.save_notebook(true);
} else {
p = Promise.resolve();
}
return p.then(function () {
return that.contents.copy(that.notebook_path, parent).then(
function (data) {
w.location = utils.url_path_join(
base_url, 'notebooks', utils.encode_uri_components(data.path)
);
},
function(error) {
w.close();
that.events.trigger('notebook_copy_failed', error);
}
);
});
};
/**
* Ensure a filename has the right extension
* Returns the filename with the appropriate extension, appending if necessary.
*/
Notebook.prototype.ensure_extension = function (name) {
var ext = utils.splitext(this.notebook_path)[1];
if (ext.length && name.slice(-ext.length) !== ext) {
name = name + ext;
}
return name;
};
/**
* Rename the notebook.
* @param {string} new_name
* @return {Promise} promise that resolves when the notebook is renamed.
*/
Notebook.prototype.rename = function (new_name) {
new_name = this.ensure_extension(new_name);
var that = this;
var parent = utils.url_path_split(this.notebook_path)[0];
var new_path = utils.url_path_join(parent, new_name);
return this.contents.rename(this.notebook_path, new_path).then(
function (json) {
that.notebook_name = json.name;
that.notebook_path = json.path;
that.last_modified = new Date(json.last_modified);
// debug 484
that._last_modified = json.last_modified;
that.session.rename_notebook(json.path);
that.events.trigger('notebook_renamed.Notebook', json);
}
);
};
/**
* Delete this notebook
*/
Notebook.prototype.delete = function () {
this.contents.delete(this.notebook_path);
};
/**
* Request a notebook's data from the server.
*
* @param {string} notebook_path - A notebook to load
*/
Notebook.prototype.load_notebook = function (notebook_path) {
this.notebook_path = notebook_path;
this.notebook_name = utils.url_path_split(this.notebook_path)[1];
this.events.trigger('notebook_loading.Notebook');
this.contents.get(notebook_path, {type: 'notebook'}).then(
$.proxy(this.load_notebook_success, this),
$.proxy(this.load_notebook_error, this)
);
};
/**
* Success callback for loading a notebook from the server.
*
* Load notebook data from the JSON response.
*
* @param {object} data JSON representation of a notebook
*/
Notebook.prototype.load_notebook_success = function (data) {
var failed, msg;
try {
this.fromJSON(data);
} catch (e) {
failed = e;
console.error("Notebook failed to load from JSON:", e);
}
if (failed || data.message) {
// *either* fromJSON failed or validation failed
var body = $("<div>");
var title;
if (failed) {
title = i18n.msg._("Notebook failed to load");
body.append($("<p>").text(
i18n.msg._("The error was: ")
)).append($("<div>").addClass("js-error").text(
failed.toString()
)).append($("<p>").text(
i18n.msg._("See the error console for details.")
));
} else {
title = i18n.msg._("Notebook validation failed");
}
if (data.message) {
if (failed) {
msg = i18n.msg._("The notebook also failed validation:");
} else {
msg = i18n.msg._("An invalid notebook may not function properly." +
" The validation error was:");
}
body.append($("<p>").text(
msg
)).append($("<div>").addClass("validation-error").append(
$("<pre>").text(data.message)
));
}
dialog.modal({
notebook: this,
keyboard_manager: this.keyboard_manager,
title: title,
body: body,
buttons : {
OK : {
"class" : "btn-primary"
}
}
});
}
if (this.ncells() === 0) {
this.insert_cell_below('code');
this.edit_mode(0);
} else {
this.select(0);
this.handle_command_mode(this.get_cell(0));
}
this.set_dirty(false);
this.scroll_to_top();
this.writable = data.writable || false;
this.last_modified = new Date(data.last_modified);
// debug 484
this._last_modified = 'load-success:'+data.last_modified;
var nbmodel = data.content;
var orig_nbformat = nbmodel.metadata.orig_nbformat;
var orig_nbformat_minor = nbmodel.metadata.orig_nbformat_minor;
if (orig_nbformat !== undefined && nbmodel.nbformat !== orig_nbformat) {
var oldmsg = i18n.msg._("This notebook has been converted from an older notebook format" +
" to the current notebook format v(%s).");
var newmsg = i18n.msg._("This notebook has been converted from a newer notebook format" +
" to the current notebook format v(%s).");
if (nbmodel.nbformat > orig_nbformat) {
msg = i18n.msg.sprintf(oldmsg,nbmodel.nbformat);
} else {
msg = i18n.msg.sprintf(newmsg,nbmodel.nbformat);
}
msg += " ";
msg += i18n.msg._("The next time you save this notebook, the " +
"current notebook format will be used.");
msg += " ";
if (nbmodel.nbformat > orig_nbformat) {
msg += i18n.msg._("Older versions of Jupyter may not be able to read the new format.");
} else {
msg += i18n.msg._("Some features of the original notebook may not be available.");
}
msg += " ";
msg += i18n.msg._("To preserve the original version, close the " +
"notebook without saving it.");
dialog.modal({
notebook: this,
keyboard_manager: this.keyboard_manager,
title : i18n.msg._("Notebook converted"),
body : msg,
buttons : {
OK : {
class : "btn-primary"
}
}
});
} else if (this.nbformat_minor < nbmodel.nbformat_minor) {
this.nbformat_minor = nbmodel.nbformat_minor;
}
if (this.session === null) {
var kernel_name = utils.get_url_param('kernel_name');
if (kernel_name) {
this.kernel_selector.set_kernel(kernel_name);
} else if (this.metadata.kernelspec) {
this.kernel_selector.set_kernel(this.metadata.kernelspec);
} else if (this.metadata.language) {
// compat with IJulia, IHaskell, and other early kernels
// adopters that where setting a language metadata.
this.kernel_selector.set_kernel({
name: i18n.msg._("(No name)"),
language: this.metadata.language
});
// this should be stored in kspec now, delete it.
// remove once we do not support notebook v3 anymore.
delete this.metadata.language;
} else {
// setting kernel via set_kernel above triggers start_session,
// otherwise start a new session with the server's default kernel
// spec_changed events will fire after kernel is loaded
this.start_session();
}
}
// load our checkpoint list
this.list_checkpoints();
// load toolbar state
if (this.metadata.celltoolbar) {
celltoolbar.CellToolbar.global_show();
celltoolbar.CellToolbar.activate_preset(this.metadata.celltoolbar);
} else {
celltoolbar.CellToolbar.global_hide();
}
if (!this.writable) {
this.set_autosave_interval(0);
this.events.trigger('notebook_read_only.Notebook');
}
// now that we're fully loaded, it is safe to restore save functionality
this._fully_loaded = true;
this.events.trigger('notebook_loaded.Notebook');
};
Notebook.prototype.set_kernelselector = function(k_selector){
this.kernel_selector = k_selector;
};
/**
* Failure callback for loading a notebook from the server.
*
* @param {Error} error
*/
Notebook.prototype.load_notebook_error = function (error) {
this.events.trigger('notebook_load_failed.Notebook', error);
var msg;
if (error.name === utils.XHR_ERROR && error.xhr.status === 500) {
utils.log_ajax_error(error.xhr, error.xhr_status, error.xhr_error);
msg = i18n.msg.sprintf(i18n.msg._("An unknown error occurred while loading this notebook. " +
"This version can load notebook formats %s or earlier. See the server log for details.",
"v" + this.nbformat));
} else {
msg = error.message;
console.warn('Error stack trace while loading notebook was:');
console.warn(error.stack);
}
dialog.modal({
notebook: this,
keyboard_manager: this.keyboard_manager,
title: i18n.msg._("Error loading notebook"),
body : msg,
buttons : {
"OK": {}
}
});
};
/********************* checkpoint-related ********************/
/**
* Save the notebook then immediately create a checkpoint.
*/
Notebook.prototype.save_checkpoint = function () {
this._checkpoint_after_save = true;
this.save_notebook(true);
};
/**
* Add a checkpoint for this notebook.
*/
Notebook.prototype.add_checkpoint = function (checkpoint) {
var found = false;
for (var i = 0; i < this.checkpoints.length; i++) {
var existing = this.checkpoints[i];
if (existing.id === checkpoint.id) {
found = true;
this.checkpoints[i] = checkpoint;
break;
}
}
if (!found) {
this.checkpoints.push(checkpoint);
}
this.last_checkpoint = this.checkpoints[this.checkpoints.length - 1];
};
/**
* List checkpoints for this notebook.
*/
Notebook.prototype.list_checkpoints = function () {
var that = this;
this.contents.list_checkpoints(this.notebook_path).then(
$.proxy(this.list_checkpoints_success, this),
function(error) {
that.events.trigger('list_checkpoints_failed.Notebook', error);
}
);
};
/**
* Success callback for listing checkpoints.
*
* @param {object} data - JSON representation of a checkpoint
*/
Notebook.prototype.list_checkpoints_success = function (data) {
this.checkpoints = data;
if (data.length) {
this.last_checkpoint = data[data.length - 1];
} else {
this.last_checkpoint = null;
}
this.events.trigger('checkpoints_listed.Notebook', [data]);
};
/**
* Create a checkpoint of this notebook on the server from the most recent save.
*/
Notebook.prototype.create_checkpoint = function () {
var that = this;
this.contents.create_checkpoint(this.notebook_path).then(
$.proxy(this.create_checkpoint_success, this),
function (error) {
that.events.trigger('checkpoint_failed.Notebook', error);
}
);
};
/**
* Success callback for creating a checkpoint.
*
* @param {object} data - JSON representation of a checkpoint
*/
Notebook.prototype.create_checkpoint_success = function (data) {
this.add_checkpoint(data);
this.events.trigger('checkpoint_created.Notebook', data);
};
/**
* Display the restore checkpoint dialog
* @param {string} checkpoint ID
*/
Notebook.prototype.restore_checkpoint_dialog = function (checkpoint) {
var that = this;
checkpoint = checkpoint || this.last_checkpoint;
if ( ! checkpoint ) {
console.log("restore dialog, but no checkpoint to restore to!");
return;
}
var body = $('<div/>').append(
$('<p/>').addClass("p-space").text(
i18n.msg._("Are you sure you want to revert the notebook to " +
"the latest checkpoint?")
).append(
$("<strong/>").text(" "+i18n.msg._("This cannot be undone."))
)
).append(
$('<p/>').addClass("p-space").text(i18n.msg._("The checkpoint was last updated at:"))
).append(
$('<p/>').addClass("p-space").text(
moment(checkpoint.last_modified).format('LLLL') +
' ('+moment(checkpoint.last_modified).fromNow()+')'// Long form: Tuesday, January 27, 2015 12:15 PM
).css("text-align", "center")
);
dialog.modal({
notebook: this,
keyboard_manager: this.keyboard_manager,
title : i18n.msg._("Revert notebook to checkpoint"),
body : body,
default_button: "Cancel",
buttons : {
Cancel: {},
Revert : {
class : "btn-danger",
click : function () {
that.restore_checkpoint(checkpoint.id);
}
}
}
});
};
/**
* Restore the notebook to a checkpoint state.
*
* @param {string} checkpoint ID
*/
Notebook.prototype.restore_checkpoint = function (checkpoint) {
this.events.trigger('notebook_restoring.Notebook', checkpoint);
var that = this;
this.contents.restore_checkpoint(this.notebook_path, checkpoint).then(
$.proxy(this.restore_checkpoint_success, this),
function (error) {
that.events.trigger('checkpoint_restore_failed.Notebook', error);
}
);
};
/**
* Success callback for restoring a notebook to a checkpoint.
*/
Notebook.prototype.restore_checkpoint_success = function () {
this.events.trigger('checkpoint_restored.Notebook');
this.load_notebook(this.notebook_path);
};
/**
* Delete a notebook checkpoint.
*
* @param {string} checkpoint ID
*/
Notebook.prototype.delete_checkpoint = function (checkpoint) {
this.events.trigger('notebook_restoring.Notebook', checkpoint);
var that = this;
this.contents.delete_checkpoint(this.notebook_path, checkpoint).then(
$.proxy(this.delete_checkpoint_success, this),
function (error) {
that.events.trigger('checkpoint_delete_failed.Notebook', error);
}
);
};
/**
* Success callback for deleting a notebook checkpoint.
*/
Notebook.prototype.delete_checkpoint_success = function () {
this.events.trigger('checkpoint_deleted.Notebook');
this.load_notebook(this.notebook_path);
};
return {Notebook: Notebook};
})
|