Compare commits
528 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2802e29945 | ||
|
|
e9eb8cbfc7 | ||
|
|
d343d8380c | ||
|
|
02906fa39f | ||
|
|
c1e797fe24 | ||
|
|
d7a42d8445 | ||
|
|
4f82bed52e | ||
|
|
84365f6721 | ||
|
|
e209dcc8d3 | ||
|
|
cd15a0f983 | ||
|
|
eb435e785c | ||
|
|
f03e521120 | ||
|
|
883909af4b | ||
|
|
13d66433e7 | ||
|
|
c44cfcb27c | ||
|
|
c14e5cbae5 | ||
|
|
f09e0b4205 | ||
|
|
ad72cea9a6 | ||
|
|
c289bc4239 | ||
|
|
733fa01b7e | ||
|
|
4d03460944 | ||
|
|
b3ba5d9eaa | ||
|
|
9e8ef3585e | ||
|
|
5c9cf44720 | ||
|
|
05a0d19ee9 | ||
|
|
d38adbe6ca | ||
|
|
871981cec7 | ||
|
|
8a54001e11 | ||
|
|
1e59f6e8be | ||
|
|
0e1eb5b56e | ||
|
|
e43df945b4 | ||
|
|
c23706b794 | ||
|
|
98cd10c6f5 | ||
|
|
55b92e854c | ||
|
|
0c926d60b8 | ||
|
|
d4d91fd003 | ||
|
|
89c4efbac3 | ||
|
|
3a5a34da0a | ||
|
|
cf3992545d | ||
|
|
0b7f663d43 | ||
|
|
abd72f8df0 | ||
|
|
1abdf72a04 | ||
|
|
7c536b66d0 | ||
|
|
cc1c019216 | ||
|
|
d20f231b34 | ||
|
|
8b03bf5fd9 | ||
|
|
af4025731a | ||
|
|
77bbb405fb | ||
|
|
7592cd2fe0 | ||
|
|
c5b996c8b1 | ||
|
|
ae0749d6b8 | ||
|
|
666a389718 | ||
|
|
6cd2bf9fea | ||
|
|
3ad7ea6df8 | ||
|
|
cb75a96e2c | ||
|
|
70965f4b69 | ||
|
|
29042f08a1 | ||
|
|
379db55111 | ||
|
|
4a65e773ce | ||
|
|
2829a91ff7 | ||
|
|
083e75bfb1 | ||
|
|
8f95e6ebb3 | ||
|
|
6b1826e8da | ||
|
|
f76598232a | ||
|
|
193149abac | ||
|
|
8c155d9f76 | ||
|
|
2061cc3674 | ||
|
|
832d6c2e97 | ||
|
|
e0870bbdb2 | ||
|
|
297983f411 | ||
|
|
1e9872c015 | ||
|
|
7ddf0af81b | ||
|
|
359bae6d30 | ||
|
|
d01add8f2b | ||
|
|
752a1c7df6 | ||
|
|
0d24d1e0d2 | ||
|
|
31fcf51506 | ||
|
|
f3c5ed8ee6 | ||
|
|
76d77439b7 | ||
|
|
2b428c7eb9 | ||
|
|
106d4be274 | ||
|
|
8e5d6bc467 | ||
|
|
e21aca045a | ||
|
|
a359afb799 | ||
|
|
41fb55cb01 | ||
|
|
f8cc65dfae | ||
|
|
e94368a356 | ||
|
|
2c8f2173a3 | ||
|
|
65eb1e9cb7 | ||
|
|
69ecbdfecc | ||
|
|
6c622b4100 | ||
|
|
59b645c399 | ||
|
|
134723a54b | ||
|
|
c482fed2c9 | ||
|
|
f60846ea2e | ||
|
|
cb23f8635a | ||
|
|
19f8f6bf3c | ||
|
|
b036cb04ff | ||
|
|
050efa339d | ||
|
|
faeff098fe | ||
|
|
4e298ed7d8 | ||
|
|
c810e4491a | ||
|
|
edbf45e542 | ||
|
|
caee53e778 | ||
|
|
55281650e2 | ||
|
|
ff17b551b4 | ||
|
|
4c3ab339cd | ||
|
|
99d64722a1 | ||
|
|
1b12bcb5d9 | ||
|
|
7a083865dd | ||
|
|
794b6bcb7b | ||
|
|
64ccd9043e | ||
|
|
18af4e92b0 | ||
|
|
cfbae50248 | ||
|
|
20576684dd | ||
|
|
1c2bdd1654 | ||
|
|
93aa1a13c6 | ||
|
|
4cd86a397c | ||
|
|
efcb203dd9 | ||
|
|
c859785edc | ||
|
|
41a4de081f | ||
|
|
82a8d41ac6 | ||
|
|
d274389a33 | ||
|
|
faecb124cc | ||
|
|
ce2d958f9a | ||
|
|
e37c8ff87f | ||
|
|
fd2136875e | ||
|
|
35d56ec3f0 | ||
|
|
310528ea10 | ||
|
|
98ee81606b | ||
|
|
6731eb9b2d | ||
|
|
e833783fb0 | ||
|
|
9d13d297cb | ||
|
|
2967969add | ||
|
|
060eddf812 | ||
|
|
473d2d5d09 | ||
|
|
13cc8df4be | ||
|
|
39edd4679d | ||
|
|
4cd45abfdd | ||
|
|
cc297a06d3 | ||
|
|
341a5e0c40 | ||
|
|
d967e23791 | ||
|
|
98610df1d4 | ||
|
|
7dd99cf3a1 | ||
|
|
9434baba11 | ||
|
|
4cbdf612af | ||
|
|
0c6eaf536a | ||
|
|
48870b1dd1 | ||
|
|
56121a9c9d | ||
|
|
0e0ae1b5be | ||
|
|
e956d83aa2 | ||
|
|
bfce480a91 | ||
|
|
3df446c306 | ||
|
|
e10fd68f90 | ||
|
|
cfd5842538 | ||
|
|
56e95fd640 | ||
|
|
52cf0dd147 | ||
|
|
311404d03c | ||
|
|
5900b3f1c7 | ||
|
|
45bc26f5eb | ||
|
|
45fc08e4a4 | ||
|
|
e3aa776f5a | ||
|
|
7101762082 | ||
|
|
34bbb376be | ||
|
|
391bdf5cd4 | ||
|
|
1e4f533008 | ||
|
|
dfd35b1a62 | ||
|
|
c7f6545f8a | ||
|
|
71c6343aab | ||
|
|
65005ef93a | ||
|
|
7d59bcab72 | ||
|
|
3f200c245c | ||
|
|
378a696bfe | ||
|
|
200a953849 | ||
|
|
0e95fba28d | ||
|
|
907525efd7 | ||
|
|
d490b794db | ||
|
|
f04cc69abe | ||
|
|
c93ce5dbab | ||
|
|
23c65eb518 | ||
|
|
2cf0e4a7ff | ||
|
|
c2a23d03c2 | ||
|
|
09fb170a83 | ||
|
|
20e2d9aa57 | ||
|
|
4192405444 | ||
|
|
6bbafc5920 | ||
|
|
1caf7b5140 | ||
|
|
10e0ff71bf | ||
|
|
5a0aec5b1d | ||
|
|
9964add97c | ||
|
|
d5f04551f2 | ||
|
|
8ba8eb58ed | ||
|
|
14cacefa96 | ||
|
|
6d6a4d3d33 | ||
|
|
e19f280e1b | ||
|
|
40e5e42ecc | ||
|
|
1741a59d3a | ||
|
|
7787317d06 | ||
|
|
76b3906ade | ||
|
|
efcf8c0c95 | ||
|
|
12bb4a8d93 | ||
|
|
e56e376894 | ||
|
|
4b4ada4137 | ||
|
|
eb94780cd4 | ||
|
|
750f963796 | ||
|
|
08639e6691 | ||
|
|
1a959baa72 | ||
|
|
227930e25b | ||
|
|
88ce19d99f | ||
|
|
257733e0cc | ||
|
|
e0b147ead0 | ||
|
|
24283e7eeb | ||
|
|
afe3f306e7 | ||
|
|
c4a68e9e5a | ||
|
|
67c35e5327 | ||
|
|
53f4408652 | ||
|
|
d72d5c64e2 | ||
|
|
9ca4b48f95 | ||
|
|
338331aa54 | ||
|
|
42c0b7b0fa | ||
|
|
28b9d322a2 | ||
|
|
38de99fc9c | ||
|
|
a4416bd11f | ||
|
|
27cbd242b2 | ||
|
|
c790b79393 | ||
|
|
7646dc11fe | ||
|
|
104ec5ba73 | ||
|
|
53a0718a78 | ||
|
|
892f123975 | ||
|
|
461daca00e | ||
|
|
09c0069b43 | ||
|
|
42de43d052 | ||
|
|
6ce51fa099 | ||
|
|
51728fb192 | ||
|
|
d438b510df | ||
|
|
2d669a50b2 | ||
|
|
4aabf3c69c | ||
|
|
69f9cf28df | ||
|
|
81cb51bb8d | ||
|
|
371f97e050 | ||
|
|
3204447a74 | ||
|
|
36303e338d | ||
|
|
b0b2fd7804 | ||
|
|
a37206e259 | ||
|
|
ff94a22826 | ||
|
|
8244472cb2 | ||
|
|
15dd46a91a | ||
|
|
c379b00918 | ||
|
|
9bf856f6e6 | ||
|
|
37df0a9338 | ||
|
|
e6aaca1728 | ||
|
|
bbbee21b0d | ||
|
|
6fb6f441d5 | ||
|
|
cda7c66637 | ||
|
|
53122bfa9f | ||
|
|
1fecd35bb7 | ||
|
|
85058bd847 | ||
|
|
40c02651ae | ||
|
|
8d72dc7bc4 | ||
|
|
46d630a2c0 | ||
|
|
7e040a4177 | ||
|
|
483de0fc30 | ||
|
|
09277868d2 | ||
|
|
86a19c25a8 | ||
|
|
1715b0c378 | ||
|
|
3599863304 | ||
|
|
91dc4f1d03 | ||
|
|
4b124cc214 | ||
|
|
0ed01e5a21 | ||
|
|
b7192d706c | ||
|
|
557e4892b0 | ||
|
|
b61b0bf3ad | ||
|
|
3a6a8af9f6 | ||
|
|
5b7167436b | ||
|
|
8d4b4430de | ||
|
|
9d4cb09fdf | ||
|
|
14bcad629e | ||
|
|
645c3b10dd | ||
|
|
16f9222847 | ||
|
|
b7e7c8caf2 | ||
|
|
15cedc0269 | ||
|
|
b14831613e | ||
|
|
b673593683 | ||
|
|
7703d959ef | ||
|
|
cb47024f2b | ||
|
|
55cbc1830a | ||
|
|
3f61d725c4 | ||
|
|
bc8bc03fd2 | ||
|
|
cbc20782ae | ||
|
|
af290117d4 | ||
|
|
42a662a7ad | ||
|
|
2ead96313b | ||
|
|
fcd9e0d5c6 | ||
|
|
593540e467 | ||
|
|
f66d0e1200 | ||
|
|
fa1c719c96 | ||
|
|
77b66d6015 | ||
|
|
8c14ba01f7 | ||
|
|
ad87d196e5 | ||
|
|
aac892364c | ||
|
|
64b670fd8f | ||
|
|
a55c6777d3 | ||
|
|
f9e16557c4 | ||
|
|
165b682e01 | ||
|
|
92ab6dc635 | ||
|
|
0385ce6eb2 | ||
|
|
5ba6e8fea2 | ||
|
|
8979c0919f | ||
|
|
b9048b6d65 | ||
|
|
3592dba7f5 | ||
|
|
a7defed64c | ||
|
|
ff2f11a706 | ||
|
|
84cc47920b | ||
|
|
f57d96d64d | ||
|
|
c310627d1b | ||
|
|
be66f53c7e | ||
|
|
77f32a8f4b | ||
|
|
9b8a24eeb9 | ||
|
|
c87bf553f6 | ||
|
|
2361eb4a84 | ||
|
|
4f4cc8f98f | ||
|
|
5f1caf668b | ||
|
|
054152f162 | ||
|
|
78cf9df6ef | ||
|
|
2924b20c92 | ||
|
|
f6318ae86c | ||
|
|
e57907de35 | ||
|
|
df2f9e7119 | ||
|
|
23d7eb7a43 | ||
|
|
99a6dbeac2 | ||
|
|
b05daddc5c | ||
|
|
6868ddeed5 | ||
|
|
8de6bff2fb | ||
|
|
9028ec9857 | ||
|
|
8696a01eda | ||
|
|
f8f91c6a6a | ||
|
|
97739e9e8a | ||
|
|
16b68572cd | ||
|
|
d6e63b4d7c | ||
|
|
a6e8111484 | ||
|
|
bdc214f45b | ||
|
|
a91570768e | ||
|
|
d35321c6c6 | ||
|
|
e482cba237 | ||
|
|
c7cf13f8ea | ||
|
|
e0329ce59a | ||
|
|
de7848ba21 | ||
|
|
d6f5a5684f | ||
|
|
9883590a91 | ||
|
|
b11bdddfe2 | ||
|
|
623cd515de | ||
|
|
f53da87f6f | ||
|
|
ff7ef47cc7 | ||
|
|
108b24abdd | ||
|
|
2d309c6e81 | ||
|
|
07f0cdadcd | ||
|
|
7c8c9bc3af | ||
|
|
948e0b1f43 | ||
|
|
be9027f36f | ||
|
|
9bb4155460 | ||
|
|
ad877b2305 | ||
|
|
fb9ad028f8 | ||
|
|
833694229d | ||
|
|
d6a8a3d410 | ||
|
|
4e9d228a60 | ||
|
|
db0d31260e | ||
|
|
9178b23473 | ||
|
|
40d5e5dfe9 | ||
|
|
f95476c51e | ||
|
|
73ab77ad8b | ||
|
|
e6f84c45b9 | ||
|
|
58c22b8ed0 | ||
|
|
ee1de04544 | ||
|
|
9977aa571a | ||
|
|
65b883749a | ||
|
|
5cee4f8876 | ||
|
|
3aec2c4568 | ||
|
|
3defd7d7b1 | ||
|
|
ac97332393 | ||
|
|
62bda4b917 | ||
|
|
cb6857c16b | ||
|
|
643e945540 | ||
|
|
b52b639eed | ||
|
|
e0ea9b78f8 | ||
|
|
8e4f92ac64 | ||
|
|
350bd25404 | ||
|
|
6d3fe6cf89 | ||
|
|
a3bf95e423 | ||
|
|
fc72cdf3d0 | ||
|
|
b619bd3db7 | ||
|
|
b1631ae2b3 | ||
|
|
a01aa78f36 | ||
|
|
975bc64fd0 | ||
|
|
231fa489cb | ||
|
|
123f0f8269 | ||
|
|
a6223cc319 | ||
|
|
8bdc5f20e7 | ||
|
|
bb4f3d6e1a | ||
|
|
25f54356d4 | ||
|
|
5b3b5b6821 | ||
|
|
1474a4fe79 | ||
|
|
c89ed53be1 | ||
|
|
e692beafba | ||
|
|
850ef39bf7 | ||
|
|
1bbb99b548 | ||
|
|
7675d605ea | ||
|
|
7d5cdb9220 | ||
|
|
78089bc0c4 | ||
|
|
eb9d7bf5c3 | ||
|
|
8ce53e8dfa | ||
|
|
0f2b2daeab | ||
|
|
68ccf6510d | ||
|
|
d960513ef2 | ||
|
|
1865c0b1dd | ||
|
|
af412e7e24 | ||
|
|
a74b1dd1bf | ||
|
|
7d9c853eeb | ||
|
|
7caf1c0794 | ||
|
|
70b3edcbeb | ||
|
|
50543724d4 | ||
|
|
ad81e641b3 | ||
|
|
429ee8e423 | ||
|
|
604795d6fc | ||
|
|
6599e08d32 | ||
|
|
94ddb6c11f | ||
|
|
a514060402 | ||
|
|
fec5ddd150 | ||
|
|
811a44fd14 | ||
|
|
1c5bad24f3 | ||
|
|
17b4de18d7 | ||
|
|
290cb2f1a7 | ||
|
|
ff7cb99bfe | ||
|
|
339de2fa41 | ||
|
|
cafab17ee0 | ||
|
|
9fa1757ffb | ||
|
|
e94921c002 | ||
|
|
d30098d646 | ||
|
|
fba11869b6 | ||
|
|
453412fa0c | ||
|
|
607897a1b0 | ||
|
|
221fdc51ba | ||
|
|
37551a8517 | ||
|
|
8877eab977 | ||
|
|
2d0205714c | ||
|
|
49111345d1 | ||
|
|
570564b0c4 | ||
|
|
22dd63d77b | ||
|
|
736311ff9a | ||
|
|
34b377522a | ||
|
|
9f846dbe3c | ||
|
|
845694beb6 | ||
|
|
665f728946 | ||
|
|
d879e4a560 | ||
|
|
8e1a68d461 | ||
|
|
2738d12e0f | ||
|
|
25148d06fe | ||
|
|
4870b197de | ||
|
|
12377794a6 | ||
|
|
bf27623756 | ||
|
|
9afdf01430 | ||
|
|
80f16dadde | ||
|
|
a68ac4fc02 | ||
|
|
3dde465427 | ||
|
|
f77232740c | ||
|
|
56f251ca0c | ||
|
|
9282bfcc60 | ||
|
|
8d0bbbc9f1 | ||
|
|
ee33f2a4a8 | ||
|
|
ab313c2d4d | ||
|
|
4c1de287cd | ||
|
|
9ea9f828bc | ||
|
|
58e4cd91cc | ||
|
|
b5f17b1acb | ||
|
|
e9c884d674 | ||
|
|
492953c7f0 | ||
|
|
dd8d9d9d8d | ||
|
|
9ff32ed9cd | ||
|
|
c9b0c4547a | ||
|
|
037b499cb2 | ||
|
|
f4fc987597 | ||
|
|
580bc6fd6e | ||
|
|
c91e6160fe | ||
|
|
13c6c1ad37 | ||
|
|
0faa7d3174 | ||
|
|
cfe7c65987 | ||
|
|
c5a2706c1b | ||
|
|
a379d7020e | ||
|
|
a74a16cfba | ||
|
|
37e0e1c384 | ||
|
|
62061ae737 | ||
|
|
8fe2680f80 | ||
|
|
09a747ce59 | ||
|
|
2b34f738b1 | ||
|
|
050c4075b8 | ||
|
|
e64a6d6129 | ||
|
|
b27537a44b | ||
|
|
db8ce08794 | ||
|
|
4b2f599f4b | ||
|
|
78a0fe0769 | ||
|
|
927a1362af | ||
|
|
7e31612c3c | ||
|
|
fbf75915f4 | ||
|
|
bf3d0bdd3d | ||
|
|
20cdd86fcf | ||
|
|
c6f048adc7 | ||
|
|
1451997172 | ||
|
|
351a59033f | ||
|
|
34bfe4527d | ||
|
|
667069b573 | ||
|
|
c3a7486930 | ||
|
|
1a2a69b21a | ||
|
|
06168c5364 | ||
|
|
a0ab8b9432 | ||
|
|
0eab440a8a | ||
|
|
567e36badf | ||
|
|
cff267c9c6 | ||
|
|
cf8ee0acac | ||
|
|
f387c4c358 | ||
|
|
c526cedd41 | ||
|
|
5551a018ac | ||
|
|
3744d9b71d | ||
|
|
436bd7b39c | ||
|
|
4233383a98 | ||
|
|
1356dc1ef0 | ||
|
|
484cc81a73 | ||
|
|
914caadeec | ||
|
|
1770fa0026 | ||
|
|
c8a20b0d32 |
21
.travis.yml
21
.travis.yml
@@ -1,7 +1,6 @@
|
||||
language: python
|
||||
|
||||
python:
|
||||
- '2.5'
|
||||
- '2.6'
|
||||
- '2.7'
|
||||
- 'pypy'
|
||||
@@ -11,6 +10,9 @@ env:
|
||||
- DB=sqlite:memory
|
||||
- DB=mysql://root:@localhost/test_w2p
|
||||
- DB=postgres://postgres:@localhost/test_w2p
|
||||
- DB=google:datastore
|
||||
- DB=mongodb://mongodb:mongodb@localhost/test_w2p
|
||||
- DB=imap://imap:imap@localhost:993
|
||||
before_script:
|
||||
- if [[ $TRAVIS_PYTHON_VERSION != '2.7' ]]; then pip install unittest2; fi
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install coverage; fi;
|
||||
@@ -19,6 +21,15 @@ before_script:
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == '2.5' ]]; then pip install pysqlite; fi
|
||||
- if [[ $DB == mysql* ]]; then mysql -e 'create database test_w2p;'; fi
|
||||
- if [[ $DB == postgres* ]]; then psql -c 'create database test_w2p;' -U postgres; fi
|
||||
|
||||
# Install last sdk for app engine (update only whenever a new release is available)
|
||||
- if [[ $DB == google* ]]; then wget http://googleappengine.googlecode.com/files/google_appengine_1.8.9.zip -nv; fi
|
||||
- if [[ $DB == google* ]]; then unzip -q google_appengine_1.8.9.zip; fi
|
||||
- if [[ $DB == google* ]]; then mv -f ./google_appengine/google ./google; fi
|
||||
|
||||
- if [[ $DB == mongodb* ]]; then pip install pymongo; fi
|
||||
- if [[ $DB == mongodb* ]]; then mongo test_w2p --eval 'db.addUser("mongodb", "mongodb");'; fi
|
||||
|
||||
#Temporal solution to travis issue #155
|
||||
- sudo chmod 777 /dev/shm
|
||||
- sudo rm -rf /dev/shm && sudo ln -s /run/shm /dev/shm
|
||||
@@ -28,6 +39,11 @@ matrix:
|
||||
env: DB=postgres://postgres:@localhost/test_w2p
|
||||
- python: 'pypy'
|
||||
env: DB=mysql://root:@localhost/test_w2p
|
||||
- python: 'pypy'
|
||||
env: DB=google:datastore
|
||||
- python: '2.6'
|
||||
env: DB=google:datastore
|
||||
|
||||
|
||||
script: export COVERAGE_PROCESS_START=gluon/tests/coverage.ini; ./web2py.py --run_system_tests --with_coverage
|
||||
after_success:
|
||||
@@ -36,3 +52,6 @@ after_success:
|
||||
|
||||
notifications:
|
||||
email: true
|
||||
|
||||
services: mongodb
|
||||
|
||||
|
||||
42
CHANGELOG
42
CHANGELOG
@@ -1,4 +1,44 @@
|
||||
## 2.7.1 - 2.7.2
|
||||
## 2.9.1 - 2.9.5
|
||||
|
||||
- many small but important bug fixes
|
||||
- jquery 1.11
|
||||
- codemirror 3.21, thanks Paolo Valleri
|
||||
- fixed security issue with sessions in database, thanks Nathan Humphreys
|
||||
- fixed security issue with persistant data in session, thanks Kiran
|
||||
- fixed security issue with redirect after expired login, thanks André Kablu
|
||||
- cleaner DAL and rname integration, thanks niphlod and Michele
|
||||
- added mongodb and imap tests for dal, thanks Alan
|
||||
- NoSQL dal tests, thanks Alan
|
||||
- better docstrings, thanks Niphlod
|
||||
- allow URL(...,language=...) with parametric router, thanks Jonathan
|
||||
- allow non-expiration of gae-memcache, thanks crimsoncantab
|
||||
- MARKMIN(...,_class='...'), thanks Luca
|
||||
- better transliteration in building slugs
|
||||
- autolink emails
|
||||
- new Janrain API, thanks PeterQ2
|
||||
- enable admin app for GAE (experimental), thanks Alan
|
||||
- many bug fixes
|
||||
- invalidate function in web2py.js, thanks Paolo
|
||||
- DAL(...,adapter_args=dict(engine='MyISAM'))
|
||||
- todolist panel in admin editor, thanks Paolo Valleri
|
||||
|
||||
## 2.8.1
|
||||
|
||||
- no more winservice (use nssm instead)
|
||||
- better imap support in DAL
|
||||
- db().select().as_tree()
|
||||
- bootstrap 2.3.2
|
||||
- codemirror 3.19
|
||||
- improved mongoDB support, thanks Alan
|
||||
- support for wiki custom render function
|
||||
- Wiki(...groups=['x','y']) allows bypassing default permissions
|
||||
- fixed websocket_messaging.py to support newer Tornado
|
||||
- NDB support for GAE, thanks Quint
|
||||
- fixed major concurrecy issue with MEMDB
|
||||
- blocked generic.jsonp for security reasons
|
||||
- many bug fixes, thanks Niphlod, Michele, Anthony, Tim, and many others.
|
||||
|
||||
## 2.7.1 - 2.7.4
|
||||
|
||||
- jQuery 1.10.2
|
||||
- codemirror 3.18, thanks Paolo
|
||||
|
||||
2
Makefile
2
Makefile
@@ -30,7 +30,7 @@ update:
|
||||
echo "remember that pymysql was tweaked"
|
||||
src:
|
||||
### Use semantic versioning
|
||||
echo 'Version 2.7.3-stable+timestamp.'`date +%Y.%m.%d.%H.%M.%S` > VERSION
|
||||
echo 'Version 2.9.5-stable+timestamp.'`date +%Y.%m.%d.%H.%M.%S` > VERSION
|
||||
### rm -f all junk files
|
||||
make clean
|
||||
### clean up baisc apps
|
||||
|
||||
2
VERSION
2
VERSION
@@ -1 +1 @@
|
||||
Version 2.7.3-stable+timestamp.2013.10.11.18.10.01
|
||||
Version 2.9.5-stable+timestamp.2014.03.15.21.24.06
|
||||
|
||||
@@ -16,6 +16,8 @@ try:
|
||||
except ImportError:
|
||||
pgv = None
|
||||
|
||||
is_gae = request.env.web2py_runtime_gae or False
|
||||
|
||||
# ## critical --- make a copy of the environment
|
||||
|
||||
global_env = copy.copy(globals())
|
||||
@@ -186,6 +188,10 @@ def select():
|
||||
import re
|
||||
db = get_database(request)
|
||||
dbname = request.args[0]
|
||||
try:
|
||||
is_imap = db._uri.startswith("imap://")
|
||||
except (KeyError, AttributeError, TypeError):
|
||||
is_imap = False
|
||||
regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)')
|
||||
if len(request.args) > 1 and hasattr(db[request.args[1]], '_primarykey'):
|
||||
regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)')
|
||||
@@ -203,7 +209,15 @@ def select():
|
||||
else:
|
||||
start = 0
|
||||
nrows = 0
|
||||
stop = start + 100
|
||||
|
||||
step = 100
|
||||
fields = []
|
||||
|
||||
if is_imap:
|
||||
step = 3
|
||||
|
||||
stop = start + step
|
||||
|
||||
table = None
|
||||
rows = []
|
||||
orderby = request.vars.orderby
|
||||
@@ -235,21 +249,27 @@ def select():
|
||||
if match:
|
||||
table = match.group('table')
|
||||
try:
|
||||
nrows = db(query).count()
|
||||
nrows = db(query, ignore_common_filters=True).count()
|
||||
if form.vars.update_check and form.vars.update_fields:
|
||||
db(query).update(**eval_in_global_env('dict(%s)'
|
||||
% form.vars.update_fields))
|
||||
db(query, ignore_common_filters=True).update(
|
||||
**eval_in_global_env('dict(%s)' % form.vars.update_fields))
|
||||
response.flash = T('%s %%{row} updated', nrows)
|
||||
elif form.vars.delete_check:
|
||||
db(query).delete()
|
||||
db(query, ignore_common_filters=True).delete()
|
||||
response.flash = T('%s %%{row} deleted', nrows)
|
||||
nrows = db(query).count()
|
||||
nrows = db(query, ignore_common_filters=True).count()
|
||||
|
||||
if is_imap:
|
||||
fields = [db[table][name] for name in
|
||||
("id", "uid", "created", "to",
|
||||
"sender", "subject")]
|
||||
if orderby:
|
||||
rows = db(query, ignore_common_filters=True).select(limitby=(
|
||||
start, stop), orderby=eval_in_global_env(orderby))
|
||||
rows = db(query, ignore_common_filters=True).select(
|
||||
*fields, limitby=(start, stop),
|
||||
orderby=eval_in_global_env(orderby))
|
||||
else:
|
||||
rows = db(query, ignore_common_filters=True).select(
|
||||
limitby=(start, stop))
|
||||
*fields, limitby=(start, stop))
|
||||
except Exception, e:
|
||||
import traceback
|
||||
tb = traceback.format_exc()
|
||||
@@ -278,11 +298,12 @@ def select():
|
||||
table=table,
|
||||
start=start,
|
||||
stop=stop,
|
||||
step=step,
|
||||
nrows=nrows,
|
||||
rows=rows,
|
||||
query=request.vars.query,
|
||||
formcsv=formcsv,
|
||||
tb=tb,
|
||||
tb=tb
|
||||
)
|
||||
|
||||
|
||||
@@ -340,36 +361,43 @@ def state():
|
||||
|
||||
|
||||
def ccache():
|
||||
cache.ram.initialize()
|
||||
cache.disk.initialize()
|
||||
if is_gae:
|
||||
form = FORM(
|
||||
P(TAG.BUTTON(T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")))
|
||||
else:
|
||||
cache.ram.initialize()
|
||||
cache.disk.initialize()
|
||||
|
||||
form = FORM(
|
||||
P(TAG.BUTTON(
|
||||
T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
||||
P(TAG.BUTTON(
|
||||
T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
||||
P(TAG.BUTTON(
|
||||
T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
||||
)
|
||||
form = FORM(
|
||||
P(TAG.BUTTON(
|
||||
T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
||||
P(TAG.BUTTON(
|
||||
T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
||||
P(TAG.BUTTON(
|
||||
T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
||||
)
|
||||
|
||||
if form.accepts(request.vars, session):
|
||||
clear_ram = False
|
||||
clear_disk = False
|
||||
session.flash = ""
|
||||
if request.vars.yes:
|
||||
clear_ram = clear_disk = True
|
||||
if request.vars.ram:
|
||||
clear_ram = True
|
||||
if request.vars.disk:
|
||||
clear_disk = True
|
||||
|
||||
if clear_ram:
|
||||
cache.ram.clear()
|
||||
session.flash += T("Ram Cleared")
|
||||
if clear_disk:
|
||||
cache.disk.clear()
|
||||
session.flash += T("Disk Cleared")
|
||||
|
||||
if is_gae:
|
||||
if request.vars.yes:
|
||||
cache.ram.clear()
|
||||
session.flash += T("Cache Cleared")
|
||||
else:
|
||||
clear_ram = False
|
||||
clear_disk = False
|
||||
if request.vars.yes:
|
||||
clear_ram = clear_disk = True
|
||||
if request.vars.ram:
|
||||
clear_ram = True
|
||||
if request.vars.disk:
|
||||
clear_disk = True
|
||||
if clear_ram:
|
||||
cache.ram.clear()
|
||||
session.flash += T("Ram Cleared")
|
||||
if clear_disk:
|
||||
cache.disk.clear()
|
||||
session.flash += T("Disk Cleared")
|
||||
redirect(URL(r=request))
|
||||
|
||||
try:
|
||||
@@ -395,6 +423,7 @@ def ccache():
|
||||
'oldest': time.time(),
|
||||
'keys': []
|
||||
}
|
||||
|
||||
disk = copy.copy(ram)
|
||||
total = copy.copy(ram)
|
||||
disk['keys'] = []
|
||||
@@ -409,72 +438,81 @@ def ccache():
|
||||
|
||||
return (hours, minutes, seconds)
|
||||
|
||||
for key, value in cache.ram.storage.iteritems():
|
||||
if isinstance(value, dict):
|
||||
ram['hits'] = value['hit_total'] - value['misses']
|
||||
ram['misses'] = value['misses']
|
||||
try:
|
||||
ram['ratio'] = ram['hits'] * 100 / value['hit_total']
|
||||
except (KeyError, ZeroDivisionError):
|
||||
ram['ratio'] = 0
|
||||
else:
|
||||
if hp:
|
||||
ram['bytes'] += hp.iso(value[1]).size
|
||||
ram['objects'] += hp.iso(value[1]).count
|
||||
ram['entries'] += 1
|
||||
if value[0] < ram['oldest']:
|
||||
ram['oldest'] = value[0]
|
||||
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||
folder = os.path.join(request.folder,'cache')
|
||||
if not os.path.exists(folder):
|
||||
os.mkdir(folder)
|
||||
locker = open(os.path.join(folder, 'cache.lock'), 'a')
|
||||
portalocker.lock(locker, portalocker.LOCK_EX)
|
||||
disk_storage = shelve.open(
|
||||
os.path.join(folder, 'cache.shelve'))
|
||||
try:
|
||||
for key, value in disk_storage.items():
|
||||
if is_gae:
|
||||
gae_stats = cache.ram.client.get_stats()
|
||||
try:
|
||||
gae_stats['ratio'] = ((gae_stats['hits'] * 100) /
|
||||
(gae_stats['hits'] + gae_stats['misses']))
|
||||
except ZeroDivisionError:
|
||||
gae_stats['ratio'] = T("?")
|
||||
gae_stats['oldest'] = GetInHMS(time.time() - gae_stats['oldest_item_age'])
|
||||
total.update(gae_stats)
|
||||
else:
|
||||
for key, value in cache.ram.storage.iteritems():
|
||||
if isinstance(value, dict):
|
||||
disk['hits'] = value['hit_total'] - value['misses']
|
||||
disk['misses'] = value['misses']
|
||||
ram['hits'] = value['hit_total'] - value['misses']
|
||||
ram['misses'] = value['misses']
|
||||
try:
|
||||
disk['ratio'] = disk['hits'] * 100 / value['hit_total']
|
||||
ram['ratio'] = ram['hits'] * 100 / value['hit_total']
|
||||
except (KeyError, ZeroDivisionError):
|
||||
disk['ratio'] = 0
|
||||
ram['ratio'] = 0
|
||||
else:
|
||||
if hp:
|
||||
disk['bytes'] += hp.iso(value[1]).size
|
||||
disk['objects'] += hp.iso(value[1]).count
|
||||
disk['entries'] += 1
|
||||
if value[0] < disk['oldest']:
|
||||
disk['oldest'] = value[0]
|
||||
disk['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||
ram['bytes'] += hp.iso(value[1]).size
|
||||
ram['objects'] += hp.iso(value[1]).count
|
||||
ram['entries'] += 1
|
||||
if value[0] < ram['oldest']:
|
||||
ram['oldest'] = value[0]
|
||||
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||
folder = os.path.join(request.folder,'cache')
|
||||
if not os.path.exists(folder):
|
||||
os.mkdir(folder)
|
||||
locker = open(os.path.join(folder, 'cache.lock'), 'a')
|
||||
portalocker.lock(locker, portalocker.LOCK_EX)
|
||||
disk_storage = shelve.open(
|
||||
os.path.join(folder, 'cache.shelve'))
|
||||
try:
|
||||
for key, value in disk_storage.items():
|
||||
if isinstance(value, dict):
|
||||
disk['hits'] = value['hit_total'] - value['misses']
|
||||
disk['misses'] = value['misses']
|
||||
try:
|
||||
disk['ratio'] = disk['hits'] * 100 / value['hit_total']
|
||||
except (KeyError, ZeroDivisionError):
|
||||
disk['ratio'] = 0
|
||||
else:
|
||||
if hp:
|
||||
disk['bytes'] += hp.iso(value[1]).size
|
||||
disk['objects'] += hp.iso(value[1]).count
|
||||
disk['entries'] += 1
|
||||
if value[0] < disk['oldest']:
|
||||
disk['oldest'] = value[0]
|
||||
disk['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||
finally:
|
||||
portalocker.unlock(locker)
|
||||
locker.close()
|
||||
disk_storage.close()
|
||||
|
||||
finally:
|
||||
portalocker.unlock(locker)
|
||||
locker.close()
|
||||
disk_storage.close()
|
||||
|
||||
total['entries'] = ram['entries'] + disk['entries']
|
||||
total['bytes'] = ram['bytes'] + disk['bytes']
|
||||
total['objects'] = ram['objects'] + disk['objects']
|
||||
total['hits'] = ram['hits'] + disk['hits']
|
||||
total['misses'] = ram['misses'] + disk['misses']
|
||||
total['keys'] = ram['keys'] + disk['keys']
|
||||
try:
|
||||
total['ratio'] = total['hits'] * 100 / (total['hits'] +
|
||||
total['entries'] = ram['entries'] + disk['entries']
|
||||
total['bytes'] = ram['bytes'] + disk['bytes']
|
||||
total['objects'] = ram['objects'] + disk['objects']
|
||||
total['hits'] = ram['hits'] + disk['hits']
|
||||
total['misses'] = ram['misses'] + disk['misses']
|
||||
total['keys'] = ram['keys'] + disk['keys']
|
||||
try:
|
||||
total['ratio'] = total['hits'] * 100 / (total['hits'] +
|
||||
total['misses'])
|
||||
except (KeyError, ZeroDivisionError):
|
||||
total['ratio'] = 0
|
||||
except (KeyError, ZeroDivisionError):
|
||||
total['ratio'] = 0
|
||||
|
||||
if disk['oldest'] < ram['oldest']:
|
||||
total['oldest'] = disk['oldest']
|
||||
else:
|
||||
total['oldest'] = ram['oldest']
|
||||
if disk['oldest'] < ram['oldest']:
|
||||
total['oldest'] = disk['oldest']
|
||||
else:
|
||||
total['oldest'] = ram['oldest']
|
||||
|
||||
ram['oldest'] = GetInHMS(time.time() - ram['oldest'])
|
||||
disk['oldest'] = GetInHMS(time.time() - disk['oldest'])
|
||||
total['oldest'] = GetInHMS(time.time() - total['oldest'])
|
||||
ram['oldest'] = GetInHMS(time.time() - ram['oldest'])
|
||||
disk['oldest'] = GetInHMS(time.time() - disk['oldest'])
|
||||
total['oldest'] = GetInHMS(time.time() - total['oldest'])
|
||||
|
||||
def key_table(keys):
|
||||
return TABLE(
|
||||
@@ -483,9 +521,10 @@ def ccache():
|
||||
**dict(_class='cache-keys',
|
||||
_style="border-collapse: separate; border-spacing: .5em;"))
|
||||
|
||||
ram['keys'] = key_table(ram['keys'])
|
||||
disk['keys'] = key_table(disk['keys'])
|
||||
total['keys'] = key_table(total['keys'])
|
||||
if not is_gae:
|
||||
ram['keys'] = key_table(ram['keys'])
|
||||
disk['keys'] = key_table(disk['keys'])
|
||||
total['keys'] = key_table(total['keys'])
|
||||
|
||||
return dict(form=form, total=total,
|
||||
ram=ram, disk=disk, object_stats=hp != False)
|
||||
@@ -577,8 +616,8 @@ def bg_graph_model():
|
||||
graph.add_edge(n1, n2, color="#4C4C4C", label='')
|
||||
|
||||
graph.layout()
|
||||
#return graph.draw(format='png', prog='dot')
|
||||
if not request.args:
|
||||
response.headers['Content-Type'] = 'image/png'
|
||||
return graph.draw(format='png', prog='dot')
|
||||
else:
|
||||
response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0)
|
||||
|
||||
@@ -54,9 +54,13 @@ def interact():
|
||||
filename = web_debugger.filename
|
||||
lineno = web_debugger.lineno
|
||||
if filename:
|
||||
# prevent IOError 2 on some circuntances (EAFP instead of os.access)
|
||||
try:
|
||||
lines = open(filename).readlines()
|
||||
except:
|
||||
lines = ""
|
||||
lines = dict([(i + 1, l) for (i, l) in enumerate(
|
||||
[l.strip("\n").strip("\r") for l
|
||||
in open(filename).readlines()])])
|
||||
[l.strip("\n").strip("\r") for l in lines])])
|
||||
filename = os.path.basename(filename)
|
||||
else:
|
||||
lines = {}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# coding: utf8
|
||||
|
||||
EXPERIMENTAL_STUFF = True
|
||||
MAXNFILES = 1000
|
||||
|
||||
if EXPERIMENTAL_STUFF:
|
||||
if is_mobile:
|
||||
@@ -12,6 +13,7 @@ from gluon.admin import *
|
||||
from gluon.fileutils import abspath, read_file, write_file
|
||||
from gluon.utils import web2py_uuid
|
||||
from gluon.tools import Config
|
||||
from gluon.compileapp import find_exposed_functions
|
||||
from glob import glob
|
||||
import shutil
|
||||
import platform
|
||||
@@ -29,10 +31,18 @@ from gluon.languages import (read_possible_languages, read_dict, write_dict,
|
||||
read_plural_dict, write_plural_dict)
|
||||
|
||||
|
||||
if DEMO_MODE and request.function in ['change_password', 'pack', 'pack_custom','pack_plugin', 'upgrade_web2py', 'uninstall', 'cleanup', 'compile_app', 'remove_compiled_app', 'delete', 'delete_plugin', 'create_file', 'upload_file', 'update_languages', 'reload_routes', 'git_push', 'git_pull']:
|
||||
if DEMO_MODE and request.function in ['change_password', 'pack',
|
||||
'pack_custom','pack_plugin', 'upgrade_web2py', 'uninstall',
|
||||
'cleanup', 'compile_app', 'remove_compiled_app', 'delete',
|
||||
'delete_plugin', 'create_file', 'upload_file', 'update_languages',
|
||||
'reload_routes', 'git_push', 'git_pull', 'install_plugin']:
|
||||
session.flash = T('disabled in demo mode')
|
||||
redirect(URL('site'))
|
||||
|
||||
if is_gae and request.function in ('edit', 'edit_language',
|
||||
'edit_plurals', 'update_languages', 'create_file', 'install_plugin'):
|
||||
session.flash = T('disabled in GAE mode')
|
||||
redirect(URL('site'))
|
||||
|
||||
if not is_manager() and request.function in ['change_password', 'upgrade_web2py']:
|
||||
session.flash = T('disabled in multi user mode')
|
||||
@@ -62,10 +72,12 @@ def log_progress(app, mode='EDIT', filename=None, progress=0):
|
||||
|
||||
|
||||
def safe_open(a, b):
|
||||
if DEMO_MODE and ('w' in b or 'a' in b):
|
||||
if (DEMO_MODE or is_gae) and ('w' in b or 'a' in b):
|
||||
class tmp:
|
||||
def write(self, data):
|
||||
pass
|
||||
def close(self):
|
||||
pass
|
||||
return tmp()
|
||||
return open(a, b)
|
||||
|
||||
@@ -230,7 +242,7 @@ def site():
|
||||
redirect(URL('design', args=appname))
|
||||
else:
|
||||
session.flash = \
|
||||
DIV(T('unable to create application "%s"' % appname),
|
||||
DIV(T('unable to create application "%s"', appname),
|
||||
PRE(error))
|
||||
redirect(URL(r=request))
|
||||
|
||||
@@ -341,7 +353,7 @@ def pack():
|
||||
response.headers['Content-Disposition'] = disposition
|
||||
return safe_read(filename, 'rb')
|
||||
else:
|
||||
session.flash = T('internal error: %s' % e)
|
||||
session.flash = T('internal error: %s', e)
|
||||
redirect(URL('site'))
|
||||
|
||||
def pack_plugin():
|
||||
@@ -375,7 +387,7 @@ def pack_custom():
|
||||
response.headers['Content-Disposition'] = disposition
|
||||
return safe_read(filename, 'rb')
|
||||
else:
|
||||
session.flash = T('internal error: %s' % e)
|
||||
session.flash = T('internal error: %s', e)
|
||||
redirect(URL(args=request.args))
|
||||
def ignore(fs):
|
||||
return [f for f in fs if not (
|
||||
@@ -563,36 +575,30 @@ def edit():
|
||||
# Load json only if it is ajax edited...
|
||||
app = get_app(request.vars.app)
|
||||
app_path = apath(app, r=request)
|
||||
editor_defaults={'theme':'web2py', 'editor': 'default'}
|
||||
preferences={'theme':'web2py', 'editor': 'default', 'closetag': 'true', 'codefolding': 'false', 'tabwidth':'4', 'indentwithtabs':'false', 'linenumbers':'true', 'highlightline':'true'}
|
||||
config = Config(os.path.join(request.folder, 'settings.cfg'),
|
||||
section='editor', default_values=editor_defaults)
|
||||
preferences = config.read()
|
||||
section='editor', default_values={})
|
||||
preferences.update(config.read())
|
||||
|
||||
if not(request.ajax):
|
||||
if not(request.ajax) and not(is_mobile):
|
||||
# return the scaffolding, the rest will be through ajax requests
|
||||
response.title = T('Editing %s') % app
|
||||
editarea_preferences = {}
|
||||
editarea_preferences['FONT_SIZE'] = '10'
|
||||
editarea_preferences['FULL_SCREEN'] = 'false'
|
||||
editarea_preferences['ALLOW_TOGGLE'] = 'true'
|
||||
editarea_preferences['REPLACE_TAB_BY_SPACES'] = '4'
|
||||
editarea_preferences['DISPLAY'] = 'onload'
|
||||
for key in editarea_preferences:
|
||||
if key in globals():
|
||||
editarea_preferences[key] = globals()[key]
|
||||
return response.render ('default/edit.html', dict(app=request.args[0], editor_settings=preferences, editarea_preferences=editarea_preferences))
|
||||
return response.render ('default/edit.html', dict(app=app, editor_settings=preferences))
|
||||
|
||||
# show settings tab and save prefernces
|
||||
if 'settings' in request.vars:
|
||||
if request.post_vars: #save new preferences
|
||||
if config.save(request.post_vars.items()):
|
||||
post_vars = request.post_vars.items()
|
||||
# Since unchecked checkbox are not serialized, we must set them as false by hand to store the correct preference in the settings
|
||||
post_vars+= [(opt, 'false') for opt in preferences if opt not in request.post_vars ]
|
||||
if config.save(post_vars):
|
||||
response.headers["web2py-component-flash"] = T('Preferences saved correctly')
|
||||
else:
|
||||
response.headers["web2py-component-flash"] = T('Preferences saved on session only')
|
||||
response.headers["web2py-component-command"] = "update_theme('%s');update_editor('%s');jQuery('a[href=#editor_settings] button.close').click();" % (config.read()['theme'], config.read()['editor'])
|
||||
response.headers["web2py-component-command"] = "update_editor(%s);$('a[href=#editor_settings] button.close').click();" % response.json(config.read())
|
||||
return
|
||||
else:
|
||||
details = {'filename':'settings', 'id':'editor_settings', 'force': False}
|
||||
details = {'realfilename':'settings', 'filename':'settings', 'id':'editor_settings', 'force': False}
|
||||
details['plain_html'] = response.render('default/editor_settings.html', {'editor_settings':preferences})
|
||||
return response.json(details)
|
||||
|
||||
@@ -600,7 +606,7 @@ def edit():
|
||||
# Load json only if it is ajax edited...
|
||||
app = get_app(request.vars.app)
|
||||
filename = '/'.join(request.args)
|
||||
response.title = request.args[-1]
|
||||
realfilename = request.args[-1]
|
||||
if request.vars.app:
|
||||
path = abspath(filename)
|
||||
else:
|
||||
@@ -615,7 +621,7 @@ def edit():
|
||||
elif filename[-4:] == '.css':
|
||||
filetype = 'css'
|
||||
elif filename[-3:] == '.js':
|
||||
filetype = 'js'
|
||||
filetype = 'javascript'
|
||||
else:
|
||||
filetype = 'html'
|
||||
|
||||
@@ -747,7 +753,7 @@ def edit():
|
||||
|
||||
if len(request.args) > 2 and request.args[1] == 'controllers':
|
||||
controller = (request.args[2])[:-3]
|
||||
functions = regex_expose.findall(data)
|
||||
functions = find_exposed_functions(data)
|
||||
else:
|
||||
(controller, functions) = (None, None)
|
||||
|
||||
@@ -755,7 +761,10 @@ def edit():
|
||||
return response.json({'file_hash': file_hash, 'saved_on': saved_on, 'functions': functions, 'controller': controller, 'application': request.args[0], 'highlight': highlight})
|
||||
else:
|
||||
file_details = dict(app=request.args[0],
|
||||
lineno=request.vars.lineno or 1,
|
||||
editor_settings=preferences,
|
||||
filename=filename,
|
||||
realfilename=realfilename,
|
||||
filetype=filetype,
|
||||
data=data,
|
||||
edit_controller=edit_controller,
|
||||
@@ -766,11 +775,61 @@ def edit():
|
||||
view_link=view_link,
|
||||
editviewlinks=editviewlinks,
|
||||
id=IS_SLUG()(filename)[0],
|
||||
force= True if (request.vars.restore or request.vars.revert) else False)
|
||||
force= True if (request.vars.restore or
|
||||
request.vars.revert) else False)
|
||||
plain_html = response.render('default/edit_js.html', file_details)
|
||||
file_details['plain_html'] = plain_html
|
||||
return response.json(file_details)
|
||||
if is_mobile:
|
||||
return response.render('default.mobile/edit.html',
|
||||
file_details, editor_settings=preferences)
|
||||
else:
|
||||
return response.json(file_details)
|
||||
|
||||
def todolist():
|
||||
""" Returns all TODO of the requested app
|
||||
"""
|
||||
app = request.vars.app or ''
|
||||
app_path = apath('%(app)s' % {'app':app}, r=request)
|
||||
dirs=['models', 'controllers', 'modules', 'private' ]
|
||||
def listfiles(app, dir, regexp='.*\.py$'):
|
||||
files = sorted( listdir(apath('%(app)s/%(dir)s/' % {'app':app, 'dir':dir}, r=request), regexp))
|
||||
files = [x.replace(os.path.sep, '/') for x in files if not x.endswith('.bak')]
|
||||
return files
|
||||
|
||||
pattern = '#\s*(todo)+\s+(.*)'
|
||||
regex = re.compile(pattern, re.IGNORECASE)
|
||||
|
||||
output = []
|
||||
for d in dirs:
|
||||
for f in listfiles(app, d):
|
||||
matches = []
|
||||
filename= apath(os.path.join(app, d, f), r=request)
|
||||
with open(filename, 'r') as f_s:
|
||||
src = f_s.read()
|
||||
for m in regex.finditer(src):
|
||||
start = m.start()
|
||||
lineno = src.count('\n', 0, start) + 1
|
||||
matches.append({'text':m.group(0), 'lineno':lineno})
|
||||
if len(matches) != 0:
|
||||
output.append({'filename':f,'matches':matches, 'dir':d})
|
||||
|
||||
return {'todo':output, 'app': app}
|
||||
|
||||
def editor_sessions():
|
||||
config = Config(os.path.join(request.folder, 'settings.cfg'),
|
||||
section='editor_sessions', default_values={})
|
||||
preferences = config.read()
|
||||
|
||||
if request.vars.session_name and request.vars.files:
|
||||
session_name = request.vars.session_name
|
||||
files = request.vars.files
|
||||
preferences.update({session_name:','.join(files)})
|
||||
if config.save(preferences.items()):
|
||||
response.headers["web2py-component-flash"] = T('Session saved correctly')
|
||||
else:
|
||||
response.headers["web2py-component-flash"] = T('Session saved on session only')
|
||||
|
||||
return response.render('default/editor_sessions.html', {'editor_sessions':preferences})
|
||||
|
||||
def resolve():
|
||||
"""
|
||||
@@ -1007,7 +1066,7 @@ def design():
|
||||
functions = {}
|
||||
for c in controllers:
|
||||
data = safe_read(apath('%s/controllers/%s' % (app, c), r=request))
|
||||
items = regex_expose.findall(data)
|
||||
items = find_exposed_functions(data)
|
||||
functions[c] = items
|
||||
|
||||
# Get all views
|
||||
@@ -1037,9 +1096,9 @@ def design():
|
||||
privates.sort()
|
||||
|
||||
# Get all static files
|
||||
MAXNFILES = 1000
|
||||
statics = listdir(apath('%s/static/' % app, r=request), '[^\.#].*')
|
||||
statics = [x.replace('\\', '/') for x in statics[:MAXNFILES]]
|
||||
statics = listdir(apath('%s/static/' % app, r=request), '[^\.#].*',
|
||||
maxnum = MAXNFILES)
|
||||
statics = [x.replace(os.path.sep, '/') for x in statics]
|
||||
statics.sort()
|
||||
|
||||
# Get all languages
|
||||
@@ -1051,11 +1110,12 @@ def design():
|
||||
|
||||
#Get crontab
|
||||
cronfolder = apath('%s/cron' % app, r=request)
|
||||
if not os.path.exists(cronfolder):
|
||||
os.mkdir(cronfolder)
|
||||
crontab = apath('%s/cron/crontab' % app, r=request)
|
||||
if not os.path.exists(crontab):
|
||||
safe_write(crontab, '#crontab')
|
||||
if not is_gae:
|
||||
if not os.path.exists(cronfolder):
|
||||
os.mkdir(cronfolder)
|
||||
if not os.path.exists(crontab):
|
||||
safe_write(crontab, '#crontab')
|
||||
|
||||
plugins = []
|
||||
|
||||
@@ -1144,7 +1204,7 @@ def plugin():
|
||||
functions = {}
|
||||
for c in controllers:
|
||||
data = safe_read(apath('%s/controllers/%s' % (app, c), r=request))
|
||||
items = regex_expose.findall(data)
|
||||
items = find_exposed_functions(data)
|
||||
functions[c] = items
|
||||
|
||||
# Get all views
|
||||
@@ -1173,8 +1233,9 @@ def plugin():
|
||||
privates.sort()
|
||||
|
||||
# Get all static files
|
||||
statics = listdir(apath('%s/static/' % app, r=request), '[^\.#].*')
|
||||
statics = [x.replace('\\', '/') for x in statics]
|
||||
statics = listdir(apath('%s/static/' % app, r=request), '[^\.#].*',
|
||||
maxnum = MAXNFILES)
|
||||
statics = [x.replace(os.path.sep, '/') for x in statics]
|
||||
statics.sort()
|
||||
|
||||
# Get all languages
|
||||
@@ -1206,7 +1267,6 @@ def plugin():
|
||||
languages=languages,
|
||||
crontab=crontab)
|
||||
|
||||
|
||||
def create_file():
|
||||
""" Create files handler """
|
||||
if request.vars and not request.vars.token == session.token:
|
||||
@@ -1217,6 +1277,8 @@ def create_file():
|
||||
app = get_app(request.vars.app)
|
||||
path = abspath(request.vars.location)
|
||||
else:
|
||||
if request.vars.dir:
|
||||
request.vars.location += request.vars.dir + '/'
|
||||
app = get_app(name=request.vars.location.split('/')[0])
|
||||
path = apath(request.vars.location, r=request)
|
||||
filename = re.sub('[^\w./-]+', '_', request.vars.filename)
|
||||
@@ -1325,7 +1387,8 @@ def create_file():
|
||||
from gluon import *\n""")[1:]
|
||||
|
||||
elif (path[-8:] == '/static/') or (path[-9:] == '/private/'):
|
||||
if request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin):
|
||||
if (request.vars.plugin and
|
||||
not filename.startswith('plugin_%s/' % request.vars.plugin)):
|
||||
filename = 'plugin_%s/%s' % (request.vars.plugin, filename)
|
||||
text = ''
|
||||
|
||||
@@ -1343,7 +1406,11 @@ def create_file():
|
||||
|
||||
safe_write(full_filename, text)
|
||||
log_progress(app, 'CREATE', filename)
|
||||
session.flash = T('file "%(filename)s" created',
|
||||
if request.vars.dir:
|
||||
result = T('file "%(filename)s" created',
|
||||
dict(filename=full_filename[len(path):]))
|
||||
else:
|
||||
session.flash = T('file "%(filename)s" created',
|
||||
dict(filename=full_filename[len(path):]))
|
||||
vars = {}
|
||||
if request.vars.id:
|
||||
@@ -1352,13 +1419,51 @@ def create_file():
|
||||
vars['app'] = request.vars.app
|
||||
redirect(URL('edit',
|
||||
args=[os.path.join(request.vars.location, filename)], vars=vars))
|
||||
|
||||
except Exception, e:
|
||||
if not isinstance(e, HTTP):
|
||||
session.flash = T('cannot create file')
|
||||
|
||||
redirect(request.vars.sender + anchor)
|
||||
if request.vars.dir:
|
||||
response.flash = result
|
||||
response.headers['web2py-component-content'] = 'append'
|
||||
response.headers['web2py-component-command'] = """
|
||||
$.web2py.invalidate('#files_menu');
|
||||
load_file('%s');
|
||||
$.web2py.enableElement($('#form form').find($.web2py.formInputClickSelector));
|
||||
""" % URL('edit', args=[app,request.vars.dir,filename])
|
||||
return ''
|
||||
else:
|
||||
redirect(request.vars.sender + anchor)
|
||||
|
||||
|
||||
def listfiles(app, dir, regexp='.*\.py$'):
|
||||
files = sorted(
|
||||
listdir(apath('%(app)s/%(dir)s/' % {'app':app, 'dir':dir}, r=request), regexp))
|
||||
files = [x.replace('\\', '/') for x in files if not x.endswith('.bak')]
|
||||
return files
|
||||
|
||||
def editfile(path,file,vars={}, app = None):
|
||||
args=(path,file) if 'app' in vars else (app,path,file)
|
||||
url = URL('edit', args=args, vars=vars)
|
||||
return A(file, _class='editor_filelink', _href=url, _style='word-wrap: nowrap;')
|
||||
|
||||
def files_menu():
|
||||
app = request.vars.app or 'welcome'
|
||||
dirs=[{'name':'models', 'reg':'.*\.py$'},
|
||||
{'name':'controllers', 'reg':'.*\.py$'},
|
||||
{'name':'views', 'reg':'[\w/\-]+(\.\w+)+$'},
|
||||
{'name':'modules', 'reg':'.*\.py$'},
|
||||
{'name':'static', 'reg': '[^\.#].*'}]
|
||||
result_files = []
|
||||
for dir in dirs:
|
||||
result_files.append(TAG[''](LI(dir['name'], _class="nav-header component", _onclick="collapse('" + dir['name'] + "_files');"),
|
||||
LI(UL(*[LI(editfile(dir['name'], f, dict(id=dir['name'] + f.replace('.','__')), app), _style="overflow:hidden", _id=dir['name']+"__"+f.replace('.','__'))
|
||||
for f in listfiles(app, dir['name'], regexp=dir['reg'])],
|
||||
_class="nav nav-list small-font"),
|
||||
_id=dir['name'] + '_files', _style="display: none;")))
|
||||
return dict(result_files = result_files)
|
||||
|
||||
def upload_file():
|
||||
""" File uploading handler """
|
||||
if request.vars and not request.vars.token == session.token:
|
||||
@@ -1418,8 +1523,11 @@ def errors():
|
||||
import hashlib
|
||||
|
||||
app = get_app()
|
||||
|
||||
method = request.args(1) or 'new'
|
||||
if is_gae:
|
||||
method = 'dbold' if ('old' in
|
||||
(request.args(1) or '')) else 'dbnew'
|
||||
else:
|
||||
method = request.args(1) or 'new'
|
||||
db_ready = {}
|
||||
db_ready['status'] = get_ticket_storage(app)
|
||||
db_ready['errmessage'] = T(
|
||||
@@ -1486,32 +1594,30 @@ def errors():
|
||||
for fn in tk_db(tk_table.id > 0).select():
|
||||
try:
|
||||
error = pickle.loads(fn.ticket_data)
|
||||
except AttributeError:
|
||||
hash = hashlib.md5(error['traceback']).hexdigest()
|
||||
|
||||
if hash in delete_hashes:
|
||||
tk_db(tk_table.id == fn.id).delete()
|
||||
tk_db.commit()
|
||||
else:
|
||||
try:
|
||||
hash2error[hash]['count'] += 1
|
||||
except KeyError:
|
||||
error_lines = error['traceback'].split("\n")
|
||||
last_line = error_lines[-2]
|
||||
error_causer = os.path.split(error['layer'])[1]
|
||||
hash2error[hash] = dict(count=1,
|
||||
pickel=error, causer=error_causer,
|
||||
last_line=last_line, hash=hash,
|
||||
ticket=fn.ticket_id)
|
||||
except AttributeError, e:
|
||||
tk_db(tk_table.id == fn.id).delete()
|
||||
tk_db.commit()
|
||||
|
||||
hash = hashlib.md5(error['traceback']).hexdigest()
|
||||
|
||||
if hash in delete_hashes:
|
||||
tk_db(tk_table.id == fn.id).delete()
|
||||
tk_db.commit()
|
||||
else:
|
||||
try:
|
||||
hash2error['hash']['count'] += 1
|
||||
except KeyError:
|
||||
error_lines = error['traceback'].split("\n")
|
||||
last_line = error_lines[-2]
|
||||
error_causer = os.path.split(error['layer'])[1]
|
||||
hash2error[hash] = dict(count=1, pickel=error,
|
||||
causer=error_causer,
|
||||
last_line=last_line,
|
||||
hash=hash, ticket=fn.ticket_id)
|
||||
|
||||
decorated = [(x['count'], x) for x in hash2error.values()]
|
||||
|
||||
decorated.sort(key=operator.itemgetter(0), reverse=True)
|
||||
|
||||
return dict(errors=[x[1] for x in decorated], app=app, method=method)
|
||||
return dict(errors=[x[1] for x in decorated], app=app,
|
||||
method=method, db_ready=db_ready)
|
||||
|
||||
elif method == 'dbold':
|
||||
tk_db, tk_table = get_ticket_storage(app)
|
||||
@@ -1519,16 +1625,18 @@ def errors():
|
||||
if item[:7] == 'delete_':
|
||||
tk_db(tk_table.ticket_id == item[7:]).delete()
|
||||
tk_db.commit()
|
||||
tickets_ = tk_db(tk_table.id > 0).select(tk_table.ticket_id, tk_table.created_datetime, orderby=~tk_table.created_datetime)
|
||||
tickets_ = tk_db(tk_table.id > 0).select(tk_table.ticket_id,
|
||||
tk_table.created_datetime,
|
||||
orderby=~tk_table.created_datetime)
|
||||
tickets = [row.ticket_id for row in tickets_]
|
||||
times = dict(
|
||||
[(row.ticket_id, row.created_datetime) for row in tickets_])
|
||||
|
||||
return dict(app=app, tickets=tickets, method=method, times=times)
|
||||
times = dict([(row.ticket_id, row.created_datetime) for
|
||||
row in tickets_])
|
||||
return dict(app=app, tickets=tickets, method=method,
|
||||
times=times, db_ready=db_ready)
|
||||
|
||||
else:
|
||||
for item in request.vars:
|
||||
# delete_all} rows doesn't contain any ticket
|
||||
# delete_all rows doesn't contain any ticket
|
||||
# Remove anything else as requested
|
||||
if item[:7] == 'delete_' and (not item == "delete_all}"):
|
||||
os.unlink(apath('%s/errors/%s' % (app, item[7:]), r=request))
|
||||
@@ -1548,6 +1656,9 @@ def get_ticket_storage(app):
|
||||
if os.path.exists(ticket_file):
|
||||
db_string = open(ticket_file).read()
|
||||
db_string = db_string.strip().replace('\r', '').replace('\n', '')
|
||||
elif is_gae:
|
||||
# use Datastore as fallback if there is no ticket_file
|
||||
db_string = "google:datastore"
|
||||
else:
|
||||
return False
|
||||
tickets_table = 'web2py_ticket'
|
||||
@@ -1791,3 +1902,42 @@ def git_push():
|
||||
session.flash = T("Push failed, there are unmerged entries in the cache. Resolve merge issues manually and try again.")
|
||||
redirect(URL('site'))
|
||||
return dict(app=app, form=form)
|
||||
|
||||
def plugins():
|
||||
app = request.args(0)
|
||||
from serializers import loads_json
|
||||
if not session.plugins:
|
||||
try:
|
||||
rawlist = urllib.urlopen("http://www.web2pyslices.com/" +
|
||||
"public/api.json/action/list/content/Package?package" +
|
||||
"_type=plugin&search_index=false").read()
|
||||
session.plugins = loads_json(rawlist)
|
||||
except:
|
||||
response.flash = T('Unable to download the list of plugins')
|
||||
session.plugins = []
|
||||
return dict(plugins=session.plugins["results"], app=request.args(0))
|
||||
|
||||
def install_plugin():
|
||||
app = request.args(0)
|
||||
source = request.vars.source
|
||||
plugin = request.vars.plugin
|
||||
if not (source and app):
|
||||
raise HTTP(500, T("Invalid request"))
|
||||
form = SQLFORM.factory()
|
||||
result = None
|
||||
if form.process().accepted:
|
||||
# get w2p plugin
|
||||
if "web2py.plugin." in source:
|
||||
filename = "web2py.plugin.%s.w2p" % \
|
||||
source.split("web2py.plugin.")[-1].split(".w2p")[0]
|
||||
else:
|
||||
filename = "web2py.plugin.%s.w2p" % cleanpath(plugin)
|
||||
if plugin_install(app, urllib.urlopen(source),
|
||||
request, filename):
|
||||
session.flash = T('New plugin installed: %s', filename)
|
||||
else:
|
||||
session.flash = \
|
||||
T('unable to install plugin "%s"', filename)
|
||||
redirect(URL(f="plugins", args=[app,]))
|
||||
return dict(form=form, app=app, plugin=plugin, source=source)
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import cStringIO
|
||||
import gluon.contrib.shell
|
||||
import code
|
||||
import thread
|
||||
import cgi
|
||||
from gluon.shell import env
|
||||
|
||||
if DEMO_MODE or MULTI_USER_MODE:
|
||||
@@ -40,7 +41,7 @@ def callback():
|
||||
k = len(session['commands:' + app]) - 1
|
||||
#output = PRE(output)
|
||||
#return TABLE(TR('In[%i]:'%k,PRE(command)),TR('Out[%i]:'%k,output))
|
||||
return 'In [%i] : %s%s\n' % (k + 1, command, output)
|
||||
return cgi.escape('In [%i] : %s%s\n' % (k + 1, command, output))
|
||||
|
||||
|
||||
def reset():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# coding: utf8
|
||||
# -*- coding: utf-8 -*-
|
||||
{
|
||||
'!langcode!': 'es',
|
||||
'!langname!': 'Español',
|
||||
@@ -9,8 +9,10 @@
|
||||
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
|
||||
'(requires internet access, experimental)': '(requiere acceso a internet, experimental)',
|
||||
'(something like "it-it")': '(algo como "it-it")',
|
||||
'(version %s)': '(version %s)',
|
||||
'@markmin\x01(file **gluon/contrib/plural_rules/%s.py** is not found)': '(file **gluon/contrib/plural_rules/%s.py** is not found)',
|
||||
'@markmin\x01An error occured, please [[reload %s]] the page': 'An error occured, please [[reload %s]] the page',
|
||||
'@markmin\x01Number of entries: **%s**': 'Number of entries: **%s**',
|
||||
'@markmin\x01Searching: **%s** %%{file}': 'Searching: **%s** files',
|
||||
'A new version of web2py is available': 'Hay una nueva versión de web2py disponible',
|
||||
'A new version of web2py is available: %s': 'Hay una nueva versión de web2py disponible: %s',
|
||||
@@ -29,11 +31,13 @@
|
||||
'An error occured, please %s the page': 'Ha ocurrido un error, por favor %s la página',
|
||||
'and rename it (required):': 'y renombrela (requerido):',
|
||||
'and rename it:': ' y renombrelo:',
|
||||
'App does not exist or you are not authorized': 'App does not exist or you are not authorized',
|
||||
'appadmin': 'appadmin',
|
||||
'appadmin is disabled because insecure channel': 'admin deshabilitado, el canal no es seguro',
|
||||
'application "%s" uninstalled': 'aplicación "%s" desinstalada',
|
||||
'application %(appname)s installed with md5sum: %(digest)s': 'application %(appname)s installed with md5sum: %(digest)s',
|
||||
'application compiled': 'aplicación compilada',
|
||||
'Application exists already': 'Application exists already',
|
||||
'application is compiled and cannot be designed': 'la aplicación está compilada y no puede ser modificada',
|
||||
'Application name:': 'Nombre de la aplicación:',
|
||||
'are not used': 'are not used',
|
||||
@@ -44,6 +48,7 @@
|
||||
'Are you sure you want to uninstall application "%s"': '¿Está seguro que desea desinstalar la aplicación "%s"',
|
||||
'Are you sure you want to uninstall application "%s"?': '¿Está seguro que desea desinstalar la aplicación "%s"?',
|
||||
'Are you sure you want to upgrade web2py now?': '¿Está seguro que desea actualizar web2py ahora?',
|
||||
'Are you sure?': 'Are you sure?',
|
||||
'arguments': 'argumentos',
|
||||
'at char %s': 'en el caracter %s',
|
||||
'at line %s': 'en la línea %s',
|
||||
@@ -53,13 +58,17 @@
|
||||
'Autocomplete': 'Autocomplete',
|
||||
'Autocomplete Python Code': 'Autocompletar código Python',
|
||||
'Available databases and tables': 'Bases de datos y tablas disponibles',
|
||||
'Available Databases and Tables': 'Available Databases and Tables',
|
||||
'back': 'atrás',
|
||||
'Back to the plugins list': 'Back to the plugins list',
|
||||
'breakpoint': 'breakpoint',
|
||||
'breakpoints': 'breakpoints',
|
||||
'browse': 'buscar',
|
||||
'Cache': 'Cache',
|
||||
'cache': 'cache',
|
||||
'cache, errors and sessions cleaned': 'cache, errores y sesiones eliminados',
|
||||
'can be a git repo': 'puede ser un repositorio git',
|
||||
'Cancel': 'Cancel',
|
||||
'Cannot be empty': 'No puede estar vacío',
|
||||
'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'No se puede compilar: hay errores en su aplicación. Depure, corrija errores y vuelva a intentarlo.',
|
||||
'Cannot compile: there are errors in your app:': 'No se puede compilar: hay errores en su aplicación:',
|
||||
@@ -73,6 +82,9 @@
|
||||
'Check to delete': 'Marque para eliminar',
|
||||
'Checking for upgrades...': 'Buscando actulizaciones...',
|
||||
'Clean': 'limpiar',
|
||||
'Clear CACHE?': 'Clear CACHE?',
|
||||
'Clear DISK': 'Clear DISK',
|
||||
'Clear RAM': 'Clear RAM',
|
||||
'click here for online examples': 'haga clic aquí para ver ejemplos en línea',
|
||||
'click here for the administrative interface': 'haga clic aquí para usar la interfaz administrativa',
|
||||
'Click row to expand traceback': 'Click row to expand traceback',
|
||||
@@ -107,6 +119,7 @@
|
||||
'database': 'base de datos',
|
||||
'database %s select': 'selección en base de datos %s',
|
||||
'database administration': 'administración base de datos',
|
||||
'Database Administration (appadmin)': 'Database Administration (appadmin)',
|
||||
'Date and Time': 'Fecha y Hora',
|
||||
'db': 'db',
|
||||
'Debug': 'Debug',
|
||||
@@ -117,6 +130,7 @@
|
||||
'delete plugin': 'eliminar plugin',
|
||||
'Delete this file (you will be asked to confirm deletion)': 'Elimine este fichero (se le pedirá confirmación)',
|
||||
'Delete:': 'Elimine:',
|
||||
'Demo': 'Demo',
|
||||
'Deploy': 'Deploy',
|
||||
'Deploy on Google App Engine': 'Instale en Google App Engine',
|
||||
'Deploy to OpenShift': 'Instale en OpenShift',
|
||||
@@ -128,7 +142,10 @@
|
||||
'details': 'detalles',
|
||||
'direction: ltr': 'direction: ltr',
|
||||
'Disable': 'Deshabilitar',
|
||||
'DISK': 'DISK',
|
||||
'docs': 'docs',
|
||||
'Docs': 'Docs',
|
||||
'Done!': 'Done!',
|
||||
'done!': 'listo!',
|
||||
'Download': 'Descargar',
|
||||
'download files via http:': 'descargar archivos via http:',
|
||||
@@ -143,6 +160,7 @@
|
||||
'Edit current record': 'Edite el registro actual',
|
||||
'Edit Profile': 'Editar Perfil',
|
||||
'edit views:': 'editar vistas:',
|
||||
'Editing %s': 'Editing %s',
|
||||
'Editing file': 'Editando archivo',
|
||||
'Editing file "%s"': 'Editando archivo "%s"',
|
||||
'Editing Language file': 'Editando archivo de lenguaje',
|
||||
@@ -150,13 +168,16 @@
|
||||
'Editing myemail': 'Editing myemail',
|
||||
'Editing rbare': 'Editing rbare',
|
||||
'Editing ul': 'Editing ul',
|
||||
'Enable': 'Enable',
|
||||
'Enterprise Web Framework': 'Armazón Empresarial para Internet',
|
||||
'Error': 'Error',
|
||||
'Error logs for "%(app)s"': 'Bitácora de errores en "%(app)s"',
|
||||
'Error snapshot': 'Error snapshot',
|
||||
'Error ticket': 'Error ticket',
|
||||
'Errors': 'errores',
|
||||
'Errors in form, please check it out.': 'Errors in form, please check it out.',
|
||||
'Exception instance attributes': 'Atributos de la instancia de Excepción',
|
||||
'Exit Fullscreen': 'Exit Fullscreen',
|
||||
'Expand Abbreviation': 'Expand Abbreviation',
|
||||
'export as csv file': 'exportar como archivo CSV',
|
||||
'exposes': 'expone',
|
||||
@@ -181,30 +202,38 @@
|
||||
'First name': 'Nombre',
|
||||
'Frames': 'Frames',
|
||||
'Functions with no doctests will result in [passed] tests.': 'Funciones sin doctests equivalen a pruebas [aceptadas].',
|
||||
'Git Pull': 'Git Pull',
|
||||
'Git Push': 'Git Push',
|
||||
'Globals##debug': 'Globals',
|
||||
'graph model': 'graph model',
|
||||
'Group ID': 'ID de Grupo',
|
||||
'Hello World': 'Hola Mundo',
|
||||
'Help': 'ayuda',
|
||||
'here': 'here',
|
||||
'htmledit': 'htmledit',
|
||||
'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'Si el reporte anterior contiene un número de tiquete este indica un falla en la ejecución del controlador, antes de cualquier intento de ejecutat doctests. Esto generalmente se debe a un error en la indentación o un error por fuera del código de la función.\r\nUn titulo verde indica que todas las pruebas pasaron (si existen). En dicho caso los resultados no se muestran.',
|
||||
'Image': 'Image',
|
||||
'Import/Export': 'Importar/Exportar',
|
||||
'includes': 'incluye',
|
||||
'insert new': 'inserte nuevo',
|
||||
'insert new %s': 'inserte nuevo %s',
|
||||
'inspect attributes': 'inspect attributes',
|
||||
'Install': 'instalar',
|
||||
'Installation of %(plugin)s for %(app)s': 'Installation of %(plugin)s for %(app)s',
|
||||
'Installation of %(plugin)s for %(app)s app': 'Installation of %(plugin)s for %(app)s app',
|
||||
'Installed applications': 'Aplicaciones instaladas',
|
||||
'Interaction at %s line %s': 'Interaction at %s line %s',
|
||||
'Interactive console': 'Interactive console',
|
||||
'internal error': 'error interno',
|
||||
'Internal State': 'Estado Interno',
|
||||
'Invalid action': 'Acción inválida',
|
||||
'Invalid application name': 'Invalid application name',
|
||||
'Invalid email': 'Correo inválido',
|
||||
'invalid password': 'contraseña inválida',
|
||||
'invalid password.': 'invalid password.',
|
||||
'Invalid Query': 'Consulta inválida',
|
||||
'invalid request': 'solicitud inválida',
|
||||
'Invalid request': 'Invalid request',
|
||||
'invalid ticket': 'tiquete inválido',
|
||||
'Key bindings': 'Key bindings',
|
||||
'Key bindings for ZenCoding Plugin': 'Key bindings for ZenCoding Plugin',
|
||||
@@ -216,6 +245,8 @@
|
||||
'Last name': 'Apellido',
|
||||
'Last saved on:': 'Guardado en:',
|
||||
'License for': 'Licencia para',
|
||||
'License:': 'License:',
|
||||
'lists by ticket': 'lists by ticket',
|
||||
'loading...': 'cargando...',
|
||||
'locals': 'locals',
|
||||
'Locals##debug': 'Locals',
|
||||
@@ -226,6 +257,7 @@
|
||||
'Lost Password': 'Contraseña perdida',
|
||||
'manage': 'gestionar',
|
||||
'Manage': 'Gestionar',
|
||||
'Manage Cache': 'Manage Cache',
|
||||
'merge': 'combinar',
|
||||
'Models': 'Modelos',
|
||||
'models': 'modelos',
|
||||
@@ -235,6 +267,11 @@
|
||||
'new application "%s" created': 'nueva aplicación "%s" creada',
|
||||
'New application wizard': 'Asistente para nueva aplicación',
|
||||
'new plugin installed': 'nuevo plugin instalado',
|
||||
'New plugin installed: %s': 'New plugin installed: %s',
|
||||
'New plugin installed: web2py.plugin.attachment.w2p': 'New plugin installed: web2py.plugin.attachment.w2p',
|
||||
'New plugin installed: web2py.plugin.dialog.w2p': 'New plugin installed: web2py.plugin.dialog.w2p',
|
||||
'New plugin installed: web2py.plugin.math2py.w2p': 'New plugin installed: web2py.plugin.math2py.w2p',
|
||||
'New plugin installed: web2py.plugin.timezone.w2p': 'New plugin installed: web2py.plugin.timezone.w2p',
|
||||
'New Record': 'Registro nuevo',
|
||||
'new record inserted': 'nuevo registro insertado',
|
||||
'New simple application': 'Nueva aplicación',
|
||||
@@ -254,6 +291,7 @@
|
||||
'or provide application url:': 'o provea URL de la aplicación:',
|
||||
'Origin': 'Origen',
|
||||
'Original/Translation': 'Original/Traducción',
|
||||
'Overview': 'Overview',
|
||||
'Overwrite installed app': 'sobreescriba la aplicación instalada',
|
||||
'Pack all': 'empaquetar todo',
|
||||
'Pack compiled': 'empaquete compiladas',
|
||||
@@ -264,8 +302,10 @@
|
||||
'password changed': 'contraseña cambiada',
|
||||
'Peeking at file': 'Visualizando archivo',
|
||||
'Please': 'Please',
|
||||
'Plugin': 'Plugin',
|
||||
'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" eliminado',
|
||||
'Plugin "%s" in application': 'Plugin "%s" en aplicación',
|
||||
'Plugin page': 'Plugin page',
|
||||
'plugins': 'plugins',
|
||||
'Plugins': 'Plugins',
|
||||
'Plural-Forms:': 'Plural-Forms:',
|
||||
@@ -273,7 +313,9 @@
|
||||
'previous 100 rows': '100 filas anteriores',
|
||||
'Private files': 'Archivos privados',
|
||||
'private files': 'archivos privados',
|
||||
'Project Progress': 'Project Progress',
|
||||
'Query:': 'Consulta:',
|
||||
'RAM': 'RAM',
|
||||
'Rapid Search': 'Rapid Search',
|
||||
'record': 'registro',
|
||||
'record does not exist': 'el registro no existe',
|
||||
@@ -288,6 +330,8 @@
|
||||
'Removed Breakpoint on %s at line %s': 'Eliminado punto de ruptura en %s en la línea %s',
|
||||
'Replace': 'Reemplazar',
|
||||
'Replace All': 'Reemplazar todos',
|
||||
'Repository (%s)': 'Repository (%s)',
|
||||
'Repository: %s': 'Repository: %s',
|
||||
'request': 'request',
|
||||
'Resolve Conflict file': 'archivo Resolución de Conflicto',
|
||||
'response': 'response',
|
||||
@@ -307,6 +351,8 @@
|
||||
'Save file: %s': 'Guardar: %s',
|
||||
'Save via Ajax': 'Guardar via Ajax',
|
||||
'Saved file hash:': 'Hash del archivo guardado:',
|
||||
'Screenshot %s': 'Screenshot %s',
|
||||
'Screenshots': 'Screenshots',
|
||||
'selected': 'seleccionado(s)',
|
||||
'session': 'session',
|
||||
'session expired': 'sesión expirada',
|
||||
@@ -314,25 +360,29 @@
|
||||
'shell': 'shell',
|
||||
'Site': 'sitio',
|
||||
'some files could not be removed': 'algunos archivos no pudieron ser removidos',
|
||||
'source : filesystem': 'source : filesystem',
|
||||
'Start searching': 'Iniciar búsqueda',
|
||||
'Start wizard': 'Iniciar asistente',
|
||||
'state': 'estado',
|
||||
'Static': 'Static',
|
||||
'static': 'estáticos',
|
||||
'Static files': 'Archivos estáticos',
|
||||
'Statistics': 'Statistics',
|
||||
'step': 'step',
|
||||
'stop': 'stop',
|
||||
'submit': 'enviar',
|
||||
'Submit': 'Submit',
|
||||
'Success!': 'Success!',
|
||||
'successful': 'exitoso',
|
||||
'Sure you want to delete this object?': '¿Está seguro que desea eliminar este objeto?',
|
||||
'switch to : db': 'switch to : db',
|
||||
'table': 'tabla',
|
||||
'Table name': 'Nombre de la tabla',
|
||||
'test': 'probar',
|
||||
'Testing application': 'Probando aplicación',
|
||||
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "consulta" es una condición como "db.tabla1.campo1==\'valor\'". Algo como "db.tabla1.campo1==db.tabla2.campo2" resulta en un JOIN SQL.',
|
||||
'the application logic, each URL path is mapped in one exposed function in the controller': 'la lógica de la aplicación, cada ruta URL se mapea en una función expuesta en el controlador',
|
||||
'The application logic, each URL path is mapped in one exposed function in the controller': 'La lógica de la aplicación, cada ruta URL se mapea en una función expuesta en el controlador',
|
||||
'the application logic, each URL path is mapped in one exposed function in the controller': 'la lógica de la aplicación, cada ruta URL se mapea en una función expuesta en el controlador',
|
||||
'the data representation, define database tables and sets': 'la representación de datos, define tablas y conjuntos de base de datos',
|
||||
'The data representation, define database tables and sets': 'La representación de datos, define tablas y conjuntos de base de datos',
|
||||
'The presentations layer, views are also known as templates': 'La capa de presentación, las vistas también son llamadas plantillas',
|
||||
@@ -359,6 +409,7 @@
|
||||
'To emulate a breakpoint programatically, write:': 'To emulate a breakpoint programatically, write:',
|
||||
'to use the debugger!': 'to use the debugger!',
|
||||
'toggle breakpoint': 'alternar punto de ruptura',
|
||||
'Toggle comment': 'Toggle comment',
|
||||
'Toggle Fullscreen': 'Alternar pantalla completa',
|
||||
'Traceback': 'Traceback',
|
||||
'translation strings for the application': 'cadenas de caracteres de traducción para la aplicación',
|
||||
@@ -410,6 +461,8 @@
|
||||
'web2py upgraded; please restart it': 'web2py actualizado; favor reiniciar',
|
||||
'Welcome to web2py': 'Bienvenido a web2py',
|
||||
'YES': 'SI',
|
||||
'Yes': 'Yes',
|
||||
'You are going to install': 'You are going to install',
|
||||
'You need to set up and reach a': 'You need to set up and reach a',
|
||||
'Your application will be blocked until you click an action button (next, step, continue, etc.)': 'Your application will be blocked until you click an action button (next, step, continue, etc.)',
|
||||
'Your can inspect variables using the console below': 'Your can inspect variables using the console below',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# coding: utf8
|
||||
# -*- coding: utf-8 -*-
|
||||
{
|
||||
'!langcode!': 'it',
|
||||
'!langname!': 'Italiano',
|
||||
@@ -303,6 +303,7 @@
|
||||
'to previous version.': 'torna a versione precedente',
|
||||
'To create a plugin, name a file/folder plugin_[name]': 'Per creare un plugin, chiamare un file o cartella plugin_[nome]',
|
||||
'toggle breakpoint': 'toggle breakpoint',
|
||||
'Toggle comment': 'Toggle comment',
|
||||
'Toggle Fullscreen': 'Toggle Fullscreen',
|
||||
'Traceback': 'Traceback',
|
||||
'translation strings for the application': "stringhe di traduzioni per l'applicazione",
|
||||
|
||||
@@ -185,8 +185,8 @@
|
||||
'Invalid Query': 'Неверный запрос',
|
||||
'invalid request': 'неверный запрос',
|
||||
'invalid ticket': 'неверный тикет',
|
||||
'Key bindings': 'Связываник клавиш',
|
||||
'Key bindings for ZenConding Plugin': 'Связывание клавиш для плагина ZenConding',
|
||||
'Key bindings': 'Комбинации клавиш',
|
||||
'Key bindings for ZenConding Plugin': 'Комбинации клавиш для плагина ZenConding',
|
||||
'language file "%(filename)s" created/updated': 'Языковой файл "%(filename)s" создан/обновлен',
|
||||
'Language files (static strings) updated': 'Языковые файлы (статичные строки) обновлены',
|
||||
'languages': 'языки',
|
||||
@@ -204,7 +204,7 @@
|
||||
'Login to the Administrative Interface': 'Вход в интерфейс администратора',
|
||||
'Logout': 'выход',
|
||||
'Lost Password': 'Забыли пароль',
|
||||
'lost password?': 'Пароль утерен?',
|
||||
'lost password?': 'Пароль утерян?',
|
||||
'Main Menu': 'Главное меню',
|
||||
'Match Pair': 'Найти пару',
|
||||
'Menu Model': 'Модель меню',
|
||||
|
||||
426
applications/admin/languages/tr.py
Normal file
426
applications/admin/languages/tr.py
Normal file
@@ -0,0 +1,426 @@
|
||||
# coding: utf-8
|
||||
{
|
||||
'!langcode!': 'tr',
|
||||
'!langname!': 'Türkçe',
|
||||
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"güncelleme" ("update") "field1 = \'yenideğer\'" gibi seçeneğe bağlı bir ifadedir. JOIN sonuçlarını silemez veya silemezsiniz.',
|
||||
'%s %%{row} deleted': '%s %%{row} silindi',
|
||||
'%s %%{row} updated': '%s %%{row} güncellendi',
|
||||
'%Y-%m-%d': '%d-%m-%Y',
|
||||
'%Y-%m-%d %H:%M:%S': '%d-%m-%Y %H:%M:%S',
|
||||
'(requires internet access)': '(Internet erişimi gerekir)',
|
||||
'(requires internet access, experimental)': '(internet erişimi gerekir, deneysel)',
|
||||
'(something like "it-it")': '("it-it" şeklinde birşeyler) ',
|
||||
'1: Setting Parameters': '1: Parametrelerin Yapılandırılması',
|
||||
'@markmin\x01An error occured, please [[reload %s]] the page': '@markmin\x01Bir hata oluştu, lütfen sayfayı [[reload %s]]',
|
||||
"@markmin\x01Mercurial Version Control System Interface[[NEWLINE]]for application '%s'": "'%s' uygulaması için[[NEWLINE]]Mercurial Sürüm Kontrol Sistemi Arayüzü",
|
||||
'@markmin\x01Searching: **%s** %%{file}': '@markmin\x01Aranıyor: **%s** %%{file}',
|
||||
'A new version of web2py is available: %s': "web2py'nin yeni sürümü mevcut: %s ",
|
||||
'A new version of web2py is available: Version 1.68.2 (2009-10-21 09:59:29)\n': "web2py'nin yeni sürümü mevcut: Sürüm 1.68.2 (2009-10-21 09:59:29)\r\n",
|
||||
'About': 'Hakkında',
|
||||
'About application': 'Uygulama hakkında',
|
||||
'Add breakpoint': 'Kesme noktası ekle',
|
||||
'additional code for your application': 'uygulamanız için fazladan kod',
|
||||
'Additional code for your application': 'Uygulamanız için fazladan kod',
|
||||
'Admin design page': 'Yönetici tasarım sayfası',
|
||||
'admin disabled because no admin password': 'yönetici parolası olmadığından admin etkinsiz',
|
||||
'admin disabled because not supported on google app engine': 'Google App Motoru tafaından desteklenmediğinden admin etkinsizleştirildi',
|
||||
'admin disabled because unable to access password file': 'parola dosyasına erişielemdiğinden admin etkinsizleştirildi',
|
||||
'Admin is disabled because insecure channel': 'güvenzis kanal olduğundan admin etkinsizleştirildi',
|
||||
'Admin language': 'Admin dilleri',
|
||||
'Admin versioning page': 'Yönetici sürümleme sayfası',
|
||||
'administrative interface': 'yönetsel arayüz',
|
||||
'Administrator Password:': 'Yönetici Parolası:',
|
||||
'and rename it (required):': 've yeniden adlandır (gerekli):',
|
||||
'and rename it:': 'yeniden adlandır:',
|
||||
'appadmin': 'appadmin',
|
||||
'appadmin is disabled because insecure channel': 'güvenzis kanal olduğundan admin etkinsizleştirildi',
|
||||
'Application': 'Uygulama',
|
||||
'application "%s" uninstalled': '"%s" uygulaması kaldırıldı',
|
||||
'application %(appname)s installed with md5sum: %(digest)s': '%(appname)s uygulaması md5sum %(digest)s ile kuruldu',
|
||||
'application compiled': 'uygulama derlendi',
|
||||
'application is compiled and cannot be designed': 'uygulama derlenmiş ve tasarlanamaz',
|
||||
'Application name:': 'Uygulama adı:',
|
||||
'are not used': 'kullanılamıyor',
|
||||
'are not used yet': 'şimdilik kullanılamıyor',
|
||||
'Are you sure you want to delete file "%s"?': '«%s» dosyasını silmek istediğinize emin misiniz?',
|
||||
'Are you sure you want to delete plugin "%s"?': '"%s" eklentisini kaldırmak istediğinizden emin misiniz?',
|
||||
'Are you sure you want to delete this object?': 'Bu nesneyi silmek istediğinizden emin misiniz?',
|
||||
'Are you sure you want to uninstall application "%s"?': '«%s» uygulamasını kaldırmak istediğinizden emin misiniz?',
|
||||
'Are you sure you want to upgrade web2py now?': "web2py'yi güncellemek istediğinizden emin misiniz?",
|
||||
'arguments': 'argümanlar',
|
||||
'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'UYARI: Giriş günceli bağlantı (HTTPS) gerektirmekte veya yerel makinada çalışılmalıdır.',
|
||||
'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'UYARI: ÇOKLU TEST GÜVENLİ DEĞİL. BİRDEN ÇOK TESTİ AYNI ANDA YAPMAYIN.',
|
||||
'ATTENTION: you cannot edit the running application!': 'UYARI: çalışan uygulamayı düzenleyemezsiniz!',
|
||||
'Autocomplete Python Code': 'Python Kodlarını Otomatik Tamamla',
|
||||
'Available databases and tables': 'Kullanılabilir veritabanları ve tablolar',
|
||||
'back': 'geri',
|
||||
'Back to wizard': 'Sihirbaza geri dön',
|
||||
'Basics': 'Temeller',
|
||||
'Begin': 'Başla',
|
||||
'breakpoint': 'kesme noktası',
|
||||
'Breakpoints': 'Kesme Noktaları',
|
||||
'breakpoints': 'kesme noktaları',
|
||||
'cache': 'zula',
|
||||
'cache, errors and sessions cleaned': 'zula, hatalar ve oturumlar temizlendi',
|
||||
'can be a git repo': 'git deposu olabilir',
|
||||
'Cancel': 'Vazgeç',
|
||||
'Cannot be empty': 'Boş olamaz',
|
||||
'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Derlenemiyor: uygulamanızda hata(lar) var. Hataları düzeltin ve tekrar deneyin.',
|
||||
'Cannot compile: there are errors in your app:': 'Derlenemiyor: uygulamanızda hata(lar) var:',
|
||||
'cannot create file': 'dosya oluşturulamıyor',
|
||||
'cannot upload file "%(filename)s"': '"%(filename)s" dosyalarını yükleyemiyor',
|
||||
'Change admin password': 'admin parolasını değiştir',
|
||||
'change editor settings': 'düzenleyici ayarlarını değiştir',
|
||||
'check all': 'tümünü kontrol et',
|
||||
'Check for upgrades': 'Güncellemeleri kontrol et',
|
||||
'Check to delete': 'Silmek için kontrok et',
|
||||
'Checking for upgrades...': 'Güncellemeler denetleniyor ... ',
|
||||
'Clean': 'Temizle',
|
||||
'Click row to expand traceback': 'Takibi genişletmek için satır üzerine tıkla',
|
||||
'click to check for upgrades': 'güncellemeleri denetlemek için tıklayın',
|
||||
'code': 'kod',
|
||||
'collapse/expand all': 'sıkıştır/tümünü aç',
|
||||
'Comment:': 'Yorum:',
|
||||
'Commit': 'Öneri',
|
||||
'Commit form': 'Tarafından öneri',
|
||||
'Compile': 'Derle',
|
||||
'compiled application removed': 'derlenmiş uygulama kaldırıldı',
|
||||
'Condition': 'Durum',
|
||||
'Controllers': 'Denetçiler',
|
||||
'controllers': 'denetçiler',
|
||||
'Count': 'Sayı',
|
||||
'Create': 'Oluştur',
|
||||
'create file with filename:': 'dosya adı ile dosya oluştur:',
|
||||
'create new application:': 'yeni uygulama oluştur:',
|
||||
'Create new simple application': 'Yeni basit uygulama oluştur',
|
||||
'Create/Upload': 'Oluştur/Yükle',
|
||||
'created by': 'yazan:',
|
||||
'crontab': 'krontab',
|
||||
'Current request': 'Şimdiki istek',
|
||||
'Current response': 'Şimdiki yanıt',
|
||||
'Current session': 'Şimdiki oturum',
|
||||
'currently running': 'şimdiki çalışan',
|
||||
'currently saved or': 'şimdiki kaydedilen veya',
|
||||
'data uploaded': 'veri yüklendi',
|
||||
'database': 'veritabı',
|
||||
'database %s select': '%s veritabanı seçildi',
|
||||
'Database administration': 'Veritabanı yönetimi',
|
||||
'database administration': 'veritabı yönetimi',
|
||||
'Date and Time': 'Tarih ve Zaman',
|
||||
'db': 'db',
|
||||
'Debug': 'Hata Ayıkla',
|
||||
'defines tables': 'tablolar tanımlı',
|
||||
'Delete': 'Sil',
|
||||
'delete': 'sil',
|
||||
'delete all checked': 'tüm kontrol edilenleri sil',
|
||||
'delete plugin': ' eklentiyi sil',
|
||||
'Delete this file (you will be asked to confirm deletion)': 'Bu dosyayı sil (silmek için onay istenecek)',
|
||||
'Delete:': 'Sil:',
|
||||
'deleted after first hit': 'ilk vuruşta silinir',
|
||||
'Deploy': 'Yayımla',
|
||||
'Deploy on Google App Engine': 'Google App Motorunda Yayınla',
|
||||
'Deploy to OpenShift': "OpenShift'e Yayınla ",
|
||||
'Deployment form': 'Yayınlama formu',
|
||||
'design': 'tadarla',
|
||||
'Detailed traceback description': 'Ayrıntılı nedenin bulma tanımı',
|
||||
'direction: ltr': 'yön: ltr',
|
||||
'Disable': 'Devre Dışı',
|
||||
'docs': 'dokümanlar',
|
||||
'done!': 'bitti!',
|
||||
'Download .w2p': '.w2p İndir',
|
||||
'download layouts': 'düzenleri indir',
|
||||
'download plugins': 'eklentileri indir',
|
||||
'EDIT': 'DÜZENLE',
|
||||
'Edit': 'Düzenle',
|
||||
'edit all': 'tümünü düzenle',
|
||||
'Edit application': 'Uygulamayı düzenle',
|
||||
'edit controller': 'denetçiyi düzenle',
|
||||
'edit controller:': 'denetçiyi düzenle:',
|
||||
'Edit current record': 'Şimdiki kaydı düzenle',
|
||||
'edit views:': 'görünümleri düzenle:',
|
||||
'Editing %s': '%s Düzenleniyor',
|
||||
'Editing file': 'Dosya düzenleniyor',
|
||||
'Editing file "%s"': '"%s" dosyası düzenleniyor ',
|
||||
'Editing Language file': 'Dil dosyası düzenleniyor',
|
||||
'Enable': 'Etkinleştir',
|
||||
'enter a valid email address': 'geçerli e-posta adresi girin',
|
||||
'enter a value': 'bir değer girin',
|
||||
'enter only letters, numbers, and underscore': 'sadece harf, sayı ve alt çizgi giriniz',
|
||||
'Enterprise Web Framework': 'Enterprise Web Çatısı',
|
||||
'Error': 'Hata',
|
||||
'Error logs for "%(app)s"': '"%(app)s" uygulaması için hata kayıtları',
|
||||
'Error snapshot': 'Hata resmi',
|
||||
'Error ticket': 'Hata bileti',
|
||||
'Errors': 'Hatalar',
|
||||
'Exception instance attributes': 'Hata durumu özellikleri',
|
||||
'Exit Fullscreen': 'Tam Ekrandan Çık',
|
||||
'Expand Abbreviation': 'Kısıtlamayı Aç',
|
||||
'export as csv file': 'CSV olarak dışa ver',
|
||||
'exposes': 'sergileniyor',
|
||||
'exposes:': 'sergile:',
|
||||
'extends': 'genişlet',
|
||||
'failed to reload module': 'modül yüklenemedi',
|
||||
'failed to reload module because:': 'modü yüklenemedi çünkü:',
|
||||
'File': 'Dosya',
|
||||
'file "%(filename)s" created': '"%(filename)s" dosyaları oluşturuldu',
|
||||
'file "%(filename)s" deleted': '"%(filename)s" dosyaları silindi',
|
||||
'file "%(filename)s" uploaded': '"%(filename)s" dosyaları yüklendi',
|
||||
'file "%s" of %s restored': '"%s" dosyasının %s kısmı geri alındı',
|
||||
'file changed on disk': 'dosya disk üzerinde değişti',
|
||||
'file does not exist': 'dosya bulunamıyor',
|
||||
'file not found': 'dosya bulanamadı',
|
||||
'file saved on %(time)s': 'dosyası %(time)s zamanında kaydedildi',
|
||||
'file saved on %s': 'dosyası kaydedildi: %s',
|
||||
'Filename': 'Dosya adı',
|
||||
'filter': 'filtre',
|
||||
'Find Next': 'Sonrakini Bul',
|
||||
'Find Previous': 'Öncekini Bul',
|
||||
'Frames': 'Çerçeveler',
|
||||
'Functions with no doctests will result in [passed] tests.': '[passed] testlerdeki işlevlerde doctest yok',
|
||||
'GAE Email': 'GAE E-postası',
|
||||
'GAE Password': 'GAE Parolası',
|
||||
'Generate': 'Oluştur',
|
||||
'Git Pull': 'Git Çek',
|
||||
'Git Push': 'Git İtele',
|
||||
'Globals##debug': 'Geneller',
|
||||
'go!': 'git!',
|
||||
'Google App Engine Deployment Interface': 'Google App Motoru Yayınlama Arayüzü',
|
||||
'Google Application Id': 'Google Uygulama Id',
|
||||
'Goto': 'Git',
|
||||
'graph model': 'grafik modeli',
|
||||
'Help': 'Yardım',
|
||||
'Hide/Show Translated strings': 'Çevrilmiş cümleleri Gizle/Görüntüle',
|
||||
'Hits': 'Vuruşlar',
|
||||
'Home': 'Anasayfa',
|
||||
'honored only if the expression evaluates to true': 'sadece deyim doğru sonucunu verirse',
|
||||
'htmledit': 'html dğzenleyici',
|
||||
'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'Doküman testi yapılmadan önce, eğer yukarıdaki rapor bir bilet numarası içeriyorsa bu denetleyici çalıştırılırken bir hata oluşturğunu gösterir. Bu genellikle girinti/çıkıntı (indentation) hatası veya işlev dışındaki bir hatadan kaynaklanır.\nYeşil başlık geçilen tüm testleri (eğer tanımlanmışsa) gösterir. Bu durumda test sonuçları görüntülenmez.',
|
||||
'Import/Export': 'İçe/Dışa Aktarıcı',
|
||||
'includes': 'içerir',
|
||||
'index': 'indeks',
|
||||
'insert new': 'yeni ekle',
|
||||
'insert new %s': '%s yeni ekle',
|
||||
'inspect attributes': 'özellikleri denetleyin',
|
||||
'Install': 'Kurucu',
|
||||
'Installed applications': 'Kurulu uygulamalar',
|
||||
'internal error': 'dahili hata',
|
||||
'Internal State': 'Dahili Durum',
|
||||
'Invalid action': 'Geçersiz eylem',
|
||||
'invalid expression': 'geçersiz ifade',
|
||||
'invalid password': 'Parola geçersiz',
|
||||
'invalid password.': 'geçersiz parola.',
|
||||
'Invalid Query': 'Geçersiz Sorgu',
|
||||
'invalid request': 'geçersiz istek',
|
||||
'invalid ticket': 'geçersiz bilet',
|
||||
'Key bindings': 'Anahtarlar',
|
||||
'Key bindings for ZenCoding Plugin': 'ZenCoding Eklentisi için anahtarlar',
|
||||
'language file "%(filename)s" created/updated': '"%(filename)s" dil dosyası/dosyaları güncellendi',
|
||||
'Language files (static strings) updated': 'Dil dosyası (statik cümleler) güncellendi',
|
||||
'languages': 'diller',
|
||||
'Languages': 'Diller',
|
||||
'Last saved on:': 'Son kaydedilme:',
|
||||
'License for': 'için lisanslanmış',
|
||||
'Line Nr': 'Satır Nr',
|
||||
'Line number': 'Satır numarası',
|
||||
'lists by exception': 'istisnaya göre sırala',
|
||||
'lists by ticket': 'bilete göre sırala',
|
||||
'loading...': 'yükleniyor ...',
|
||||
'locals': 'yereller',
|
||||
'Locals##debug': 'Yereller',
|
||||
'Login': 'Giriş',
|
||||
'login': 'giriş',
|
||||
'Login to the Administrative Interface': 'Yönetsel Arayüze Giriş\t',
|
||||
'Logout': 'Çıkış',
|
||||
'Manage': 'Yönet',
|
||||
'merge': 'birleştir',
|
||||
'Models': 'Modeller',
|
||||
'models': 'modeller',
|
||||
'Modules': 'Modüller',
|
||||
'modules': 'modüller',
|
||||
'new application "%s" created': 'yeni uygulama "%s" oluşturuldu',
|
||||
'New Application Wizard': 'Yeni Uygulama Sihirbazı',
|
||||
'New application wizard': 'Yeni uygulama sihirbazı',
|
||||
'new plugin installed': 'yeni eklenti kuruldu',
|
||||
'New Record': 'Yeni Kayıt',
|
||||
'new record inserted': 'yeni kayıt eklendi',
|
||||
'New simple application': 'Yeni basit uygulama',
|
||||
'next 100 rows': 'sonraki 100 satır',
|
||||
'NO': 'HAYIR',
|
||||
'No databases in this application': 'Bu uygulamada veritabanı yok',
|
||||
'No Interaction yet': 'Henüz etkileşim yok',
|
||||
'no match': 'eşlenen yok',
|
||||
'no package selected': 'hiç paket seçilmemiş',
|
||||
'No ticket_storage.txt found under /private folder': '/private dizininde ticket_storage.txt dosyası bulunamadı',
|
||||
'Note: If you receive an error with github status code of 128, ensure the system and account you are deploying from has a cooresponding ssh key configured in the openshift account.': 'Not: Eğer github hata kodu 128 durumunu bildiren bir ileti alırsanız, OpenShift hesabınızı ait ssh anahtarının doğru yapılandırıldığından emin olun.',
|
||||
'online designer': 'çevirimiçi tasarlayıcı',
|
||||
'Open new app in new window': 'Yeni pencerede yeni uygualama aç',
|
||||
'OpenShift Deployment Interface': 'OpenShift Yayınlama Arayüzü',
|
||||
'or alternatively': 'veya seçenek olarak',
|
||||
'Or Get from URL:': 'Veya şu URL den alın:',
|
||||
'or import from csv file': 'veya CSV dsoyasından içerin',
|
||||
'or provide app url:': "veya uygulama URL'si verin:",
|
||||
'or provide application url:': "veya uygulama URL'si verin:",
|
||||
'Original/Translation': 'Orjinal / Çeviri',
|
||||
'Overwrite installed app': 'Kurulu uygulama üzerine yaz',
|
||||
'Pack all': 'Tümünü paketle',
|
||||
'Pack compiled': 'Derlenenleri paketle',
|
||||
'Pack custom': 'Tercihli paketle',
|
||||
'pack plugin': 'eklentiyi paketle',
|
||||
'PAM authenticated user, cannot change password here': 'PAM onaylı kullanıcı, parola buradan değiştirilemiyor',
|
||||
'password changed': 'parola değiştirilidi',
|
||||
'Path to appcfg.py': 'appcfg.py dosyasının patikası',
|
||||
'Path to local openshift repo root.': 'Yerel openshift repo kökünün patikası.',
|
||||
'Peeking at file': 'Dosya gözetleniyor',
|
||||
'Please': 'Lütfen',
|
||||
'plugin "%(plugin)s" deleted': '"%(plugin)s" eklentisi silindi',
|
||||
'Plugin "%s" in application': '"%s" uygulamasında eklenti',
|
||||
'plugins': 'eklentiler',
|
||||
'Plugins': 'Eklentiler',
|
||||
'Plural-Forms:': 'Çoğul-Kipler:',
|
||||
'Powered by': 'Yazılım Temeli:',
|
||||
'previous 100 rows': 'önceki 100 satır',
|
||||
'Private files': 'Özel dosyalar',
|
||||
'private files': 'özel dosyalar',
|
||||
'Project Progress': 'Proje İlerlemesi',
|
||||
'pygraphviz library not found': 'pygraphviz kütüphanesi yok',
|
||||
'Query:': 'Sorgu: ',
|
||||
'Rapid Search': 'Hızlı Arama',
|
||||
'record': 'kayıt',
|
||||
'record does not exist': 'kayıt bulunamıyor',
|
||||
'record id': 'kayıt id',
|
||||
'refresh': 'yeniden yükle',
|
||||
'Reload routes': 'Yönelendirmeyi yeniden yükle',
|
||||
'Remove compiled': 'Derlemeyi kaldır',
|
||||
'Removed Breakpoint on %s at line %s': ' %s üzerindeki kesme noktası %s satırında değiştrildi.',
|
||||
'Replace': 'Değiştir',
|
||||
'Replace All': 'Tümünü değiştir',
|
||||
'request': 'istek',
|
||||
'requires python-git, but not installed': 'python-git gerekyior, fakat kurulu değil',
|
||||
'Resolve Conflict file': 'Dosyadaki çakışmayı çöz',
|
||||
'response': 'tepki',
|
||||
'restart': 'yeniden başla',
|
||||
'restore': 'geri al',
|
||||
'revert': 'geri al',
|
||||
'Rows in table': 'Tablosundaki satırlar',
|
||||
'Rows selected': 'Seçilen satırlar',
|
||||
"Run tests in this file (to run all files, you may also use the button labelled 'test')": "Bu dosyadaki testleri çalıştırır (tüm dosyaları çalıştırmak için, 'test' etiketli düğmeyi kullanabilirsiniz)",
|
||||
'Running on %s': '%s üzerinde çalışıyor',
|
||||
'Save': 'Kaydet',
|
||||
'save': 'kaydet',
|
||||
'Save file:': 'Dosyayı kaydet:',
|
||||
'Save file: %s': 'Dosyayı farklı kaydet: %s',
|
||||
'Save via Ajax': 'Ajax üzerinden kaydet',
|
||||
'Saved file hash:': 'Kaydedilen dosyanın parmak izi:',
|
||||
'Select Files to Package': 'Paketlenecek Dosyaları Seç',
|
||||
'selected': 'seçildi',
|
||||
'session': 'oturum',
|
||||
'session expired': 'oturum zamanaşımına uğradı',
|
||||
'Set Breakpoint on %s at line %s: %s': "%s'nin %s satırındaki kesme noktasını: %s yap",
|
||||
'shell': 'kabuk',
|
||||
'Site': 'Site',
|
||||
'skip to generate': 'oluşturmak için atla',
|
||||
'some files could not be removed': 'bazı dosyalar kaldırılamadı',
|
||||
'source : filesystem': 'kaynak : dosyasistemi',
|
||||
'Start a new app': 'Yeni uygualama başla',
|
||||
'Start searching': 'Aramaya başla',
|
||||
'Start wizard': 'Başlatma sihirbazı',
|
||||
'state': 'durum',
|
||||
'static': 'statik',
|
||||
'Static': 'Statik',
|
||||
'Static files': 'Statik dosyalar',
|
||||
'Step': 'Basamak',
|
||||
'Submit': 'Gönder',
|
||||
'submit': 'gönder',
|
||||
'successful': 'başarılı',
|
||||
'Sure you want to delete this object?': 'Bu nesneyi silmek istediğinizden emin misiniz? ',
|
||||
'switch to : db': 'geç : db',
|
||||
'table': 'tablo',
|
||||
'Temporary': 'Geçici',
|
||||
'test': 'test',
|
||||
'Testing application': 'Uygulama test ediliyor',
|
||||
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"sorgulama" "db.table1.field1==\'değer\'" şeklinde bir durumu ifade eder. SQL birleştirmede (JOIN) "db.table1.field1==db.table2.field2" şeklindedir.',
|
||||
'the application logic, each URL path is mapped in one exposed function in the controller': 'uygulama mantığı: her URL denetleyicideki bir işleve eşlenir',
|
||||
'The application logic, each URL path is mapped in one exposed function in the controller': 'Uygulama mantığı: her URL denetleyicideki bir işleve eşlenir',
|
||||
'the data representation, define database tables and sets': 'veri gösterimi, veritabanı tablolarını ve setlerini tanımla',
|
||||
'The data representation, define database tables and sets': 'Veri gösterimi, veritabanı tablolarını ve setlerini tanımla',
|
||||
'The presentations layer, views are also known as templates': 'Sunum katmanı, görünümler şablon olarakda biliniyor.',
|
||||
'the presentations layer, views are also known as templates': 'sunum katmanı, görünümler şablon olarakda biliniyor.',
|
||||
'There are no controllers': 'Denetçiler yok',
|
||||
'There are no models': 'Modeller yok',
|
||||
'There are no modules': 'Modüller yok',
|
||||
'There are no plugins': 'Eklentiler yok',
|
||||
'There are no private files': 'Özel dosyalar yok',
|
||||
'There are no static files': 'Statik dosyalar yok',
|
||||
'There are no translators, only default language is supported': 'Çeviriler, sadeceön tanmlı dil destekleniyor.',
|
||||
'There are no views': 'Görünümler yok',
|
||||
'These files are not served, they are only available from within your app': 'Bu dosyalar servis yapılmıyor, bunlar sadece uygulamanız içerisinden erişilebilir.',
|
||||
'These files are served without processing, your images go here': 'Bu dosyalarda işlem yapılmadan kaydedildi, resimler buraya gidiyor:',
|
||||
'these files are served without processing, your images go here': 'bu dosyalarda işlem yapılmadan kaydedildi, resimler buraya gidiyor:',
|
||||
'This is the %(filename)s template': 'Bu şablonlar %(filename)s: ',
|
||||
"This page can commit your changes to an openshift app repo and push them to your cloud instance. This assumes that you've already created the application instance using the web2py skeleton and have that repo somewhere on a filesystem that this web2py instance can access. This functionality requires GitPython installed and on the python path of the runtime that web2py is operating in.": "Bu sayfa uygulamanızı OpenShif uygulama reposuna koyar. Uygulamanızın web2py iskeleti ile oluşturulduğunuz ve web2py dosya sisteminizdeki ropoya erişilebileceği varsayılmıştır. Bu işlev web2py'nin çalıştığı ortamda GitPython'e ihtiyaç duyar.",
|
||||
'This page can upload your application to the Google App Engine computing cloud. Mind that you must first create indexes locally and this is done by installing the Google appserver and running the app locally with it once, or there will be errors when selecting records. Attention: deployment may take long time, depending on the network speed. Attention: it will overwrite your app.yaml. DO NOT SUBMIT TWICE.': 'Bu sayfa uygulamanızı Google App Motoru bilişim bulutuna yükleyecektir. İndeksleri yerel olarak oluştırmanız gerektiğini aklınızda tutun, Google uygulama sunucusunu yerel olarak kurup çalıştırın, aksi halde bazı kayıtlarda hatalar olacaktır. Uyarı: yayınlama ağ hızınıza bağlı olarak uzun zaman alabilir. Uyarı: bu sizin app.yaml dosyasını yeniden yazar. LÜTFEN BİRDEN FAZLA GÖNDERMEYİN.',
|
||||
'this page to see if a breakpoint was hit and debug interaction is required.': 'bu sayfayı, kesme noktasına geldiğini görmek için ve hata ayıklama etkileşmesi gerekiyor..',
|
||||
'Ticket': 'Bilet',
|
||||
'Ticket ID': 'Bile ID\'si',
|
||||
'TM': 'TM',
|
||||
'to previous version.': 'önceki sürüme.',
|
||||
'To create a plugin, name a file/folder plugin_[name]': 'Eklenti oluşturmak için dosyayı dosya/klasör plugin_[isim] şeklinde isimlendir. ',
|
||||
'To emulate a breakpoint programatically, write:': 'Program ile kesme noktasını öykünmek için, yazın:',
|
||||
'to use the debugger!': 'hata ayıklayıcısını kullanmak için!',
|
||||
'toggle breakpoint': 'kesme noktasını değiştir',
|
||||
'Toggle Fullscreen': 'Tam Ekrana Geç',
|
||||
'Traceback': 'Nedenin bul',
|
||||
'translation strings for the application': 'uygulama için çeviri cümleleri',
|
||||
'Translation strings for the application': 'Uygulama için çeviri cümleleri',
|
||||
'try': 'dene',
|
||||
'try something like': 'gibi birşey dene',
|
||||
'Try the mobile interface': 'Mobil arayüzü dene',
|
||||
'try view': 'görünümü dene',
|
||||
'Unable to check for upgrades': 'Güncellemeler denetlenemiyor',
|
||||
'unable to create application "%s"': '"%s" uygulaması oluşturulamıyor',
|
||||
'unable to delete file "%(filename)s"': '"%(filename)s" dosylaları silinemiyor',
|
||||
'unable to delete file plugin "%(plugin)s"': '"%(plugin)s" eklenti dosyasyaları silenemiyor',
|
||||
'Unable to download': 'İndirilemiyor',
|
||||
'Unable to download app': 'Uygulamanız indirilemiyor',
|
||||
'Unable to download app because:': 'Uygulamanız indirilemiyor çünkü:',
|
||||
'Unable to download because': 'İndirilemiyor çünkü:',
|
||||
'unable to parse csv file': "impossible d'analyser les fichiers CSV",
|
||||
'unable to uninstall "%s"': 'kladıramıyor çünkü "%s"',
|
||||
'unable to upgrade because "%s"': 'güncelleyemiyor çünkü "%s"',
|
||||
'uncheck all': 'tümünü kladır',
|
||||
'Uninstall': 'Kaldır',
|
||||
'update': 'güncelle',
|
||||
'update all languages': 'tüm delleri yükle',
|
||||
'Update:': 'Güncelle:',
|
||||
'upgrade now': 'şimdi güncelle',
|
||||
'upgrade web2py now': "web2py'yi güncelle",
|
||||
'upload': 'yükle',
|
||||
'Upload': 'Yükle',
|
||||
'Upload & install packed application': 'Paketlenmiş uygulamayı yükle ve kur',
|
||||
'Upload a package:': 'Paket yükle:',
|
||||
'Upload and install packed application': 'Paketlenmiş uygulamayı yükle ve kur',
|
||||
'upload application:': 'uygulamayı yükle:',
|
||||
'Upload existing application': 'Var olan uygulamayı yükle',
|
||||
'upload file:': 'dosyayı yükle:',
|
||||
'upload plugin file:': 'eklenti dosyasını yükle:',
|
||||
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Karmaşık sorgularda Ve (AND) için (...)&(...) kullanın, Veya (OR) için (...)|(...) kullanın ve DEĞİL (NOT) için ~(...) kullanın. ',
|
||||
'Use an url:': "Url'yi kullan:",
|
||||
'user': 'kullanıcı',
|
||||
'variables': 'değişkenler',
|
||||
'Version': 'Sürüm',
|
||||
'versioning': 'sürümleme',
|
||||
'Versioning': 'Sürümleme',
|
||||
'view': 'görüntü',
|
||||
'Views': 'Görüntüler',
|
||||
'views': 'görüntüler',
|
||||
'Web Framework': 'Web Çatısı',
|
||||
'web2py apps to deploy': 'Yayınlanacak web2py uygulaması',
|
||||
'web2py is up to date': 'web2py güncel',
|
||||
'web2py online debugger': 'çevirimiçi web2py hata ayıklayıcı',
|
||||
'web2py Recent Tweets': 'web2py Son Twitler',
|
||||
'web2py upgraded; please restart it': 'web2py güncellendi, lütfen yeniden başlatın',
|
||||
'WSGI reference name': 'WSGI referans ismi',
|
||||
'YES': 'EVET',
|
||||
'You can also set and remove breakpoint in the edit window, using the Toggle Breakpoint button': '"kesme noktaları" düğmesini kullanarak düzenleme penceresine geçebilir ve kesme nokatalarını hem ekeleyebilir hemde kaldırabilirsiniz',
|
||||
'You need to set up and reach a': 'Gelinceye kadar kurmalısınız',
|
||||
}
|
||||
@@ -8,42 +8,6 @@ WEB2PY_VERSION_URL = WEB2PY_URL + '/examples/default/version'
|
||||
# the user-interface feature that allows you to edit files in your web
|
||||
# browser.
|
||||
|
||||
## Default editor (to change editor you need web2py.admin.editors.zip)
|
||||
## old editors like 'ace' or 'edit_area' or 'amy' are no longer supported
|
||||
TEXT_EDITOR = 'codemirror'
|
||||
|
||||
## Editor Color scheme (only for ace)
|
||||
TEXT_EDITOR_THEME = (
|
||||
"chrome", "clouds", "clouds_midnight", "cobalt", "crimson_editor", "dawn",
|
||||
"dreamweaver", "eclipse", "idle_fingers", "kr_theme", "merbivore",
|
||||
"merbivore_soft", "monokai", "mono_industrial", "pastel_on_dark",
|
||||
"solarized_dark", "solarized_light", "textmate", "tomorrow",
|
||||
"tomorrow_night", "tomorrow_night_blue", "tomorrow_night_bright",
|
||||
"tomorrow_night_eighties", "twilight", "vibrant_ink")[0]
|
||||
|
||||
## Editor Keyboard bindings (only for ace and codemirror)
|
||||
TEXT_EDITOR_KEYBINDING = '' # 'emacs' or 'vi'
|
||||
|
||||
### edit_area only
|
||||
# The default font size, measured in 'points'. The value must be an integer > 0
|
||||
FONT_SIZE = 10
|
||||
|
||||
# Displays the editor in full screen mode. The value must be 'true' or 'false'
|
||||
FULL_SCREEN = 'false'
|
||||
|
||||
# Display a check box under the editor to allow the user to switch
|
||||
# between the editor and a simple
|
||||
# HTML text area. The value must be 'true' or 'false'
|
||||
ALLOW_TOGGLE = 'true'
|
||||
|
||||
# Replaces tab characters with space characters.
|
||||
# The value can be 'false' (meaning that tabs are not replaced),
|
||||
# or an integer > 0 that specifies the number of spaces to replace a tab with.
|
||||
REPLACE_TAB_BY_SPACES = 4
|
||||
|
||||
# Toggle on/off the code editor instead of textarea on startup
|
||||
DISPLAY = "onload" or "later"
|
||||
|
||||
# if demo mode is True then admin works readonly and does not require login
|
||||
DEMO_MODE = False
|
||||
|
||||
@@ -79,3 +43,6 @@ PLUGINS_APP = 'http://web2py.com/plugins'
|
||||
# set the language
|
||||
if 'adminLanguage' in request.cookies and not (request.cookies['adminLanguage'] is None):
|
||||
T.force(request.cookies['adminLanguage'].value)
|
||||
|
||||
#set static_version
|
||||
response.static_version = open('VERSION').read().split(' ',1)[1].split('-')[0]
|
||||
|
||||
@@ -144,7 +144,7 @@ if session.is_mobile == 'true':
|
||||
elif session.is_mobile == 'false':
|
||||
is_mobile = False
|
||||
else:
|
||||
is_mobile = request.user_agent().is_mobile
|
||||
is_mobile = request.user_agent().get('is_mobile',False)
|
||||
|
||||
if DEMO_MODE:
|
||||
session.authorized = True
|
||||
|
||||
@@ -24,7 +24,7 @@ def button_enable(href, app):
|
||||
return A(label, _class='button btn', _id=id, callback=href, target=id)
|
||||
|
||||
def sp_button(href, label):
|
||||
if request.user_agent().is_mobile:
|
||||
if request.user_agent().get('is_mobile'):
|
||||
ret = A_button(SPAN(label), _href=href)
|
||||
else:
|
||||
ret = A(SPAN(label), _class='button special btn btn-inverse', _href=href)
|
||||
@@ -37,4 +37,4 @@ def searchbox(elementid):
|
||||
return SPAN(LABEL(IMG(_id="search_start", _src=URL('static', 'images/search.png'), _alt=T('filter')),
|
||||
_class='icon', _for=elementid), ' ',
|
||||
INPUT(_id=elementid, _type='text', _size=12, _class="input-medium"),
|
||||
_class="searchbox")
|
||||
_class="searchbox")
|
||||
|
||||
17
applications/admin/models/plugin_statebutton.py
Normal file
17
applications/admin/models/plugin_statebutton.py
Normal file
@@ -0,0 +1,17 @@
|
||||
response.files.append(URL('static','plugin_statebutton/js/bootstrap-switch.js'))
|
||||
response.files.append(URL('static','plugin_statebutton/css/bootstrap-switch.css'))
|
||||
|
||||
def stateWidget(field, value, data={'on-label':'Enabled', 'off-label':'Disabled', 'on':"primary", 'off':"default" }):
|
||||
try:
|
||||
fieldName = str(field).split('.')[1]
|
||||
except:
|
||||
fieldName = field
|
||||
|
||||
div = DIV(INPUT( _type='checkbox', _name='%s' % fieldName, _checked= 'checked' if value == 'true' else None, _value='true'),
|
||||
_class='make-bootstrap-switch',
|
||||
data=data)
|
||||
script = SCRIPT("""
|
||||
jQuery(".make-bootstrap-switch input[name='%s']").parent().bootstrapSwitch();
|
||||
""" % fieldName)
|
||||
return DIV(div, script)
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
[DEFAULT]
|
||||
theme = web2py
|
||||
|
||||
[editor]
|
||||
theme = web2py
|
||||
editor = default
|
||||
closetag = true
|
||||
|
||||
[editor_sessions]
|
||||
welcome = welcome/models/db.py,welcome/controllers/default.py,welcome/views/default/index.html
|
||||
|
||||
|
||||
@@ -96,8 +96,9 @@
|
||||
for (var i = start; i <= end; ++i) {
|
||||
var line = self.getLine(i);
|
||||
var found = line.indexOf(lineString);
|
||||
if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
|
||||
if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment;
|
||||
if (i != start && found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
|
||||
if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
|
||||
lines.push(line);
|
||||
}
|
||||
self.operation(function() {
|
||||
@@ -124,7 +125,10 @@
|
||||
endLine = self.getLine(--end);
|
||||
close = endLine.lastIndexOf(endString);
|
||||
}
|
||||
if (open == -1 || close == -1) return false;
|
||||
if (open == -1 || close == -1 ||
|
||||
!/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) ||
|
||||
!/comment/.test(self.getTokenTypeAt(Pos(end, close + 1))))
|
||||
return false;
|
||||
|
||||
self.operation(function() {
|
||||
self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
|
||||
|
||||
@@ -10,11 +10,22 @@
|
||||
} else {
|
||||
dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
|
||||
}
|
||||
dialog.innerHTML = template;
|
||||
if (typeof template == "string") {
|
||||
dialog.innerHTML = template;
|
||||
} else { // Assuming it's a detached DOM element.
|
||||
dialog.appendChild(template);
|
||||
}
|
||||
return dialog;
|
||||
}
|
||||
|
||||
function closeNotification(cm, newVal) {
|
||||
if (cm.state.currentNotificationClose)
|
||||
cm.state.currentNotificationClose();
|
||||
cm.state.currentNotificationClose = newVal;
|
||||
}
|
||||
|
||||
CodeMirror.defineExtension("openDialog", function(template, callback, options) {
|
||||
closeNotification(this, null);
|
||||
var dialog = dialogDiv(this, template, options && options.bottom);
|
||||
var closed = false, me = this;
|
||||
function close() {
|
||||
@@ -24,6 +35,7 @@
|
||||
}
|
||||
var inp = dialog.getElementsByTagName("input")[0], button;
|
||||
if (inp) {
|
||||
if (options && options.value) inp.value = options.value;
|
||||
CodeMirror.on(inp, "keydown", function(e) {
|
||||
if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
|
||||
if (e.keyCode == 13 || e.keyCode == 27) {
|
||||
@@ -51,6 +63,7 @@
|
||||
});
|
||||
|
||||
CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
|
||||
closeNotification(this, null);
|
||||
var dialog = dialogDiv(this, template, options && options.bottom);
|
||||
var buttons = dialog.getElementsByTagName("button");
|
||||
var closed = false, me = this, blurring = 1;
|
||||
@@ -77,4 +90,33 @@
|
||||
CodeMirror.on(b, "focus", function() { ++blurring; });
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* openNotification
|
||||
* Opens a notification, that can be closed with an optional timer
|
||||
* (default 5000ms timer) and always closes on click.
|
||||
*
|
||||
* If a notification is opened while another is opened, it will close the
|
||||
* currently opened one and open the new one immediately.
|
||||
*/
|
||||
CodeMirror.defineExtension("openNotification", function(template, options) {
|
||||
closeNotification(this, close);
|
||||
var dialog = dialogDiv(this, template, options && options.bottom);
|
||||
var duration = options && (options.duration === undefined ? 5000 : options.duration);
|
||||
var closed = false, doneTimer;
|
||||
|
||||
function close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearTimeout(doneTimer);
|
||||
dialog.parentNode.removeChild(dialog);
|
||||
}
|
||||
|
||||
CodeMirror.on(dialog, 'click', function(e) {
|
||||
CodeMirror.e_preventDefault(e);
|
||||
close();
|
||||
});
|
||||
if (duration)
|
||||
doneTimer = setTimeout(close, options.duration);
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
var wrap = cm.getWrapperElement();
|
||||
cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
|
||||
width: wrap.style.width, height: wrap.style.height};
|
||||
wrap.style.width = wrap.style.height = "";
|
||||
wrap.style.width = "";
|
||||
wrap.style.height = "auto";
|
||||
wrap.className += " CodeMirror-fullscreen";
|
||||
document.documentElement.style.overflow = "hidden";
|
||||
cm.refresh();
|
||||
|
||||
@@ -2,12 +2,10 @@
|
||||
CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
|
||||
var prev = old && old != CodeMirror.Init;
|
||||
if (val && !prev) {
|
||||
cm.on("focus", onFocus);
|
||||
cm.on("blur", onBlur);
|
||||
cm.on("change", onChange);
|
||||
onChange(cm);
|
||||
} else if (!val && prev) {
|
||||
cm.off("focus", onFocus);
|
||||
cm.off("blur", onBlur);
|
||||
cm.off("change", onChange);
|
||||
clearPlaceholder(cm);
|
||||
@@ -33,9 +31,6 @@
|
||||
cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
|
||||
}
|
||||
|
||||
function onFocus(cm) {
|
||||
clearPlaceholder(cm);
|
||||
}
|
||||
function onBlur(cm) {
|
||||
if (isEmpty(cm)) setPlaceholder(cm);
|
||||
}
|
||||
@@ -43,7 +38,6 @@
|
||||
var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
|
||||
wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
|
||||
|
||||
if (cm.hasFocus()) return;
|
||||
if (empty) setPlaceholder(cm);
|
||||
else clearPlaceholder(cm);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
var map = {
|
||||
name : "autoCloseBrackets",
|
||||
Backspace: function(cm) {
|
||||
if (cm.somethingSelected()) return CodeMirror.Pass;
|
||||
if (cm.somethingSelected() || cm.getOption("disableInput")) return CodeMirror.Pass;
|
||||
var cur = cm.getCursor(), around = charsAround(cm, cur);
|
||||
if (around && pairs.indexOf(around) % 2 == 0)
|
||||
cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1));
|
||||
@@ -49,7 +49,8 @@
|
||||
else cm.execCommand("goCharRight");
|
||||
}
|
||||
map["'" + left + "'"] = function(cm) {
|
||||
if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment")
|
||||
if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment" ||
|
||||
cm.getOption("disableInput"))
|
||||
return CodeMirror.Pass;
|
||||
if (cm.somethingSelected()) return surround(cm);
|
||||
if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
|
||||
@@ -70,7 +71,8 @@
|
||||
function buildExplodeHandler(pairs) {
|
||||
return function(cm) {
|
||||
var cur = cm.getCursor(), around = charsAround(cm, cur);
|
||||
if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
|
||||
if (!around || pairs.indexOf(around) % 2 != 0 || cm.getOption("disableInput"))
|
||||
return CodeMirror.Pass;
|
||||
cm.operation(function() {
|
||||
var newPos = CodeMirror.Pos(cur.line + 1, 0);
|
||||
cm.replaceSelection("\n\n", {anchor: newPos, head: newPos}, "+input");
|
||||
|
||||
@@ -24,16 +24,15 @@
|
||||
|
||||
(function() {
|
||||
CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) {
|
||||
if (val && (old == CodeMirror.Init || !old)) {
|
||||
var map = {name: "autoCloseTags"};
|
||||
if (typeof val != "object" || val.whenClosing)
|
||||
map["'/'"] = function(cm) { return autoCloseSlash(cm); };
|
||||
if (typeof val != "object" || val.whenOpening)
|
||||
map["'>'"] = function(cm) { return autoCloseGT(cm); };
|
||||
cm.addKeyMap(map);
|
||||
} else if (!val && (old != CodeMirror.Init && old)) {
|
||||
if (old != CodeMirror.Init && old)
|
||||
cm.removeKeyMap("autoCloseTags");
|
||||
}
|
||||
if (!val) return;
|
||||
var map = {name: "autoCloseTags"};
|
||||
if (typeof val != "object" || val.whenClosing)
|
||||
map["'/'"] = function(cm) { return autoCloseSlash(cm); };
|
||||
if (typeof val != "object" || val.whenOpening)
|
||||
map["'>'"] = function(cm) { return autoCloseGT(cm); };
|
||||
cm.addKeyMap(map);
|
||||
});
|
||||
|
||||
var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
|
||||
@@ -44,7 +43,7 @@
|
||||
function autoCloseGT(cm) {
|
||||
var pos = cm.getCursor(), tok = cm.getTokenAt(pos);
|
||||
var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
|
||||
if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass;
|
||||
if (inner.mode.name != "xml" || !state.tagName || cm.getOption("disableInput")) return CodeMirror.Pass;
|
||||
|
||||
var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html";
|
||||
var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
|
||||
@@ -54,9 +53,13 @@
|
||||
if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);
|
||||
var lowerTagName = tagName.toLowerCase();
|
||||
// Don't process the '>' at the end of an end-tag or self-closing tag
|
||||
if (tok.type == "tag" && state.type == "closeTag" ||
|
||||
if (!tagName ||
|
||||
tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||
|
||||
tok.type == "tag" && state.type == "closeTag" ||
|
||||
tok.string.indexOf("/") == (tok.string.length - 1) || // match something like <someTagName />
|
||||
dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1)
|
||||
dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||
|
||||
CodeMirror.scanForClosingTag && CodeMirror.scanForClosingTag(cm, pos, tagName,
|
||||
Math.min(cm.lastLine() + 1, pos.line + 50)))
|
||||
return CodeMirror.Pass;
|
||||
|
||||
var doIndent = indentTags && indexOf(indentTags, lowerTagName) > -1;
|
||||
@@ -64,15 +67,18 @@
|
||||
cm.replaceSelection(">" + (doIndent ? "\n\n" : "") + "</" + tagName + ">",
|
||||
{head: curPos, anchor: curPos});
|
||||
if (doIndent) {
|
||||
cm.indentLine(pos.line + 1);
|
||||
cm.indentLine(pos.line + 2);
|
||||
cm.indentLine(pos.line + 1, null, true);
|
||||
cm.indentLine(pos.line + 2, null);
|
||||
}
|
||||
}
|
||||
|
||||
function autoCloseSlash(cm) {
|
||||
var pos = cm.getCursor(), tok = cm.getTokenAt(pos);
|
||||
var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
|
||||
if (tok.string.charAt(0) != "<" || inner.mode.name != "xml") return CodeMirror.Pass;
|
||||
if (tok.type == "string" || tok.string.charAt(0) != "<" ||
|
||||
tok.start != pos.ch - 1 || inner.mode.name != "xml" ||
|
||||
cm.getOption("disableInput"))
|
||||
return CodeMirror.Pass;
|
||||
|
||||
var tagName = state.context && state.context.tagName;
|
||||
if (tagName) cm.replaceSelection("/" + tagName + ">", "end");
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
unorderedBullets = '*+-';
|
||||
|
||||
CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
|
||||
if (cm.getOption("disableInput")) return CodeMirror.Pass;
|
||||
|
||||
var pos = cm.getCursor(),
|
||||
inList = cm.getStateAfter(pos.line).list,
|
||||
inList = cm.getStateAfter(pos.line).list !== false,
|
||||
match;
|
||||
|
||||
if (!inList || !(match = cm.getLine(pos.line).match(listRE))) {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
function findMatchingBracket(cm, where, strict) {
|
||||
var state = cm.state.matchBrackets;
|
||||
var maxScanLen = (state && state.maxScanLineLength) || 10000;
|
||||
var maxScanLines = (state && state.maxScanLines) || 100;
|
||||
|
||||
var cur = where || cm.getCursor(), line = cm.getLineHandle(cur.line), pos = cur.ch - 1;
|
||||
var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
|
||||
@@ -32,7 +33,7 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var i = cur.line, found, e = forward ? Math.min(i + 100, cm.lineCount()) : Math.max(-1, i - 100); i != e; i+=d) {
|
||||
for (var i = cur.line, found, e = forward ? Math.min(i + maxScanLines, cm.lineCount()) : Math.max(-1, i - maxScanLines); i != e; i+=d) {
|
||||
if (i == cur.line) found = scan(line, i, pos);
|
||||
else found = scan(cm.getLineHandle(i), i);
|
||||
if (found) break;
|
||||
@@ -53,7 +54,7 @@
|
||||
var one = cm.markText(found.from, Pos(found.from.line, found.from.ch + 1), {className: style});
|
||||
var two = found.to && cm.markText(found.to, Pos(found.to.line, found.to.ch + 1), {className: style});
|
||||
// Kludge to work around the IE bug from issue #1193, where text
|
||||
// input stops going to the textare whever this fires.
|
||||
// input stops going to the textarea whenever this fires.
|
||||
if (ie_lt8 && cm.state.focused) cm.display.input.focus();
|
||||
var clear = function() {
|
||||
cm.operation(function() { one.clear(); two && two.clear(); });
|
||||
|
||||
42
applications/admin/static/codemirror/addon/fold/comment-fold.js
vendored
Normal file
42
applications/admin/static/codemirror/addon/fold/comment-fold.js
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
CodeMirror.registerGlobalHelper("fold", "comment", function(mode) {
|
||||
return mode.blockCommentStart && mode.blockCommentEnd;
|
||||
}, function(cm, start) {
|
||||
var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;
|
||||
if (!startToken || !endToken) return;
|
||||
var line = start.line, lineText = cm.getLine(line);
|
||||
|
||||
var startCh;
|
||||
for (var at = start.ch, pass = 0;;) {
|
||||
var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);
|
||||
if (found == -1) {
|
||||
if (pass == 1) return;
|
||||
pass = 1;
|
||||
at = lineText.length;
|
||||
continue;
|
||||
}
|
||||
if (pass == 1 && found < start.ch) return;
|
||||
if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)))) {
|
||||
startCh = found + startToken.length;
|
||||
break;
|
||||
}
|
||||
at = found - 1;
|
||||
}
|
||||
|
||||
var depth = 1, lastLine = cm.lastLine(), end, endCh;
|
||||
outer: for (var i = line; i <= lastLine; ++i) {
|
||||
var text = cm.getLine(i), pos = i == line ? startCh : 0;
|
||||
for (;;) {
|
||||
var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
|
||||
if (nextOpen < 0) nextOpen = text.length;
|
||||
if (nextClose < 0) nextClose = text.length;
|
||||
pos = Math.min(nextOpen, nextClose);
|
||||
if (pos == text.length) break;
|
||||
if (pos == nextOpen) ++depth;
|
||||
else if (!--depth) { end = i; endCh = pos; break outer; }
|
||||
++pos;
|
||||
}
|
||||
}
|
||||
if (end == null || line == end && endCh == startCh) return;
|
||||
return {from: CodeMirror.Pos(line, startCh),
|
||||
to: CodeMirror.Pos(end, endCh)};
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
(function() {
|
||||
"use strict";
|
||||
|
||||
function doFold(cm, pos, options) {
|
||||
function doFold(cm, pos, options, force) {
|
||||
var finder = options && (options.call ? options : options.rangeFinder);
|
||||
if (!finder) finder = cm.getHelper(pos, "fold");
|
||||
if (!finder) return;
|
||||
if (!finder) finder = CodeMirror.fold.auto;
|
||||
if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
|
||||
var minSize = options && options.minFoldSize || 0;
|
||||
|
||||
@@ -13,7 +12,7 @@
|
||||
if (!range || range.to.line - range.from.line < minSize) return null;
|
||||
var marks = cm.findMarksAt(range.from);
|
||||
for (var i = 0; i < marks.length; ++i) {
|
||||
if (marks[i].__isFold) {
|
||||
if (marks[i].__isFold && force !== "fold") {
|
||||
if (!allowFolded) return null;
|
||||
range.cleared = true;
|
||||
marks[i].clear();
|
||||
@@ -27,7 +26,7 @@
|
||||
pos = CodeMirror.Pos(pos.line - 1, 0);
|
||||
range = getRange(false);
|
||||
}
|
||||
if (!range || range.cleared) return;
|
||||
if (!range || range.cleared || force === "unfold") return;
|
||||
|
||||
var myWidget = makeWidget(options);
|
||||
CodeMirror.on(myWidget, "mousedown", function() { myRange.clear(); });
|
||||
@@ -59,7 +58,13 @@
|
||||
};
|
||||
|
||||
// New-style interface
|
||||
CodeMirror.defineExtension("foldCode", function(pos, options) { doFold(this, pos, options); });
|
||||
CodeMirror.defineExtension("foldCode", function(pos, options, force) {
|
||||
doFold(this, pos, options, force);
|
||||
});
|
||||
|
||||
CodeMirror.commands.fold = function(cm) {
|
||||
cm.foldCode(cm.getCursor());
|
||||
};
|
||||
|
||||
CodeMirror.registerHelper("fold", "combine", function() {
|
||||
var funcs = Array.prototype.slice.call(arguments, 0);
|
||||
@@ -70,4 +75,12 @@
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.registerHelper("fold", "auto", function(cm, start) {
|
||||
var helpers = cm.getHelpers(start, "fold");
|
||||
for (var i = 0; i < helpers.length; i++) {
|
||||
var cur = helpers[i](cm, start);
|
||||
if (cur) return cur;
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
21
applications/admin/static/codemirror/addon/fold/foldgutter.css
vendored
Normal file
21
applications/admin/static/codemirror/addon/fold/foldgutter.css
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
.CodeMirror-foldmarker {
|
||||
color: blue;
|
||||
text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px;
|
||||
font-family: arial;
|
||||
line-height: .3;
|
||||
cursor: pointer;
|
||||
}
|
||||
.CodeMirror-foldgutter {
|
||||
width: .7em;
|
||||
}
|
||||
.CodeMirror-foldgutter-open,
|
||||
.CodeMirror-foldgutter-folded {
|
||||
color: #555;
|
||||
cursor: pointer;
|
||||
}
|
||||
.CodeMirror-foldgutter-open:after {
|
||||
content: "\25BE";
|
||||
}
|
||||
.CodeMirror-foldgutter-folded:after {
|
||||
content: "\25B8";
|
||||
}
|
||||
124
applications/admin/static/codemirror/addon/fold/foldgutter.js
vendored
Normal file
124
applications/admin/static/codemirror/addon/fold/foldgutter.js
vendored
Normal file
@@ -0,0 +1,124 @@
|
||||
(function() {
|
||||
"use strict";
|
||||
|
||||
CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
|
||||
if (old && old != CodeMirror.Init) {
|
||||
cm.clearGutter(cm.state.foldGutter.options.gutter);
|
||||
cm.state.foldGutter = null;
|
||||
cm.off("gutterClick", onGutterClick);
|
||||
cm.off("change", onChange);
|
||||
cm.off("viewportChange", onViewportChange);
|
||||
cm.off("fold", onFold);
|
||||
cm.off("unfold", onFold);
|
||||
cm.off("swapDoc", updateInViewport);
|
||||
}
|
||||
if (val) {
|
||||
cm.state.foldGutter = new State(parseOptions(val));
|
||||
updateInViewport(cm);
|
||||
cm.on("gutterClick", onGutterClick);
|
||||
cm.on("change", onChange);
|
||||
cm.on("viewportChange", onViewportChange);
|
||||
cm.on("fold", onFold);
|
||||
cm.on("unfold", onFold);
|
||||
cm.on("swapDoc", updateInViewport);
|
||||
}
|
||||
});
|
||||
|
||||
var Pos = CodeMirror.Pos;
|
||||
|
||||
function State(options) {
|
||||
this.options = options;
|
||||
this.from = this.to = 0;
|
||||
}
|
||||
|
||||
function parseOptions(opts) {
|
||||
if (opts === true) opts = {};
|
||||
if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
|
||||
if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
|
||||
if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
|
||||
return opts;
|
||||
}
|
||||
|
||||
function isFolded(cm, line) {
|
||||
var marks = cm.findMarksAt(Pos(line));
|
||||
for (var i = 0; i < marks.length; ++i)
|
||||
if (marks[i].__isFold && marks[i].find().from.line == line) return true;
|
||||
}
|
||||
|
||||
function marker(spec) {
|
||||
if (typeof spec == "string") {
|
||||
var elt = document.createElement("div");
|
||||
elt.className = spec;
|
||||
return elt;
|
||||
} else {
|
||||
return spec.cloneNode(true);
|
||||
}
|
||||
}
|
||||
|
||||
function updateFoldInfo(cm, from, to) {
|
||||
var opts = cm.state.foldGutter.options, cur = from;
|
||||
cm.eachLine(from, to, function(line) {
|
||||
var mark = null;
|
||||
if (isFolded(cm, cur)) {
|
||||
mark = marker(opts.indicatorFolded);
|
||||
} else {
|
||||
var pos = Pos(cur, 0), func = opts.rangeFinder || CodeMirror.fold.auto;
|
||||
var range = func && func(cm, pos);
|
||||
if (range && range.from.line + 1 < range.to.line)
|
||||
mark = marker(opts.indicatorOpen);
|
||||
}
|
||||
cm.setGutterMarker(line, opts.gutter, mark);
|
||||
++cur;
|
||||
});
|
||||
}
|
||||
|
||||
function updateInViewport(cm) {
|
||||
var vp = cm.getViewport(), state = cm.state.foldGutter;
|
||||
if (!state) return;
|
||||
cm.operation(function() {
|
||||
updateFoldInfo(cm, vp.from, vp.to);
|
||||
});
|
||||
state.from = vp.from; state.to = vp.to;
|
||||
}
|
||||
|
||||
function onGutterClick(cm, line, gutter) {
|
||||
var opts = cm.state.foldGutter.options;
|
||||
if (gutter != opts.gutter) return;
|
||||
cm.foldCode(Pos(line, 0), opts.rangeFinder);
|
||||
}
|
||||
|
||||
function onChange(cm) {
|
||||
var state = cm.state.foldGutter, opts = cm.state.foldGutter.options;
|
||||
state.from = state.to = 0;
|
||||
clearTimeout(state.changeUpdate);
|
||||
state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600);
|
||||
}
|
||||
|
||||
function onViewportChange(cm) {
|
||||
var state = cm.state.foldGutter, opts = cm.state.foldGutter.options;
|
||||
clearTimeout(state.changeUpdate);
|
||||
state.changeUpdate = setTimeout(function() {
|
||||
var vp = cm.getViewport();
|
||||
if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
|
||||
updateInViewport(cm);
|
||||
} else {
|
||||
cm.operation(function() {
|
||||
if (vp.from < state.from) {
|
||||
updateFoldInfo(cm, vp.from, state.from);
|
||||
state.from = vp.from;
|
||||
}
|
||||
if (vp.to > state.to) {
|
||||
updateFoldInfo(cm, state.to, vp.to);
|
||||
state.to = vp.to;
|
||||
}
|
||||
});
|
||||
}
|
||||
}, opts.updateViewportTimeSpan || 400);
|
||||
}
|
||||
|
||||
function onFold(cm, from) {
|
||||
var state = cm.state.foldGutter, line = from.line;
|
||||
if (line >= state.from && line < state.to)
|
||||
updateFoldInfo(cm, line, line + 1);
|
||||
}
|
||||
})();
|
||||
@@ -1,12 +1,30 @@
|
||||
CodeMirror.registerHelper("fold", "indent", function(cm, start) {
|
||||
var tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line);
|
||||
var myIndent = CodeMirror.countColumn(firstLine, null, tabSize);
|
||||
for (var i = start.line + 1, end = cm.lineCount(); i < end; ++i) {
|
||||
if (!/\S/.test(firstLine)) return;
|
||||
var getIndent = function(line) {
|
||||
return CodeMirror.countColumn(line, null, tabSize);
|
||||
};
|
||||
var myIndent = getIndent(firstLine);
|
||||
var lastLineInFold = null;
|
||||
// Go through lines until we find a line that definitely doesn't belong in
|
||||
// the block we're folding, or to the end.
|
||||
for (var i = start.line + 1, end = cm.lastLine(); i <= end; ++i) {
|
||||
var curLine = cm.getLine(i);
|
||||
if (CodeMirror.countColumn(curLine, null, tabSize) < myIndent &&
|
||||
CodeMirror.countColumn(cm.getLine(i-1), null, tabSize) > myIndent)
|
||||
return {from: CodeMirror.Pos(start.line, firstLine.length),
|
||||
to: CodeMirror.Pos(i, curLine.length)};
|
||||
var curIndent = getIndent(curLine);
|
||||
if (curIndent > myIndent) {
|
||||
// Lines with a greater indent are considered part of the block.
|
||||
lastLineInFold = i;
|
||||
} else if (!/\S/.test(curLine)) {
|
||||
// Empty lines might be breaks within the block we're trying to fold.
|
||||
} else {
|
||||
// A non-empty line at an indent equal to or less than ours marks the
|
||||
// start of another block.
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastLineInFold) return {
|
||||
from: CodeMirror.Pos(start.line, firstLine.length),
|
||||
to: CodeMirror.Pos(lastLineInFold, cm.getLine(lastLineInFold).length)
|
||||
};
|
||||
});
|
||||
CodeMirror.indentRangeFinder = CodeMirror.fold.indent; // deprecated
|
||||
|
||||
@@ -164,4 +164,10 @@
|
||||
if (close) return {open: open, close: close};
|
||||
}
|
||||
};
|
||||
|
||||
// Used by addon/edit/closetag.js
|
||||
CodeMirror.scanForClosingTag = function(cm, pos, name, end) {
|
||||
var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);
|
||||
return !!findMatchingClose(iter, name);
|
||||
};
|
||||
})();
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
function scriptHint(editor, keywords, getToken, options) {
|
||||
// Find the token at the cursor
|
||||
var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
|
||||
if (/\b(?:string|comment)\b/.test(token.type)) return;
|
||||
token.state = CodeMirror.innerMode(editor.getMode(), token.state).state;
|
||||
|
||||
// If it's not a 'word-style' token, ignore the token.
|
||||
@@ -33,21 +34,6 @@
|
||||
tprop = getToken(editor, Pos(cur.line, tprop.start));
|
||||
if (tprop.string != ".") return;
|
||||
tprop = getToken(editor, Pos(cur.line, tprop.start));
|
||||
if (tprop.string == ')') {
|
||||
var level = 1;
|
||||
do {
|
||||
tprop = getToken(editor, Pos(cur.line, tprop.start));
|
||||
switch (tprop.string) {
|
||||
case ')': level++; break;
|
||||
case '(': level--; break;
|
||||
default: break;
|
||||
}
|
||||
} while (level > 0);
|
||||
tprop = getToken(editor, Pos(cur.line, tprop.start));
|
||||
if (tprop.type.indexOf("variable") === 0)
|
||||
tprop.type = "function";
|
||||
else return; // no clue
|
||||
}
|
||||
if (!context) var context = [];
|
||||
context.push(tprop);
|
||||
}
|
||||
@@ -101,7 +87,7 @@
|
||||
function getCompletions(token, context, keywords, options) {
|
||||
var found = [], start = token.string;
|
||||
function maybeAdd(str) {
|
||||
if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
|
||||
if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str);
|
||||
}
|
||||
function gatherCompletions(obj) {
|
||||
if (typeof obj == "string") forEach(stringProps, maybeAdd);
|
||||
@@ -110,11 +96,11 @@
|
||||
for (var name in obj) maybeAdd(name);
|
||||
}
|
||||
|
||||
if (context) {
|
||||
if (context && context.length) {
|
||||
// If this is a property, see if it belongs to some object we can
|
||||
// find in the current environment.
|
||||
var obj = context.pop(), base;
|
||||
if (obj.type.indexOf("variable") === 0) {
|
||||
if (obj.type && obj.type.indexOf("variable") === 0) {
|
||||
if (options && options.additionalContext)
|
||||
base = options.additionalContext[obj.string];
|
||||
base = base || window[obj.string];
|
||||
@@ -132,8 +118,7 @@
|
||||
while (base != null && context.length)
|
||||
base = base[context.pop().string];
|
||||
if (base != null) gatherCompletions(base);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
// If not, just look in the window object and any local scope
|
||||
// (reading into JS mode internals to get at the local and global variables)
|
||||
for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
|
||||
|
||||
@@ -84,7 +84,7 @@
|
||||
function getCompletions(token, context) {
|
||||
var found = [], start = token.string;
|
||||
function maybeAdd(str) {
|
||||
if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
|
||||
if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str);
|
||||
}
|
||||
|
||||
function gatherCompletions(obj) {
|
||||
|
||||
@@ -31,10 +31,6 @@
|
||||
|
||||
var completionList = getCompletions(token, context);
|
||||
completionList = completionList.sort();
|
||||
//prevent autocomplete for last word, instead show dropdown with one word
|
||||
if(completionList.length == 1) {
|
||||
completionList.push(" ");
|
||||
}
|
||||
|
||||
return {list: completionList,
|
||||
from: CodeMirror.Pos(cur.line, token.start),
|
||||
@@ -66,7 +62,7 @@
|
||||
function getCompletions(token, context) {
|
||||
var found = [], start = token.string;
|
||||
function maybeAdd(str) {
|
||||
if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
|
||||
if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str);
|
||||
}
|
||||
|
||||
function gatherCompletions(_obj) {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
(function() {
|
||||
"use strict";
|
||||
|
||||
var HINT_ELEMENT_CLASS = "CodeMirror-hint";
|
||||
var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
|
||||
|
||||
CodeMirror.showHint = function(cm, getHints, options) {
|
||||
// We want a single cursor position.
|
||||
if (cm.somethingSelected()) return;
|
||||
if (getHints == null) getHints = cm.getHelper(cm.getCursor(), "hint");
|
||||
if (getHints == null) return;
|
||||
if (getHints == null) {
|
||||
if (options && options.async) return;
|
||||
else getHints = CodeMirror.hint.auto;
|
||||
}
|
||||
|
||||
if (cm.state.completionActive) cm.state.completionActive.close();
|
||||
|
||||
@@ -42,6 +47,7 @@
|
||||
var completion = data.list[i];
|
||||
if (completion.hint) completion.hint(this.cm, data, completion);
|
||||
else this.cm.replaceRange(getText(completion), data.from, data.to);
|
||||
CodeMirror.signal(data, "pick", completion);
|
||||
this.close();
|
||||
},
|
||||
|
||||
@@ -58,10 +64,15 @@
|
||||
this.widget = new Widget(this, data);
|
||||
CodeMirror.signal(data, "shown");
|
||||
|
||||
var debounce = null, completion = this, finished;
|
||||
var debounce = 0, completion = this, finished;
|
||||
var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;
|
||||
var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;
|
||||
|
||||
var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
|
||||
return setTimeout(fn, 1000/60);
|
||||
};
|
||||
var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
|
||||
|
||||
function done() {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
@@ -85,15 +96,22 @@
|
||||
completion.widget = new Widget(completion, data);
|
||||
}
|
||||
|
||||
function clearDebounce() {
|
||||
if (debounce) {
|
||||
cancelAnimationFrame(debounce);
|
||||
debounce = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function activity() {
|
||||
clearTimeout(debounce);
|
||||
clearDebounce();
|
||||
var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
|
||||
if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
|
||||
pos.ch < startPos.ch || completion.cm.somethingSelected() ||
|
||||
(pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) {
|
||||
completion.close();
|
||||
} else {
|
||||
debounce = setTimeout(update, 170);
|
||||
debounce = requestAnimationFrame(update);
|
||||
if (completion.widget) completion.widget.close();
|
||||
}
|
||||
}
|
||||
@@ -140,6 +158,13 @@
|
||||
return ourMap;
|
||||
}
|
||||
|
||||
function getHintElement(hintsElement, el) {
|
||||
while (el && el != hintsElement) {
|
||||
if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
|
||||
el = el.parentNode;
|
||||
}
|
||||
}
|
||||
|
||||
function Widget(completion, data) {
|
||||
this.completion = completion;
|
||||
this.data = data;
|
||||
@@ -147,12 +172,12 @@
|
||||
|
||||
var hints = this.hints = document.createElement("ul");
|
||||
hints.className = "CodeMirror-hints";
|
||||
this.selectedHint = 0;
|
||||
this.selectedHint = options.getDefaultSelection ? options.getDefaultSelection(cm,options,data) : 0;
|
||||
|
||||
var completions = data.list;
|
||||
for (var i = 0; i < completions.length; ++i) {
|
||||
var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
|
||||
var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active");
|
||||
var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
|
||||
if (cur.className != null) className = cur.className + " " + className;
|
||||
elt.className = className;
|
||||
if (cur.render) cur.render(elt, data, cur);
|
||||
@@ -216,13 +241,18 @@
|
||||
});
|
||||
|
||||
CodeMirror.on(hints, "dblclick", function(e) {
|
||||
var t = e.target || e.srcElement;
|
||||
if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
|
||||
var t = getHintElement(hints, e.target || e.srcElement);
|
||||
if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
|
||||
});
|
||||
|
||||
CodeMirror.on(hints, "click", function(e) {
|
||||
var t = e.target || e.srcElement;
|
||||
if (t.hintId != null) widget.changeActive(t.hintId);
|
||||
var t = getHintElement(hints, e.target || e.srcElement);
|
||||
if (t && t.hintId != null) {
|
||||
widget.changeActive(t.hintId);
|
||||
if (options.completeOnSingleClick) widget.pick();
|
||||
}
|
||||
});
|
||||
|
||||
CodeMirror.on(hints, "mousedown", function() {
|
||||
setTimeout(function(){cm.focus();}, 20);
|
||||
});
|
||||
@@ -257,9 +287,9 @@
|
||||
i = avoidWrap ? 0 : this.data.list.length - 1;
|
||||
if (this.selectedHint == i) return;
|
||||
var node = this.hints.childNodes[this.selectedHint];
|
||||
node.className = node.className.replace(" CodeMirror-hint-active", "");
|
||||
node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
|
||||
node = this.hints.childNodes[this.selectedHint = i];
|
||||
node.className += " CodeMirror-hint-active";
|
||||
node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
|
||||
if (node.offsetTop < this.hints.scrollTop)
|
||||
this.hints.scrollTop = node.offsetTop - 3;
|
||||
else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
|
||||
@@ -271,4 +301,35 @@
|
||||
return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
|
||||
}
|
||||
};
|
||||
|
||||
CodeMirror.registerHelper("hint", "auto", function(cm, options) {
|
||||
var helpers = cm.getHelpers(cm.getCursor(), "hint");
|
||||
if (helpers.length) {
|
||||
for (var i = 0; i < helpers.length; i++) {
|
||||
var cur = helpers[i](cm, options);
|
||||
if (cur && cur.list.length) return cur;
|
||||
}
|
||||
} else {
|
||||
var words = cm.getHelper(cm.getCursor(), "hintWords");
|
||||
if (words) return CodeMirror.hint.fromList(cm, {words: words});
|
||||
}
|
||||
});
|
||||
|
||||
CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
|
||||
var cur = cm.getCursor(), token = cm.getTokenAt(cur);
|
||||
var found = [];
|
||||
for (var i = 0; i < options.words.length; i++) {
|
||||
var word = options.words[i];
|
||||
if (word.slice(0, token.string.length) == token.string)
|
||||
found.push(word);
|
||||
}
|
||||
|
||||
if (found.length) return {
|
||||
list: found,
|
||||
from: CodeMirror.Pos(cur.line, token.start),
|
||||
to: CodeMirror.Pos(cur.line, token.end)
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.commands.autocomplete = CodeMirror.showHint;
|
||||
})();
|
||||
|
||||
@@ -20,13 +20,13 @@
|
||||
var cx = inner.state.context, curTag = cx && tags[cx.tagName];
|
||||
var childList = cx ? curTag && curTag.children : tags["!top"];
|
||||
if (childList) {
|
||||
for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].indexOf(prefix) == 0)
|
||||
for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].lastIndexOf(prefix, 0) == 0)
|
||||
result.push("<" + childList[i]);
|
||||
} else {
|
||||
for (var name in tags) if (tags.hasOwnProperty(name) && name != "!top" && (!prefix || name.indexOf(prefix) == 0))
|
||||
for (var name in tags) if (tags.hasOwnProperty(name) && name != "!top" && (!prefix || name.lastIndexOf(prefix, 0) == 0))
|
||||
result.push("<" + name);
|
||||
}
|
||||
if (cx && (!prefix || ("/" + cx.tagName).indexOf(prefix) == 0))
|
||||
if (cx && (!prefix || ("/" + cx.tagName).lastIndexOf(prefix, 0) == 0))
|
||||
result.push("</" + cx.tagName + ">");
|
||||
} else {
|
||||
// Attribute completion
|
||||
@@ -37,6 +37,7 @@
|
||||
Pos(cur.line, token.type == "string" ? token.start : token.end));
|
||||
var atName = before.match(/([^\s\u00a0=<>\"\']+)=$/), atValues;
|
||||
if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return;
|
||||
if (typeof atValues == 'function') atValues = atValues.call(this, cm); // Functions can be used to supply values for autocomplete widget
|
||||
if (token.type == "string") {
|
||||
prefix = token.string;
|
||||
if (/['"]/.test(token.string.charAt(0))) {
|
||||
@@ -45,14 +46,14 @@
|
||||
}
|
||||
replaceToken = true;
|
||||
}
|
||||
for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].indexOf(prefix) == 0)
|
||||
for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].lastIndexOf(prefix, 0) == 0)
|
||||
result.push(quote + atValues[i] + quote);
|
||||
} else { // An attribute name
|
||||
if (token.type == "attribute") {
|
||||
prefix = token.string;
|
||||
replaceToken = true;
|
||||
}
|
||||
for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.indexOf(prefix) == 0))
|
||||
for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.lastIndexOf(prefix, 0) == 0))
|
||||
result.push(attr);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
padding: 2px 5px;
|
||||
position: fixed;
|
||||
white-space: pre;
|
||||
white-space: pre-wrap;
|
||||
z-index: 100;
|
||||
max-width: 600px;
|
||||
opacity: 0;
|
||||
|
||||
@@ -112,7 +112,7 @@
|
||||
if (options.async)
|
||||
options.getAnnotations(cm, updateLinting, options);
|
||||
else
|
||||
updateLinting(cm, options.getAnnotations(cm.getValue(), options));
|
||||
updateLinting(cm, options.getAnnotations(cm.getValue(), options.options));
|
||||
}
|
||||
|
||||
function updateLinting(cm, annotationsNotSorted) {
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
this.edit = this.mv.edit;
|
||||
this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: true}, copyObj(options)));
|
||||
|
||||
this.diff = getDiff(orig, options.value);
|
||||
this.diff = getDiff(asString(orig), asString(options.value));
|
||||
this.diffOutOfDate = false;
|
||||
|
||||
this.showDifferences = options.showDifferences !== false;
|
||||
@@ -352,6 +352,11 @@
|
||||
}
|
||||
};
|
||||
|
||||
function asString(obj) {
|
||||
if (typeof obj == "string") return obj;
|
||||
else return obj.getValue();
|
||||
}
|
||||
|
||||
// Operations on diffs
|
||||
|
||||
var dmp = new diff_match_patch();
|
||||
|
||||
@@ -47,7 +47,11 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
|
||||
return outerToken;
|
||||
} else {
|
||||
var curInner = state.innerActive, oldContent = stream.string;
|
||||
var found = indexOf(oldContent, curInner.close, stream.pos);
|
||||
if (!curInner.close && stream.sol()) {
|
||||
state.innerActive = state.inner = null;
|
||||
return this.token(stream, state);
|
||||
}
|
||||
var found = curInner.close ? indexOf(oldContent, curInner.close, stream.pos) : -1;
|
||||
if (found == stream.pos) {
|
||||
stream.match(curInner.close);
|
||||
state.innerActive = state.inner = null;
|
||||
@@ -56,8 +60,6 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
|
||||
if (found > -1) stream.string = oldContent.slice(0, found);
|
||||
var innerToken = curInner.mode.token(stream, state.inner);
|
||||
if (found > -1) stream.string = oldContent;
|
||||
var cur = stream.current(), found = cur.indexOf(curInner.close);
|
||||
if (found > -1) stream.backUp(cur.length - found);
|
||||
|
||||
if (curInner.innerStyle) {
|
||||
if (innerToken) innerToken = innerToken + ' ' + curInner.innerStyle;
|
||||
|
||||
@@ -10,6 +10,7 @@ function splitLines(string){ return string.split(/\r?\n|\r/); };
|
||||
function StringStream(string) {
|
||||
this.pos = this.start = 0;
|
||||
this.string = string;
|
||||
this.lineStart = 0;
|
||||
}
|
||||
StringStream.prototype = {
|
||||
eol: function() {return this.pos >= this.string.length;},
|
||||
@@ -41,7 +42,7 @@ StringStream.prototype = {
|
||||
if (found > -1) {this.pos = found; return true;}
|
||||
},
|
||||
backUp: function(n) {this.pos -= n;},
|
||||
column: function() {return this.start;},
|
||||
column: function() {return this.start - this.lineStart;},
|
||||
indentation: function() {return 0;},
|
||||
match: function(pattern, consume, caseInsensitive) {
|
||||
if (typeof pattern == "string") {
|
||||
@@ -58,7 +59,12 @@ StringStream.prototype = {
|
||||
return match;
|
||||
}
|
||||
},
|
||||
current: function(){return this.string.slice(this.start, this.pos);}
|
||||
current: function(){return this.string.slice(this.start, this.pos);},
|
||||
hideFirstChars: function(n, inner) {
|
||||
this.lineStart += n;
|
||||
try { return inner(); }
|
||||
finally { this.lineStart -= n; }
|
||||
}
|
||||
};
|
||||
CodeMirror.StringStream = StringStream;
|
||||
|
||||
@@ -69,17 +75,26 @@ CodeMirror.startState = function (mode, a1, a2) {
|
||||
var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
|
||||
CodeMirror.defineMode = function (name, mode) { modes[name] = mode; };
|
||||
CodeMirror.defineMIME = function (mime, spec) { mimeModes[mime] = spec; };
|
||||
CodeMirror.getMode = function (options, spec) {
|
||||
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
|
||||
CodeMirror.resolveMode = function(spec) {
|
||||
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
|
||||
spec = mimeModes[spec];
|
||||
if (typeof spec == "string")
|
||||
var mname = spec, config = {};
|
||||
else if (spec != null)
|
||||
var mname = spec.name, config = spec;
|
||||
var mfactory = modes[mname];
|
||||
if (!mfactory) throw new Error("Unknown mode: " + spec);
|
||||
return mfactory(options, config || {});
|
||||
} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
|
||||
spec = mimeModes[spec.name];
|
||||
}
|
||||
if (typeof spec == "string") return {name: spec};
|
||||
else return spec || {name: "null"};
|
||||
};
|
||||
CodeMirror.getMode = function (options, spec) {
|
||||
spec = CodeMirror.resolveMode(spec);
|
||||
var mfactory = modes[spec.name];
|
||||
if (!mfactory) throw new Error("Unknown mode: " + spec);
|
||||
return mfactory(options, spec);
|
||||
};
|
||||
CodeMirror.registerHelper = CodeMirror.registerGlobalHelper = Math.min;
|
||||
CodeMirror.defineMode("null", function() {
|
||||
return {token: function(stream) {stream.skipToEnd();}};
|
||||
});
|
||||
CodeMirror.defineMIME("text/plain", "null");
|
||||
|
||||
CodeMirror.runMode = function (string, modespec, callback, options) {
|
||||
var mode = CodeMirror.getMode({ indentUnit: 2 }, modespec);
|
||||
@@ -122,7 +137,7 @@ CodeMirror.runMode = function (string, modespec, callback, options) {
|
||||
};
|
||||
}
|
||||
|
||||
var lines = splitLines(string), state = CodeMirror.startState(mode);
|
||||
var lines = splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);
|
||||
for (var i = 0, e = lines.length; i < e; ++i) {
|
||||
if (i) callback("\n");
|
||||
var stream = new CodeMirror.StringStream(lines[i]);
|
||||
|
||||
@@ -43,7 +43,7 @@ CodeMirror.runMode = function(string, modespec, callback, options) {
|
||||
};
|
||||
}
|
||||
|
||||
var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
|
||||
var lines = CodeMirror.splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);
|
||||
for (var i = 0, e = lines.length; i < e; ++i) {
|
||||
if (i) callback("\n");
|
||||
var stream = new CodeMirror.StringStream(lines[i]);
|
||||
|
||||
@@ -5,6 +5,7 @@ function splitLines(string){ return string.split(/\r?\n|\r/); };
|
||||
function StringStream(string) {
|
||||
this.pos = this.start = 0;
|
||||
this.string = string;
|
||||
this.lineStart = 0;
|
||||
}
|
||||
StringStream.prototype = {
|
||||
eol: function() {return this.pos >= this.string.length;},
|
||||
@@ -36,7 +37,7 @@ StringStream.prototype = {
|
||||
if (found > -1) {this.pos = found; return true;}
|
||||
},
|
||||
backUp: function(n) {this.pos -= n;},
|
||||
column: function() {return this.start;},
|
||||
column: function() {return this.start - this.lineStart;},
|
||||
indentation: function() {return 0;},
|
||||
match: function(pattern, consume, caseInsensitive) {
|
||||
if (typeof pattern == "string") {
|
||||
@@ -53,7 +54,12 @@ StringStream.prototype = {
|
||||
return match;
|
||||
}
|
||||
},
|
||||
current: function(){return this.string.slice(this.start, this.pos);}
|
||||
current: function(){return this.string.slice(this.start, this.pos);},
|
||||
hideFirstChars: function(n, inner) {
|
||||
this.lineStart += n;
|
||||
try { return inner(); }
|
||||
finally { this.lineStart -= n; }
|
||||
}
|
||||
};
|
||||
exports.StringStream = StringStream;
|
||||
|
||||
@@ -76,21 +82,26 @@ exports.defineMode("null", function() {
|
||||
});
|
||||
exports.defineMIME("text/plain", "null");
|
||||
|
||||
exports.getMode = function(options, spec) {
|
||||
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
|
||||
exports.resolveMode = function(spec) {
|
||||
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
|
||||
spec = mimeModes[spec];
|
||||
if (typeof spec == "string")
|
||||
var mname = spec, config = {};
|
||||
else if (spec != null)
|
||||
var mname = spec.name, config = spec;
|
||||
var mfactory = modes[mname];
|
||||
if (!mfactory) throw new Error("Unknown mode: " + spec);
|
||||
return mfactory(options, config || {});
|
||||
} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
|
||||
spec = mimeModes[spec.name];
|
||||
}
|
||||
if (typeof spec == "string") return {name: spec};
|
||||
else return spec || {name: "null"};
|
||||
};
|
||||
exports.getMode = function(options, spec) {
|
||||
spec = exports.resolveMode(mimeModes[spec]);
|
||||
var mfactory = modes[spec.name];
|
||||
if (!mfactory) throw new Error("Unknown mode: " + spec);
|
||||
return mfactory(options, spec);
|
||||
};
|
||||
exports.registerHelper = exports.registerGlobalHelper = Math.min;
|
||||
|
||||
exports.runMode = function(string, modespec, callback) {
|
||||
var mode = exports.getMode({indentUnit: 2}, modespec);
|
||||
var lines = splitLines(string), state = exports.startState(mode);
|
||||
var lines = splitLines(string), state = (options && options.state) || exports.startState(mode);
|
||||
for (var i = 0, e = lines.length; i < e; ++i) {
|
||||
if (i) callback("\n");
|
||||
var stream = new exports.StringStream(lines[i]);
|
||||
|
||||
@@ -7,7 +7,15 @@
|
||||
// Ctrl-G.
|
||||
|
||||
(function() {
|
||||
function searchOverlay(query) {
|
||||
function searchOverlay(query, caseInsensitive) {
|
||||
var startChar;
|
||||
if (typeof query == "string") {
|
||||
startChar = query.charAt(0);
|
||||
query = new RegExp("^" + query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"),
|
||||
caseInsensitive ? "i" : "");
|
||||
} else {
|
||||
query = new RegExp("^(?:" + query.source + ")", query.ignoreCase ? "i" : "");
|
||||
}
|
||||
if (typeof query == "string") return {token: function(stream) {
|
||||
if (stream.match(query)) return "searching";
|
||||
stream.next();
|
||||
@@ -17,6 +25,8 @@
|
||||
if (stream.match(query)) return "searching";
|
||||
while (!stream.eol()) {
|
||||
stream.next();
|
||||
if (startChar)
|
||||
stream.skipTo(startChar) || stream.skipToEnd();
|
||||
if (stream.match(query, false)) break;
|
||||
}
|
||||
}};
|
||||
@@ -29,13 +39,16 @@
|
||||
function getSearchState(cm) {
|
||||
return cm.state.search || (cm.state.search = new SearchState());
|
||||
}
|
||||
function queryCaseInsensitive(query) {
|
||||
return typeof query == "string" && query == query.toLowerCase();
|
||||
}
|
||||
function getSearchCursor(cm, query, pos) {
|
||||
// Heuristic: if the query string is all lowercase, do a case insensitive search.
|
||||
return cm.getSearchCursor(query, pos, typeof query == "string" && query == query.toLowerCase());
|
||||
return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));
|
||||
}
|
||||
function dialog(cm, text, shortText, f) {
|
||||
if (cm.openDialog) cm.openDialog(text, f);
|
||||
else f(prompt(shortText, ""));
|
||||
function dialog(cm, text, shortText, deflt, f) {
|
||||
if (cm.openDialog) cm.openDialog(text, f, {value: deflt});
|
||||
else f(prompt(shortText, deflt));
|
||||
}
|
||||
function confirmDialog(cm, text, shortText, fs) {
|
||||
if (cm.openConfirm) cm.openConfirm(text, fs);
|
||||
@@ -50,11 +63,11 @@
|
||||
function doSearch(cm, rev) {
|
||||
var state = getSearchState(cm);
|
||||
if (state.query) return findNext(cm, rev);
|
||||
dialog(cm, queryDialog, "Search for:", function(query) {
|
||||
dialog(cm, queryDialog, "Search for:", cm.getSelection(), function(query) {
|
||||
cm.operation(function() {
|
||||
if (!query || state.query) return;
|
||||
state.query = parseQuery(query);
|
||||
cm.removeOverlay(state.overlay);
|
||||
cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
|
||||
state.overlay = searchOverlay(state.query);
|
||||
cm.addOverlay(state.overlay);
|
||||
state.posFrom = state.posTo = cm.getCursor();
|
||||
@@ -70,6 +83,7 @@
|
||||
if (!cursor.find(rev)) return;
|
||||
}
|
||||
cm.setSelection(cursor.from(), cursor.to());
|
||||
cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
|
||||
state.posFrom = cursor.from(); state.posTo = cursor.to();
|
||||
});}
|
||||
function clearSearch(cm) {cm.operation(function() {
|
||||
@@ -84,10 +98,10 @@
|
||||
var replacementQueryDialog = 'With: <input type="text" style="width: 10em"/>';
|
||||
var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";
|
||||
function replace(cm, all) {
|
||||
dialog(cm, replaceQueryDialog, "Replace:", function(query) {
|
||||
dialog(cm, replaceQueryDialog, "Replace:", cm.getSelection(), function(query) {
|
||||
if (!query) return;
|
||||
query = parseQuery(query);
|
||||
dialog(cm, replacementQueryDialog, "Replace with:", function(text) {
|
||||
dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) {
|
||||
if (all) {
|
||||
cm.operation(function() {
|
||||
for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
|
||||
@@ -108,6 +122,7 @@
|
||||
(start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
|
||||
}
|
||||
cm.setSelection(cursor.from(), cursor.to());
|
||||
cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
|
||||
confirmDialog(cm, doReplaceConfirm, "Replace?",
|
||||
[function() {doReplace(match);}, advance]);
|
||||
};
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
match: match};
|
||||
};
|
||||
} else { // String query
|
||||
var origQuery = query;
|
||||
if (caseFold) query = query.toLowerCase();
|
||||
var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
|
||||
var target = query.split("\n");
|
||||
@@ -58,33 +59,45 @@
|
||||
this.matches = function() {};
|
||||
} else {
|
||||
this.matches = function(reverse, pos) {
|
||||
var line = fold(doc.getLine(pos.line)), len = query.length, match;
|
||||
if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
|
||||
: (match = line.indexOf(query, pos.ch)) != -1)
|
||||
return {from: Pos(pos.line, match),
|
||||
to: Pos(pos.line, match + len)};
|
||||
if (reverse) {
|
||||
var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig);
|
||||
var match = line.lastIndexOf(query);
|
||||
if (match > -1) {
|
||||
match = adjustPos(orig, line, match);
|
||||
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
|
||||
}
|
||||
} else {
|
||||
var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig);
|
||||
var match = line.indexOf(query);
|
||||
if (match > -1) {
|
||||
match = adjustPos(orig, line, match) + pos.ch;
|
||||
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
} else {
|
||||
var origTarget = origQuery.split("\n");
|
||||
this.matches = function(reverse, pos) {
|
||||
var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(doc.getLine(ln));
|
||||
var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
|
||||
if (reverse ? offsetA > pos.ch || offsetA != match.length
|
||||
: offsetA < pos.ch || offsetA != line.length - match.length)
|
||||
return;
|
||||
for (;;) {
|
||||
if (reverse ? !ln : ln == doc.lineCount() - 1) return;
|
||||
line = fold(doc.getLine(ln += reverse ? -1 : 1));
|
||||
match = target[reverse ? --idx : ++idx];
|
||||
if (idx > 0 && idx < target.length - 1) {
|
||||
if (line != match) return;
|
||||
else continue;
|
||||
}
|
||||
var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
|
||||
if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
|
||||
return;
|
||||
var start = Pos(pos.line, offsetA), end = Pos(ln, offsetB);
|
||||
return {from: reverse ? end : start, to: reverse ? start : end};
|
||||
var last = target.length - 1;
|
||||
if (reverse) {
|
||||
if (pos.line - (target.length - 1) < doc.firstLine()) return;
|
||||
if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return;
|
||||
var to = Pos(pos.line, origTarget[last].length);
|
||||
for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln)
|
||||
if (target[i] != fold(doc.getLine(ln))) return;
|
||||
var line = doc.getLine(ln), cut = line.length - origTarget[0].length;
|
||||
if (fold(line.slice(cut)) != target[0]) return;
|
||||
return {from: Pos(ln, cut), to: to};
|
||||
} else {
|
||||
if (pos.line + (target.length - 1) > doc.lastLine()) return;
|
||||
var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length;
|
||||
if (fold(line.slice(cut)) != target[0]) return;
|
||||
var from = Pos(pos.line, cut);
|
||||
for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln)
|
||||
if (target[i] != fold(doc.getLine(ln))) return;
|
||||
if (doc.getLine(ln).slice(0, origTarget[last].length) != target[last]) return;
|
||||
return {from: from, to: Pos(ln, origTarget[last].length)};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -106,7 +119,6 @@
|
||||
|
||||
for (;;) {
|
||||
if (this.pos = this.matches(reverse, pos)) {
|
||||
if (!this.pos.from || !this.pos.to) { console.log(this.matches, this.pos); }
|
||||
this.atOccurrence = true;
|
||||
return this.pos.match || true;
|
||||
}
|
||||
@@ -134,6 +146,18 @@
|
||||
}
|
||||
};
|
||||
|
||||
// Maps a position in a case-folded line back to a position in the original line
|
||||
// (compensating for codepoints increasing in number during folding)
|
||||
function adjustPos(orig, folded, pos) {
|
||||
if (orig.length == folded.length) return pos;
|
||||
for (var pos1 = Math.min(pos, orig.length);;) {
|
||||
var len1 = orig.slice(0, pos1).toLowerCase().length;
|
||||
if (len1 < pos) ++pos1;
|
||||
else if (len1 > pos) --pos1;
|
||||
else return pos1;
|
||||
}
|
||||
}
|
||||
|
||||
CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
|
||||
return new SearchCursor(this.doc, query, pos, caseFold);
|
||||
});
|
||||
|
||||
@@ -12,10 +12,10 @@
|
||||
CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
|
||||
var prev = old && old != CodeMirror.Init;
|
||||
if (val && !prev) {
|
||||
updateActiveLine(cm);
|
||||
cm.on("cursorActivity", updateActiveLine);
|
||||
updateActiveLine(cm, cm.getCursor().line);
|
||||
cm.on("beforeSelectionChange", selectionChange);
|
||||
} else if (!val && prev) {
|
||||
cm.off("cursorActivity", updateActiveLine);
|
||||
cm.off("beforeSelectionChange", selectionChange);
|
||||
clearActiveLine(cm);
|
||||
delete cm.state.activeLine;
|
||||
}
|
||||
@@ -28,12 +28,18 @@
|
||||
}
|
||||
}
|
||||
|
||||
function updateActiveLine(cm) {
|
||||
var line = cm.getLineHandleVisualStart(cm.getCursor().line);
|
||||
function updateActiveLine(cm, selectedLine) {
|
||||
var line = cm.getLineHandleVisualStart(selectedLine);
|
||||
if (cm.state.activeLine == line) return;
|
||||
clearActiveLine(cm);
|
||||
cm.addLineClass(line, "wrap", WRAP_CLASS);
|
||||
cm.addLineClass(line, "background", BACK_CLASS);
|
||||
cm.state.activeLine = line;
|
||||
cm.operation(function() {
|
||||
clearActiveLine(cm);
|
||||
cm.addLineClass(line, "wrap", WRAP_CLASS);
|
||||
cm.addLineClass(line, "background", BACK_CLASS);
|
||||
cm.state.activeLine = line;
|
||||
});
|
||||
}
|
||||
|
||||
function selectionChange(cm, sel) {
|
||||
updateActiveLine(cm, sel.head.line);
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -201,6 +201,11 @@
|
||||
cm.on("change", function() { cm.setExtending(false); });
|
||||
}
|
||||
|
||||
function clearMark(cm) {
|
||||
cm.setExtending(false);
|
||||
cm.setCursor(cm.getCursor());
|
||||
}
|
||||
|
||||
function getInput(cm, msg, f) {
|
||||
if (cm.openDialog)
|
||||
cm.openDialog(msg + ": <input type=\"text\" style=\"width: 10em\"/>", f, {bottom: true});
|
||||
@@ -234,6 +239,11 @@
|
||||
}
|
||||
}
|
||||
|
||||
function quit(cm) {
|
||||
cm.execCommand("clearSearch");
|
||||
clearMark(cm);
|
||||
}
|
||||
|
||||
// Actual keymap
|
||||
|
||||
var keyMap = CodeMirror.keyMap.emacs = {
|
||||
@@ -249,6 +259,7 @@
|
||||
}),
|
||||
"Alt-W": function(cm) {
|
||||
addToRing(cm.getSelection());
|
||||
clearMark(cm);
|
||||
},
|
||||
"Ctrl-Y": function(cm) {
|
||||
var start = cm.getCursor();
|
||||
@@ -334,7 +345,7 @@
|
||||
"Ctrl-/": repeated("undo"), "Shift-Ctrl--": repeated("undo"),
|
||||
"Ctrl-Z": repeated("undo"), "Cmd-Z": repeated("undo"),
|
||||
"Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd",
|
||||
"Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": "clearSearch", "Shift-Alt-5": "replace",
|
||||
"Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": quit, "Shift-Alt-5": "replace",
|
||||
"Alt-/": "autocomplete",
|
||||
"Ctrl-J": "newlineAndIndent", "Enter": false, "Tab": "indentAuto",
|
||||
|
||||
|
||||
211
applications/admin/static/codemirror/keymap/vim.js
vendored
211
applications/admin/static/codemirror/keymap/vim.js
vendored
@@ -76,12 +76,15 @@
|
||||
{ keys: ['<C-p>'], type: 'keyToKey', toKeys: ['k'] },
|
||||
{ keys: ['C-['], type: 'keyToKey', toKeys: ['<Esc>'] },
|
||||
{ keys: ['<C-c>'], type: 'keyToKey', toKeys: ['<Esc>'] },
|
||||
{ keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'] },
|
||||
{ keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'] },
|
||||
{ keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'], context: 'normal' },
|
||||
{ keys: ['s'], type: 'keyToKey', toKeys: ['x', 'i'], context: 'visual'},
|
||||
{ keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'], context: 'normal' },
|
||||
{ keys: ['S'], type: 'keyToKey', toKeys: ['d', 'c', 'c'], context: 'visual' },
|
||||
{ keys: ['<Home>'], type: 'keyToKey', toKeys: ['0'] },
|
||||
{ keys: ['<End>'], type: 'keyToKey', toKeys: ['$'] },
|
||||
{ keys: ['<PageUp>'], type: 'keyToKey', toKeys: ['<C-b>'] },
|
||||
{ keys: ['<PageDown>'], type: 'keyToKey', toKeys: ['<C-f>'] },
|
||||
{ keys: ['<CR>'], type: 'keyToKey', toKeys: ['j', '^'], context: 'normal' },
|
||||
// Motions
|
||||
{ keys: ['H'], type: 'motion',
|
||||
motion: 'moveToTopLine',
|
||||
@@ -245,6 +248,12 @@
|
||||
actionArgs: { forward: true }},
|
||||
{ keys: ['<C-o>'], type: 'action', action: 'jumpListWalk',
|
||||
actionArgs: { forward: false }},
|
||||
{ keys: ['<C-e>'], type: 'action',
|
||||
action: 'scroll',
|
||||
actionArgs: { forward: true, linewise: true }},
|
||||
{ keys: ['<C-y>'], type: 'action',
|
||||
action: 'scroll',
|
||||
actionArgs: { forward: false, linewise: true }},
|
||||
{ keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true,
|
||||
actionArgs: { insertAt: 'charAfter' }},
|
||||
{ keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true,
|
||||
@@ -322,12 +331,16 @@
|
||||
CodeMirror.defineOption('vimMode', false, function(cm, val) {
|
||||
if (val) {
|
||||
cm.setOption('keyMap', 'vim');
|
||||
cm.setOption('disableInput', true);
|
||||
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
|
||||
cm.on('beforeSelectionChange', beforeSelectionChange);
|
||||
maybeInitVimState(cm);
|
||||
CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
|
||||
} else if (cm.state.vim) {
|
||||
cm.setOption('keyMap', 'default');
|
||||
cm.setOption('disableInput', false);
|
||||
cm.off('beforeSelectionChange', beforeSelectionChange);
|
||||
CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
|
||||
cm.state.vim = null;
|
||||
}
|
||||
});
|
||||
@@ -340,6 +353,18 @@
|
||||
head.ch--;
|
||||
}
|
||||
}
|
||||
function getOnPasteFn(cm) {
|
||||
var vim = cm.state.vim;
|
||||
if (!vim.onPasteFn) {
|
||||
vim.onPasteFn = function() {
|
||||
if (!vim.insertMode) {
|
||||
cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
|
||||
actions.enterInsertMode(cm, {}, vim);
|
||||
}
|
||||
};
|
||||
}
|
||||
return vim.onPasteFn;
|
||||
}
|
||||
|
||||
var numberRegex = /[\d]/;
|
||||
var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
|
||||
@@ -547,9 +572,9 @@
|
||||
maybeInitVimState_: maybeInitVimState,
|
||||
|
||||
InsertModeKey: InsertModeKey,
|
||||
map: function(lhs, rhs) {
|
||||
map: function(lhs, rhs, ctx) {
|
||||
// Add user defined key bindings.
|
||||
exCommandDispatcher.map(lhs, rhs);
|
||||
exCommandDispatcher.map(lhs, rhs, ctx);
|
||||
},
|
||||
defineEx: function(name, prefix, func){
|
||||
if (name.indexOf(prefix) !== 0) {
|
||||
@@ -609,6 +634,9 @@
|
||||
}
|
||||
commandDispatcher.processCommand(cm, vim, command);
|
||||
}
|
||||
},
|
||||
handleEx: function(cm, input) {
|
||||
exCommandDispatcher.processCommand(cm, input);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -695,6 +723,9 @@
|
||||
if (linewise && text.charAt(0) == '\n') {
|
||||
text = text.slice(1) + '\n';
|
||||
}
|
||||
if(linewise && text.charAt(text.length - 1) !== '\n'){
|
||||
text += '\n';
|
||||
}
|
||||
// Lowercase and uppercase registers refer to the same register.
|
||||
// Uppercase just means append.
|
||||
var register = this.isValidRegister(registerName) ?
|
||||
@@ -766,44 +797,80 @@
|
||||
matchCommand: function(key, keyMap, vim) {
|
||||
var inputState = vim.inputState;
|
||||
var keys = inputState.keyBuffer.concat(key);
|
||||
var matchedCommands = [];
|
||||
var selectedCharacter;
|
||||
for (var i = 0; i < keyMap.length; i++) {
|
||||
var command = keyMap[i];
|
||||
if (matchKeysPartial(keys, command.keys)) {
|
||||
if (keys.length < command.keys.length) {
|
||||
// Matches part of a multi-key command. Buffer and wait for next
|
||||
// stroke.
|
||||
inputState.keyBuffer.push(key);
|
||||
return null;
|
||||
}
|
||||
if (inputState.operator && command.type == 'action') {
|
||||
// Ignore matched action commands after an operator. Operators
|
||||
// only operate on motions. This check is really for text
|
||||
// objects since aW, a[ etcs conflicts with a.
|
||||
continue;
|
||||
}
|
||||
// Matches whole comand. Return the command.
|
||||
// Match commands that take <character> as an argument.
|
||||
if (command.keys[keys.length - 1] == 'character') {
|
||||
inputState.selectedCharacter = keys[keys.length - 1];
|
||||
if(inputState.selectedCharacter.length>1){
|
||||
switch(inputState.selectedCharacter){
|
||||
selectedCharacter = keys[keys.length - 1];
|
||||
if(selectedCharacter.length>1){
|
||||
switch(selectedCharacter){
|
||||
case '<CR>':
|
||||
inputState.selectedCharacter='\n';
|
||||
selectedCharacter='\n';
|
||||
break;
|
||||
case '<Space>':
|
||||
inputState.selectedCharacter=' ';
|
||||
selectedCharacter=' ';
|
||||
break;
|
||||
default:
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Add the command to the list of matched commands. Choose the best
|
||||
// command later.
|
||||
matchedCommands.push(command);
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the command if it is a full match, or null if not.
|
||||
function getFullyMatchedCommandOrNull(command) {
|
||||
if (keys.length < command.keys.length) {
|
||||
// Matches part of a multi-key command. Buffer and wait for next
|
||||
// stroke.
|
||||
inputState.keyBuffer.push(key);
|
||||
return null;
|
||||
} else {
|
||||
if (command.keys[keys.length - 1] == 'character') {
|
||||
inputState.selectedCharacter = selectedCharacter;
|
||||
}
|
||||
// Clear the buffer since a full match was found.
|
||||
inputState.keyBuffer = [];
|
||||
return command;
|
||||
}
|
||||
}
|
||||
// Clear the buffer since there are no partial matches.
|
||||
inputState.keyBuffer = [];
|
||||
return null;
|
||||
|
||||
if (!matchedCommands.length) {
|
||||
// Clear the buffer since there were no matches.
|
||||
inputState.keyBuffer = [];
|
||||
return null;
|
||||
} else if (matchedCommands.length == 1) {
|
||||
return getFullyMatchedCommandOrNull(matchedCommands[0]);
|
||||
} else {
|
||||
// Find the best match in the list of matchedCommands.
|
||||
var context = vim.visualMode ? 'visual' : 'normal';
|
||||
var bestMatch; // Default to first in the list.
|
||||
for (var i = 0; i < matchedCommands.length; i++) {
|
||||
var current = matchedCommands[i];
|
||||
if (current.context == context) {
|
||||
bestMatch = current;
|
||||
break;
|
||||
} else if (!bestMatch && !current.context) {
|
||||
// Only set an imperfect match to best match if no best match is
|
||||
// set and the imperfect match is not restricted to another
|
||||
// context.
|
||||
bestMatch = current;
|
||||
}
|
||||
}
|
||||
return getFullyMatchedCommandOrNull(bestMatch);
|
||||
}
|
||||
},
|
||||
processCommand: function(cm, vim, command) {
|
||||
vim.inputState.repeatOverride = command.repeatOverride;
|
||||
@@ -1598,6 +1665,43 @@
|
||||
markPos = markPos ? markPos : cm.getCursor();
|
||||
cm.setCursor(markPos);
|
||||
},
|
||||
scroll: function(cm, actionArgs, vim) {
|
||||
if (vim.visualMode) {
|
||||
return;
|
||||
}
|
||||
var repeat = actionArgs.repeat || 1;
|
||||
var lineHeight = cm.defaultTextHeight();
|
||||
var top = cm.getScrollInfo().top;
|
||||
var delta = lineHeight * repeat;
|
||||
var newPos = actionArgs.forward ? top + delta : top - delta;
|
||||
var cursor = cm.getCursor();
|
||||
var cursorCoords = cm.charCoords(cursor, 'local');
|
||||
if (actionArgs.forward) {
|
||||
if (newPos > cursorCoords.top) {
|
||||
cursor.line += (newPos - cursorCoords.top) / lineHeight;
|
||||
cursor.line = Math.ceil(cursor.line);
|
||||
cm.setCursor(cursor);
|
||||
cursorCoords = cm.charCoords(cursor, 'local');
|
||||
cm.scrollTo(null, cursorCoords.top);
|
||||
} else {
|
||||
// Cursor stays within bounds. Just reposition the scroll window.
|
||||
cm.scrollTo(null, newPos);
|
||||
}
|
||||
} else {
|
||||
var newBottom = newPos + cm.getScrollInfo().clientHeight;
|
||||
if (newBottom < cursorCoords.bottom) {
|
||||
cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
|
||||
cursor.line = Math.floor(cursor.line);
|
||||
cm.setCursor(cursor);
|
||||
cursorCoords = cm.charCoords(cursor, 'local');
|
||||
cm.scrollTo(
|
||||
null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
|
||||
} else {
|
||||
// Cursor stays within bounds. Just reposition the scroll window.
|
||||
cm.scrollTo(null, newPos);
|
||||
}
|
||||
}
|
||||
},
|
||||
scrollToCursor: function(cm, actionArgs) {
|
||||
var lineNum = cm.getCursor().line;
|
||||
var charCoords = cm.charCoords({line: lineNum, ch: 0}, 'local');
|
||||
@@ -1653,6 +1757,7 @@
|
||||
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
|
||||
}
|
||||
cm.setOption('keyMap', 'vim-insert');
|
||||
cm.setOption('disableInput', false);
|
||||
if (actionArgs && actionArgs.replace) {
|
||||
// Handle Replace-mode as a special case of insert mode.
|
||||
cm.toggleOverwrite(true);
|
||||
@@ -2688,10 +2793,9 @@
|
||||
return regexp;
|
||||
}
|
||||
function showConfirm(cm, text) {
|
||||
if (cm.openConfirm) {
|
||||
cm.openConfirm('<span style="color: red">' + text +
|
||||
'</span> <button type="button">OK</button>', function() {},
|
||||
{bottom: true});
|
||||
if (cm.openNotification) {
|
||||
cm.openNotification('<span style="color: red">' + text + '</span>',
|
||||
{bottom: true, duration: 5000});
|
||||
} else {
|
||||
alert(text);
|
||||
}
|
||||
@@ -2859,14 +2963,16 @@
|
||||
// pair of commands that have a shared prefix, at least one of their
|
||||
// shortNames must not match the prefix of the other command.
|
||||
var defaultExCommandMap = [
|
||||
{ name: 'map', type: 'builtIn' },
|
||||
{ name: 'write', shortName: 'w', type: 'builtIn' },
|
||||
{ name: 'undo', shortName: 'u', type: 'builtIn' },
|
||||
{ name: 'redo', shortName: 'red', type: 'builtIn' },
|
||||
{ name: 'sort', shortName: 'sor', type: 'builtIn'},
|
||||
{ name: 'substitute', shortName: 's', type: 'builtIn'},
|
||||
{ name: 'nohlsearch', shortName: 'noh', type: 'builtIn'},
|
||||
{ name: 'delmarks', shortName: 'delm', type: 'builtin'}
|
||||
{ name: 'map' },
|
||||
{ name: 'nmap', shortName: 'nm' },
|
||||
{ name: 'vmap', shortName: 'vm' },
|
||||
{ name: 'write', shortName: 'w' },
|
||||
{ name: 'undo', shortName: 'u' },
|
||||
{ name: 'redo', shortName: 'red' },
|
||||
{ name: 'sort', shortName: 'sor' },
|
||||
{ name: 'substitute', shortName: 's' },
|
||||
{ name: 'nohlsearch', shortName: 'noh' },
|
||||
{ name: 'delmarks', shortName: 'delm' }
|
||||
];
|
||||
Vim.ExCommandDispatcher = function() {
|
||||
this.buildCommandMap_();
|
||||
@@ -2918,6 +3024,7 @@
|
||||
exCommands[commandName](cm, params);
|
||||
} catch(e) {
|
||||
showConfirm(cm, e);
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
parseInput_: function(cm, inputStream, result) {
|
||||
@@ -3000,8 +3107,9 @@
|
||||
this.commandMap_[key] = command;
|
||||
}
|
||||
},
|
||||
map: function(lhs, rhs) {
|
||||
map: function(lhs, rhs, ctx) {
|
||||
if (lhs != ':' && lhs.charAt(0) == ':') {
|
||||
if (ctx) { throw Error('Mode not supported for ex mappings'); }
|
||||
var commandName = lhs.substring(1);
|
||||
if (rhs != ':' && rhs.charAt(0) == ':') {
|
||||
// Ex to Ex mapping
|
||||
@@ -3021,17 +3129,21 @@
|
||||
} else {
|
||||
if (rhs != ':' && rhs.charAt(0) == ':') {
|
||||
// Key to Ex mapping.
|
||||
defaultKeymap.unshift({
|
||||
var mapping = {
|
||||
keys: parseKeyString(lhs),
|
||||
type: 'keyToEx',
|
||||
exArgs: { input: rhs.substring(1) }});
|
||||
exArgs: { input: rhs.substring(1) }};
|
||||
if (ctx) { mapping.context = ctx; }
|
||||
defaultKeymap.unshift(mapping);
|
||||
} else {
|
||||
// Key to key mapping
|
||||
defaultKeymap.unshift({
|
||||
var mapping = {
|
||||
keys: parseKeyString(lhs),
|
||||
type: 'keyToKey',
|
||||
toKeys: parseKeyString(rhs)
|
||||
});
|
||||
};
|
||||
if (ctx) { mapping.context = ctx; }
|
||||
defaultKeymap.unshift(mapping);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3053,7 +3165,7 @@
|
||||
}
|
||||
|
||||
var exCommands = {
|
||||
map: function(cm, params) {
|
||||
map: function(cm, params, ctx) {
|
||||
var mapArgs = params.args;
|
||||
if (!mapArgs || mapArgs.length < 2) {
|
||||
if (cm) {
|
||||
@@ -3061,8 +3173,10 @@
|
||||
}
|
||||
return;
|
||||
}
|
||||
exCommandDispatcher.map(mapArgs[0], mapArgs[1], cm);
|
||||
exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
|
||||
},
|
||||
nmap: function(cm, params) { this.map(cm, params, 'normal'); },
|
||||
vmap: function(cm, params) { this.map(cm, params, 'visual'); },
|
||||
move: function(cm, params) {
|
||||
commandDispatcher.processCommand(cm, cm.state.vim, {
|
||||
type: 'motion',
|
||||
@@ -3078,7 +3192,7 @@
|
||||
var args = new CodeMirror.StringStream(params.argString);
|
||||
if (args.eat('!')) { reverse = true; }
|
||||
if (args.eol()) { return; }
|
||||
if (!args.eatSpace()) { throw new Error('invalid arguments ' + args.match(/.*/)[0]); }
|
||||
if (!args.eatSpace()) { return 'Invalid arguments'; }
|
||||
var opts = args.match(/[a-z]+/);
|
||||
if (opts) {
|
||||
opts = opts[0];
|
||||
@@ -3087,13 +3201,17 @@
|
||||
var decimal = opts.indexOf('d') != -1 && 1;
|
||||
var hex = opts.indexOf('x') != -1 && 1;
|
||||
var octal = opts.indexOf('o') != -1 && 1;
|
||||
if (decimal + hex + octal > 1) { throw new Error('invalid arguments'); }
|
||||
if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
|
||||
number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
|
||||
}
|
||||
if (args.eatSpace() && args.match(/\/.*\//)) { throw new Error('patterns not supported'); }
|
||||
if (args.eatSpace() && args.match(/\/.*\//)) { 'patterns not supported'; }
|
||||
}
|
||||
}
|
||||
parseArgs();
|
||||
var err = parseArgs();
|
||||
if (err) {
|
||||
showConfirm(cm, err + ': ' + params.argString);
|
||||
return;
|
||||
}
|
||||
var lineStart = params.line || cm.firstLine();
|
||||
var lineEnd = params.lineEnd || params.line || cm.lastLine();
|
||||
if (lineStart == lineEnd) { return; }
|
||||
@@ -3214,13 +3332,13 @@
|
||||
clearSearchHighlight(cm);
|
||||
},
|
||||
delmarks: function(cm, params) {
|
||||
if (!params.argString || !params.argString.trim()) {
|
||||
if (!params.argString || !trim(params.argString)) {
|
||||
showConfirm(cm, 'Argument required');
|
||||
return;
|
||||
}
|
||||
|
||||
var state = cm.state.vim;
|
||||
var stream = new CodeMirror.StringStream(params.argString.trim());
|
||||
var stream = new CodeMirror.StringStream(trim(params.argString));
|
||||
while (!stream.eol()) {
|
||||
stream.eatSpace();
|
||||
|
||||
@@ -3357,7 +3475,8 @@
|
||||
// Actually do replace.
|
||||
next();
|
||||
if (done) {
|
||||
throw new Error('No matches for ' + query.source);
|
||||
showConfirm(cm, 'No matches for ' + query.source);
|
||||
return;
|
||||
}
|
||||
if (!confirm) {
|
||||
replaceAll();
|
||||
@@ -3408,7 +3527,6 @@
|
||||
|
||||
var cmToVimKeymap = {
|
||||
'nofallthrough': true,
|
||||
'disableInput': true,
|
||||
'style': 'fat-cursor'
|
||||
};
|
||||
function bindKeys(keys, modifier) {
|
||||
@@ -3455,6 +3573,7 @@
|
||||
cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
|
||||
vim.insertMode = false;
|
||||
cm.setOption('keyMap', 'vim');
|
||||
cm.setOption('disableInput', true);
|
||||
cm.toggleOverwrite(false); // exit replace mode if we were in it.
|
||||
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
|
||||
}
|
||||
|
||||
@@ -74,7 +74,6 @@
|
||||
.cm-s-default .cm-string {color: #a11;}
|
||||
.cm-s-default .cm-string-2 {color: #f50;}
|
||||
.cm-s-default .cm-meta {color: #555;}
|
||||
.cm-s-default .cm-error {color: #f00;}
|
||||
.cm-s-default .cm-qualifier {color: #555;}
|
||||
.cm-s-default .cm-builtin {color: #30a;}
|
||||
.cm-s-default .cm-bracket {color: #997;}
|
||||
@@ -91,6 +90,7 @@
|
||||
.cm-em {font-style: italic;}
|
||||
.cm-link {text-decoration: underline;}
|
||||
|
||||
.cm-s-default .cm-error {color: #f00;}
|
||||
.cm-invalidchar {color: #f00;}
|
||||
|
||||
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
160
applications/admin/static/codemirror/mode/apl/apl.js
vendored
160
applications/admin/static/codemirror/mode/apl/apl.js
vendored
@@ -1,160 +0,0 @@
|
||||
CodeMirror.defineMode("apl", function() {
|
||||
var builtInOps = {
|
||||
".": "innerProduct",
|
||||
"\\": "scan",
|
||||
"/": "reduce",
|
||||
"⌿": "reduce1Axis",
|
||||
"⍀": "scan1Axis",
|
||||
"¨": "each",
|
||||
"⍣": "power"
|
||||
};
|
||||
var builtInFuncs = {
|
||||
"+": ["conjugate", "add"],
|
||||
"−": ["negate", "subtract"],
|
||||
"×": ["signOf", "multiply"],
|
||||
"÷": ["reciprocal", "divide"],
|
||||
"⌈": ["ceiling", "greaterOf"],
|
||||
"⌊": ["floor", "lesserOf"],
|
||||
"∣": ["absolute", "residue"],
|
||||
"⍳": ["indexGenerate", "indexOf"],
|
||||
"?": ["roll", "deal"],
|
||||
"⋆": ["exponentiate", "toThePowerOf"],
|
||||
"⍟": ["naturalLog", "logToTheBase"],
|
||||
"○": ["piTimes", "circularFuncs"],
|
||||
"!": ["factorial", "binomial"],
|
||||
"⌹": ["matrixInverse", "matrixDivide"],
|
||||
"<": [null, "lessThan"],
|
||||
"≤": [null, "lessThanOrEqual"],
|
||||
"=": [null, "equals"],
|
||||
">": [null, "greaterThan"],
|
||||
"≥": [null, "greaterThanOrEqual"],
|
||||
"≠": [null, "notEqual"],
|
||||
"≡": ["depth", "match"],
|
||||
"≢": [null, "notMatch"],
|
||||
"∈": ["enlist", "membership"],
|
||||
"⍷": [null, "find"],
|
||||
"∪": ["unique", "union"],
|
||||
"∩": [null, "intersection"],
|
||||
"∼": ["not", "without"],
|
||||
"∨": [null, "or"],
|
||||
"∧": [null, "and"],
|
||||
"⍱": [null, "nor"],
|
||||
"⍲": [null, "nand"],
|
||||
"⍴": ["shapeOf", "reshape"],
|
||||
",": ["ravel", "catenate"],
|
||||
"⍪": [null, "firstAxisCatenate"],
|
||||
"⌽": ["reverse", "rotate"],
|
||||
"⊖": ["axis1Reverse", "axis1Rotate"],
|
||||
"⍉": ["transpose", null],
|
||||
"↑": ["first", "take"],
|
||||
"↓": [null, "drop"],
|
||||
"⊂": ["enclose", "partitionWithAxis"],
|
||||
"⊃": ["diclose", "pick"],
|
||||
"⌷": [null, "index"],
|
||||
"⍋": ["gradeUp", null],
|
||||
"⍒": ["gradeDown", null],
|
||||
"⊤": ["encode", null],
|
||||
"⊥": ["decode", null],
|
||||
"⍕": ["format", "formatByExample"],
|
||||
"⍎": ["execute", null],
|
||||
"⊣": ["stop", "left"],
|
||||
"⊢": ["pass", "right"]
|
||||
};
|
||||
|
||||
var isOperator = /[\.\/⌿⍀¨⍣]/;
|
||||
var isNiladic = /⍬/;
|
||||
var isFunction = /[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/;
|
||||
var isArrow = /←/;
|
||||
var isComment = /[⍝#].*$/;
|
||||
|
||||
var stringEater = function(type) {
|
||||
var prev;
|
||||
prev = false;
|
||||
return function(c) {
|
||||
prev = c;
|
||||
if (c === type) {
|
||||
return prev === "\\";
|
||||
}
|
||||
return true;
|
||||
};
|
||||
};
|
||||
return {
|
||||
startState: function() {
|
||||
return {
|
||||
prev: false,
|
||||
func: false,
|
||||
op: false,
|
||||
string: false,
|
||||
escape: false
|
||||
};
|
||||
},
|
||||
token: function(stream, state) {
|
||||
var ch, funcName, word;
|
||||
if (stream.eatSpace()) {
|
||||
return null;
|
||||
}
|
||||
ch = stream.next();
|
||||
if (ch === '"' || ch === "'") {
|
||||
stream.eatWhile(stringEater(ch));
|
||||
stream.next();
|
||||
state.prev = true;
|
||||
return "string";
|
||||
}
|
||||
if (/[\[{\(]/.test(ch)) {
|
||||
state.prev = false;
|
||||
return null;
|
||||
}
|
||||
if (/[\]}\)]/.test(ch)) {
|
||||
state.prev = true;
|
||||
return null;
|
||||
}
|
||||
if (isNiladic.test(ch)) {
|
||||
state.prev = false;
|
||||
return "niladic";
|
||||
}
|
||||
if (/[¯\d]/.test(ch)) {
|
||||
if (state.func) {
|
||||
state.func = false;
|
||||
state.prev = false;
|
||||
} else {
|
||||
state.prev = true;
|
||||
}
|
||||
stream.eatWhile(/[\w\.]/);
|
||||
return "number";
|
||||
}
|
||||
if (isOperator.test(ch)) {
|
||||
return "operator apl-" + builtInOps[ch];
|
||||
}
|
||||
if (isArrow.test(ch)) {
|
||||
return "apl-arrow";
|
||||
}
|
||||
if (isFunction.test(ch)) {
|
||||
funcName = "apl-";
|
||||
if (builtInFuncs[ch] != null) {
|
||||
if (state.prev) {
|
||||
funcName += builtInFuncs[ch][1];
|
||||
} else {
|
||||
funcName += builtInFuncs[ch][0];
|
||||
}
|
||||
}
|
||||
state.func = true;
|
||||
state.prev = false;
|
||||
return "function " + funcName;
|
||||
}
|
||||
if (isComment.test(ch)) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
if (ch === "∘" && stream.peek() === ".") {
|
||||
stream.next();
|
||||
return "function jot-dot";
|
||||
}
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
word = stream.current();
|
||||
state.prev = true;
|
||||
return "keyword";
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/apl", "apl");
|
||||
@@ -1,72 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: APL mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/edit/matchbrackets.js"></script>
|
||||
<script src="./apl.js"></script>
|
||||
<style>
|
||||
.CodeMirror { border: 2px inset #dee; }
|
||||
</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">APL</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>APL mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
⍝ Conway's game of life
|
||||
|
||||
⍝ This example was inspired by the impressive demo at
|
||||
⍝ http://www.youtube.com/watch?v=a9xAKttWgP4
|
||||
|
||||
⍝ Create a matrix:
|
||||
⍝ 0 1 1
|
||||
⍝ 1 1 0
|
||||
⍝ 0 1 0
|
||||
creature ← (3 3 ⍴ ⍳ 9) ∈ 1 2 3 4 7 ⍝ Original creature from demo
|
||||
creature ← (3 3 ⍴ ⍳ 9) ∈ 1 3 6 7 8 ⍝ Glider
|
||||
|
||||
⍝ Place the creature on a larger board, near the centre
|
||||
board ← ¯1 ⊖ ¯2 ⌽ 5 7 ↑ creature
|
||||
|
||||
⍝ A function to move from one generation to the next
|
||||
life ← {∨/ 1 ⍵ ∧ 3 4 = ⊂+/ +⌿ 1 0 ¯1 ∘.⊖ 1 0 ¯1 ⌽¨ ⊂⍵}
|
||||
|
||||
⍝ Compute n-th generation and format it as a
|
||||
⍝ character matrix
|
||||
gen ← {' #'[(life ⍣ ⍵) board]}
|
||||
|
||||
⍝ Show first three generations
|
||||
(gen 1) (gen 2) (gen 3)
|
||||
</textarea></form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
mode: "text/apl"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p>Simple mode that tries to handle APL as well as it can.</p>
|
||||
<p>It attempts to label functions/operators based upon
|
||||
monadic/dyadic usage (but this is far from fully fleshed out).
|
||||
This means there are meaningful classnames so hover states can
|
||||
have popups etc.</p>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/apl</code> (APL code)</p>
|
||||
</article>
|
||||
@@ -1,183 +0,0 @@
|
||||
/*
|
||||
* =====================================================================================
|
||||
*
|
||||
* Filename: mode/asterisk/asterisk.js
|
||||
*
|
||||
* Description: CodeMirror mode for Asterisk dialplan
|
||||
*
|
||||
* Created: 05/17/2012 09:20:25 PM
|
||||
* Revision: none
|
||||
*
|
||||
* Author: Stas Kobzar (stas@modulis.ca),
|
||||
* Company: Modulis.ca Inc.
|
||||
*
|
||||
* =====================================================================================
|
||||
*/
|
||||
|
||||
CodeMirror.defineMode("asterisk", function() {
|
||||
var atoms = ["exten", "same", "include","ignorepat","switch"],
|
||||
dpcmd = ["#include","#exec"],
|
||||
apps = [
|
||||
"addqueuemember","adsiprog","aelsub","agentlogin","agentmonitoroutgoing","agi",
|
||||
"alarmreceiver","amd","answer","authenticate","background","backgrounddetect",
|
||||
"bridge","busy","callcompletioncancel","callcompletionrequest","celgenuserevent",
|
||||
"changemonitor","chanisavail","channelredirect","chanspy","clearhash","confbridge",
|
||||
"congestion","continuewhile","controlplayback","dahdiacceptr2call","dahdibarge",
|
||||
"dahdiras","dahdiscan","dahdisendcallreroutingfacility","dahdisendkeypadfacility",
|
||||
"datetime","dbdel","dbdeltree","deadagi","dial","dictate","directory","disa",
|
||||
"dumpchan","eagi","echo","endwhile","exec","execif","execiftime","exitwhile","extenspy",
|
||||
"externalivr","festival","flash","followme","forkcdr","getcpeid","gosub","gosubif",
|
||||
"goto","gotoif","gotoiftime","hangup","iax2provision","ices","importvar","incomplete",
|
||||
"ivrdemo","jabberjoin","jabberleave","jabbersend","jabbersendgroup","jabberstatus",
|
||||
"jack","log","macro","macroexclusive","macroexit","macroif","mailboxexists","meetme",
|
||||
"meetmeadmin","meetmechanneladmin","meetmecount","milliwatt","minivmaccmess","minivmdelete",
|
||||
"minivmgreet","minivmmwi","minivmnotify","minivmrecord","mixmonitor","monitor","morsecode",
|
||||
"mp3player","mset","musiconhold","nbscat","nocdr","noop","odbc","odbc","odbcfinish",
|
||||
"originate","ospauth","ospfinish","osplookup","ospnext","page","park","parkandannounce",
|
||||
"parkedcall","pausemonitor","pausequeuemember","pickup","pickupchan","playback","playtones",
|
||||
"privacymanager","proceeding","progress","queue","queuelog","raiseexception","read","readexten",
|
||||
"readfile","receivefax","receivefax","receivefax","record","removequeuemember",
|
||||
"resetcdr","retrydial","return","ringing","sayalpha","saycountedadj","saycountednoun",
|
||||
"saycountpl","saydigits","saynumber","sayphonetic","sayunixtime","senddtmf","sendfax",
|
||||
"sendfax","sendfax","sendimage","sendtext","sendurl","set","setamaflags",
|
||||
"setcallerpres","setmusiconhold","sipaddheader","sipdtmfmode","sipremoveheader","skel",
|
||||
"slastation","slatrunk","sms","softhangup","speechactivategrammar","speechbackground",
|
||||
"speechcreate","speechdeactivategrammar","speechdestroy","speechloadgrammar","speechprocessingsound",
|
||||
"speechstart","speechunloadgrammar","stackpop","startmusiconhold","stopmixmonitor","stopmonitor",
|
||||
"stopmusiconhold","stopplaytones","system","testclient","testserver","transfer","tryexec",
|
||||
"trysystem","unpausemonitor","unpausequeuemember","userevent","verbose","vmauthenticate",
|
||||
"vmsayname","voicemail","voicemailmain","wait","waitexten","waitfornoise","waitforring",
|
||||
"waitforsilence","waitmusiconhold","waituntil","while","zapateller"
|
||||
];
|
||||
|
||||
function basicToken(stream,state){
|
||||
var cur = '';
|
||||
var ch = '';
|
||||
ch = stream.next();
|
||||
// comment
|
||||
if(ch == ";") {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
// context
|
||||
if(ch == '[') {
|
||||
stream.skipTo(']');
|
||||
stream.eat(']');
|
||||
return "header";
|
||||
}
|
||||
// string
|
||||
if(ch == '"') {
|
||||
stream.skipTo('"');
|
||||
return "string";
|
||||
}
|
||||
if(ch == "'") {
|
||||
stream.skipTo("'");
|
||||
return "string-2";
|
||||
}
|
||||
// dialplan commands
|
||||
if(ch == '#') {
|
||||
stream.eatWhile(/\w/);
|
||||
cur = stream.current();
|
||||
if(dpcmd.indexOf(cur) !== -1) {
|
||||
stream.skipToEnd();
|
||||
return "strong";
|
||||
}
|
||||
}
|
||||
// application args
|
||||
if(ch == '$'){
|
||||
var ch1 = stream.peek();
|
||||
if(ch1 == '{'){
|
||||
stream.skipTo('}');
|
||||
stream.eat('}');
|
||||
return "variable-3";
|
||||
}
|
||||
}
|
||||
// extension
|
||||
stream.eatWhile(/\w/);
|
||||
cur = stream.current();
|
||||
if(atoms.indexOf(cur) !== -1) {
|
||||
state.extenStart = true;
|
||||
switch(cur) {
|
||||
case 'same': state.extenSame = true; break;
|
||||
case 'include':
|
||||
case 'switch':
|
||||
case 'ignorepat':
|
||||
state.extenInclude = true;break;
|
||||
default:break;
|
||||
}
|
||||
return "atom";
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
startState: function() {
|
||||
return {
|
||||
extenStart: false,
|
||||
extenSame: false,
|
||||
extenInclude: false,
|
||||
extenExten: false,
|
||||
extenPriority: false,
|
||||
extenApplication: false
|
||||
};
|
||||
},
|
||||
token: function(stream, state) {
|
||||
|
||||
var cur = '';
|
||||
var ch = '';
|
||||
if(stream.eatSpace()) return null;
|
||||
// extension started
|
||||
if(state.extenStart){
|
||||
stream.eatWhile(/[^\s]/);
|
||||
cur = stream.current();
|
||||
if(/^=>?$/.test(cur)){
|
||||
state.extenExten = true;
|
||||
state.extenStart = false;
|
||||
return "strong";
|
||||
} else {
|
||||
state.extenStart = false;
|
||||
stream.skipToEnd();
|
||||
return "error";
|
||||
}
|
||||
} else if(state.extenExten) {
|
||||
// set exten and priority
|
||||
state.extenExten = false;
|
||||
state.extenPriority = true;
|
||||
stream.eatWhile(/[^,]/);
|
||||
if(state.extenInclude) {
|
||||
stream.skipToEnd();
|
||||
state.extenPriority = false;
|
||||
state.extenInclude = false;
|
||||
}
|
||||
if(state.extenSame) {
|
||||
state.extenPriority = false;
|
||||
state.extenSame = false;
|
||||
state.extenApplication = true;
|
||||
}
|
||||
return "tag";
|
||||
} else if(state.extenPriority) {
|
||||
state.extenPriority = false;
|
||||
state.extenApplication = true;
|
||||
ch = stream.next(); // get comma
|
||||
if(state.extenSame) return null;
|
||||
stream.eatWhile(/[^,]/);
|
||||
return "number";
|
||||
} else if(state.extenApplication) {
|
||||
stream.eatWhile(/,/);
|
||||
cur = stream.current();
|
||||
if(cur === ',') return null;
|
||||
stream.eatWhile(/\w/);
|
||||
cur = stream.current().toLowerCase();
|
||||
state.extenApplication = false;
|
||||
if(apps.indexOf(cur) !== -1){
|
||||
return "def strong";
|
||||
}
|
||||
} else{
|
||||
return basicToken(stream,state);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-asterisk", "asterisk");
|
||||
@@ -1,154 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Asterisk dialplan mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="asterisk.js"></script>
|
||||
<style>
|
||||
.CodeMirror {border: 1px solid #999;}
|
||||
.cm-s-default span.cm-arrow { color: red; }
|
||||
</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Asterisk dialplan</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Asterisk dialplan mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
; extensions.conf - the Asterisk dial plan
|
||||
;
|
||||
|
||||
[general]
|
||||
;
|
||||
; If static is set to no, or omitted, then the pbx_config will rewrite
|
||||
; this file when extensions are modified. Remember that all comments
|
||||
; made in the file will be lost when that happens.
|
||||
static=yes
|
||||
|
||||
#include "/etc/asterisk/additional_general.conf
|
||||
|
||||
[iaxprovider]
|
||||
switch => IAX2/user:[key]@myserver/mycontext
|
||||
|
||||
[dynamic]
|
||||
#exec /usr/bin/dynamic-peers.pl
|
||||
|
||||
[trunkint]
|
||||
;
|
||||
; International long distance through trunk
|
||||
;
|
||||
exten => _9011.,1,Macro(dundi-e164,${EXTEN:4})
|
||||
exten => _9011.,n,Dial(${GLOBAL(TRUNK)}/${FILTER(0-9,${EXTEN:${GLOBAL(TRUNKMSD)}})})
|
||||
|
||||
[local]
|
||||
;
|
||||
; Master context for local, toll-free, and iaxtel calls only
|
||||
;
|
||||
ignorepat => 9
|
||||
include => default
|
||||
|
||||
[demo]
|
||||
include => stdexten
|
||||
;
|
||||
; We start with what to do when a call first comes in.
|
||||
;
|
||||
exten => s,1,Wait(1) ; Wait a second, just for fun
|
||||
same => n,Answer ; Answer the line
|
||||
same => n,Set(TIMEOUT(digit)=5) ; Set Digit Timeout to 5 seconds
|
||||
same => n,Set(TIMEOUT(response)=10) ; Set Response Timeout to 10 seconds
|
||||
same => n(restart),BackGround(demo-congrats) ; Play a congratulatory message
|
||||
same => n(instruct),BackGround(demo-instruct) ; Play some instructions
|
||||
same => n,WaitExten ; Wait for an extension to be dialed.
|
||||
|
||||
exten => 2,1,BackGround(demo-moreinfo) ; Give some more information.
|
||||
exten => 2,n,Goto(s,instruct)
|
||||
|
||||
exten => 3,1,Set(LANGUAGE()=fr) ; Set language to french
|
||||
exten => 3,n,Goto(s,restart) ; Start with the congratulations
|
||||
|
||||
exten => 1000,1,Goto(default,s,1)
|
||||
;
|
||||
; We also create an example user, 1234, who is on the console and has
|
||||
; voicemail, etc.
|
||||
;
|
||||
exten => 1234,1,Playback(transfer,skip) ; "Please hold while..."
|
||||
; (but skip if channel is not up)
|
||||
exten => 1234,n,Gosub(${EXTEN},stdexten(${GLOBAL(CONSOLE)}))
|
||||
exten => 1234,n,Goto(default,s,1) ; exited Voicemail
|
||||
|
||||
exten => 1235,1,Voicemail(1234,u) ; Right to voicemail
|
||||
|
||||
exten => 1236,1,Dial(Console/dsp) ; Ring forever
|
||||
exten => 1236,n,Voicemail(1234,b) ; Unless busy
|
||||
|
||||
;
|
||||
; # for when they're done with the demo
|
||||
;
|
||||
exten => #,1,Playback(demo-thanks) ; "Thanks for trying the demo"
|
||||
exten => #,n,Hangup ; Hang them up.
|
||||
|
||||
;
|
||||
; A timeout and "invalid extension rule"
|
||||
;
|
||||
exten => t,1,Goto(#,1) ; If they take too long, give up
|
||||
exten => i,1,Playback(invalid) ; "That's not valid, try again"
|
||||
|
||||
;
|
||||
; Create an extension, 500, for dialing the
|
||||
; Asterisk demo.
|
||||
;
|
||||
exten => 500,1,Playback(demo-abouttotry); Let them know what's going on
|
||||
exten => 500,n,Dial(IAX2/guest@pbx.digium.com/s@default) ; Call the Asterisk demo
|
||||
exten => 500,n,Playback(demo-nogo) ; Couldn't connect to the demo site
|
||||
exten => 500,n,Goto(s,6) ; Return to the start over message.
|
||||
|
||||
;
|
||||
; Create an extension, 600, for evaluating echo latency.
|
||||
;
|
||||
exten => 600,1,Playback(demo-echotest) ; Let them know what's going on
|
||||
exten => 600,n,Echo ; Do the echo test
|
||||
exten => 600,n,Playback(demo-echodone) ; Let them know it's over
|
||||
exten => 600,n,Goto(s,6) ; Start over
|
||||
|
||||
;
|
||||
; You can use the Macro Page to intercom a individual user
|
||||
exten => 76245,1,Macro(page,SIP/Grandstream1)
|
||||
; or if your peernames are the same as extensions
|
||||
exten => _7XXX,1,Macro(page,SIP/${EXTEN})
|
||||
;
|
||||
;
|
||||
; System Wide Page at extension 7999
|
||||
;
|
||||
exten => 7999,1,Set(TIMEOUT(absolute)=60)
|
||||
exten => 7999,2,Page(Local/Grandstream1@page&Local/Xlite1@page&Local/1234@page/n,d)
|
||||
|
||||
; Give voicemail at extension 8500
|
||||
;
|
||||
exten => 8500,1,VoicemailMain
|
||||
exten => 8500,n,Goto(s,6)
|
||||
|
||||
</textarea></form>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
mode: "text/x-asterisk",
|
||||
matchBrackets: true,
|
||||
lineNumber: true
|
||||
});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-asterisk</code>.</p>
|
||||
|
||||
</article>
|
||||
@@ -1,362 +0,0 @@
|
||||
CodeMirror.defineMode("clike", function(config, parserConfig) {
|
||||
var indentUnit = config.indentUnit,
|
||||
statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
|
||||
dontAlignCalls = parserConfig.dontAlignCalls,
|
||||
keywords = parserConfig.keywords || {},
|
||||
builtin = parserConfig.builtin || {},
|
||||
blockKeywords = parserConfig.blockKeywords || {},
|
||||
atoms = parserConfig.atoms || {},
|
||||
hooks = parserConfig.hooks || {},
|
||||
multiLineStrings = parserConfig.multiLineStrings;
|
||||
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
|
||||
|
||||
var curPunc;
|
||||
|
||||
function tokenBase(stream, state) {
|
||||
var ch = stream.next();
|
||||
if (hooks[ch]) {
|
||||
var result = hooks[ch](stream, state);
|
||||
if (result !== false) return result;
|
||||
}
|
||||
if (ch == '"' || ch == "'") {
|
||||
state.tokenize = tokenString(ch);
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
|
||||
curPunc = ch;
|
||||
return null;
|
||||
}
|
||||
if (/\d/.test(ch)) {
|
||||
stream.eatWhile(/[\w\.]/);
|
||||
return "number";
|
||||
}
|
||||
if (ch == "/") {
|
||||
if (stream.eat("*")) {
|
||||
state.tokenize = tokenComment;
|
||||
return tokenComment(stream, state);
|
||||
}
|
||||
if (stream.eat("/")) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
}
|
||||
if (isOperatorChar.test(ch)) {
|
||||
stream.eatWhile(isOperatorChar);
|
||||
return "operator";
|
||||
}
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
var cur = stream.current();
|
||||
if (keywords.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "keyword";
|
||||
}
|
||||
if (builtin.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "builtin";
|
||||
}
|
||||
if (atoms.propertyIsEnumerable(cur)) return "atom";
|
||||
return "variable";
|
||||
}
|
||||
|
||||
function tokenString(quote) {
|
||||
return function(stream, state) {
|
||||
var escaped = false, next, end = false;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == quote && !escaped) {end = true; break;}
|
||||
escaped = !escaped && next == "\\";
|
||||
}
|
||||
if (end || !(escaped || multiLineStrings))
|
||||
state.tokenize = null;
|
||||
return "string";
|
||||
};
|
||||
}
|
||||
|
||||
function tokenComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
while (ch = stream.next()) {
|
||||
if (ch == "/" && maybeEnd) {
|
||||
state.tokenize = null;
|
||||
break;
|
||||
}
|
||||
maybeEnd = (ch == "*");
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function Context(indented, column, type, align, prev) {
|
||||
this.indented = indented;
|
||||
this.column = column;
|
||||
this.type = type;
|
||||
this.align = align;
|
||||
this.prev = prev;
|
||||
}
|
||||
function pushContext(state, col, type) {
|
||||
var indent = state.indented;
|
||||
if (state.context && state.context.type == "statement")
|
||||
indent = state.context.indented;
|
||||
return state.context = new Context(indent, col, type, null, state.context);
|
||||
}
|
||||
function popContext(state) {
|
||||
var t = state.context.type;
|
||||
if (t == ")" || t == "]" || t == "}")
|
||||
state.indented = state.context.indented;
|
||||
return state.context = state.context.prev;
|
||||
}
|
||||
|
||||
// Interface
|
||||
|
||||
return {
|
||||
startState: function(basecolumn) {
|
||||
return {
|
||||
tokenize: null,
|
||||
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
|
||||
indented: 0,
|
||||
startOfLine: true
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
var ctx = state.context;
|
||||
if (stream.sol()) {
|
||||
if (ctx.align == null) ctx.align = false;
|
||||
state.indented = stream.indentation();
|
||||
state.startOfLine = true;
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
curPunc = null;
|
||||
var style = (state.tokenize || tokenBase)(stream, state);
|
||||
if (style == "comment" || style == "meta") return style;
|
||||
if (ctx.align == null) ctx.align = true;
|
||||
|
||||
if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
|
||||
else if (curPunc == "{") pushContext(state, stream.column(), "}");
|
||||
else if (curPunc == "[") pushContext(state, stream.column(), "]");
|
||||
else if (curPunc == "(") pushContext(state, stream.column(), ")");
|
||||
else if (curPunc == "}") {
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
if (ctx.type == "}") ctx = popContext(state);
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
}
|
||||
else if (curPunc == ctx.type) popContext(state);
|
||||
else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
|
||||
pushContext(state, stream.column(), "statement");
|
||||
state.startOfLine = false;
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function(state, textAfter) {
|
||||
if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
|
||||
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
|
||||
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
|
||||
var closing = firstChar == ctx.type;
|
||||
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
|
||||
else if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
|
||||
else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
|
||||
else return ctx.indented + (closing ? 0 : indentUnit);
|
||||
},
|
||||
|
||||
electricChars: "{}",
|
||||
blockCommentStart: "/*",
|
||||
blockCommentEnd: "*/",
|
||||
lineComment: "//",
|
||||
fold: "brace"
|
||||
};
|
||||
});
|
||||
|
||||
(function() {
|
||||
function words(str) {
|
||||
var obj = {}, words = str.split(" ");
|
||||
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
|
||||
return obj;
|
||||
}
|
||||
var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
|
||||
"double static else struct entry switch extern typedef float union for unsigned " +
|
||||
"goto while enum void const signed volatile";
|
||||
|
||||
function cppHook(stream, state) {
|
||||
if (!state.startOfLine) return false;
|
||||
for (;;) {
|
||||
if (stream.skipTo("\\")) {
|
||||
stream.next();
|
||||
if (stream.eol()) {
|
||||
state.tokenize = cppHook;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
stream.skipToEnd();
|
||||
state.tokenize = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return "meta";
|
||||
}
|
||||
|
||||
// C#-style strings where "" escapes a quote.
|
||||
function tokenAtString(stream, state) {
|
||||
var next;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == '"' && !stream.eat('"')) {
|
||||
state.tokenize = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return "string";
|
||||
}
|
||||
|
||||
function mimes(ms, mode) {
|
||||
for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
|
||||
}
|
||||
|
||||
mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], {
|
||||
name: "clike",
|
||||
keywords: words(cKeywords),
|
||||
blockKeywords: words("case do else for if switch while struct"),
|
||||
atoms: words("null"),
|
||||
hooks: {"#": cppHook}
|
||||
});
|
||||
mimes(["text/x-c++src", "text/x-c++hdr"], {
|
||||
name: "clike",
|
||||
keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
|
||||
"static_cast typeid catch operator template typename class friend private " +
|
||||
"this using const_cast inline public throw virtual delete mutable protected " +
|
||||
"wchar_t"),
|
||||
blockKeywords: words("catch class do else finally for if struct switch try while"),
|
||||
atoms: words("true false null"),
|
||||
hooks: {"#": cppHook}
|
||||
});
|
||||
CodeMirror.defineMIME("text/x-java", {
|
||||
name: "clike",
|
||||
keywords: words("abstract assert boolean break byte case catch char class const continue default " +
|
||||
"do double else enum extends final finally float for goto if implements import " +
|
||||
"instanceof int interface long native new package private protected public " +
|
||||
"return short static strictfp super switch synchronized this throw throws transient " +
|
||||
"try void volatile while"),
|
||||
blockKeywords: words("catch class do else finally for if switch try while"),
|
||||
atoms: words("true false null"),
|
||||
hooks: {
|
||||
"@": function(stream) {
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
return "meta";
|
||||
}
|
||||
}
|
||||
});
|
||||
CodeMirror.defineMIME("text/x-csharp", {
|
||||
name: "clike",
|
||||
keywords: words("abstract as base break case catch checked class const continue" +
|
||||
" default delegate do else enum event explicit extern finally fixed for" +
|
||||
" foreach goto if implicit in interface internal is lock namespace new" +
|
||||
" operator out override params private protected public readonly ref return sealed" +
|
||||
" sizeof stackalloc static struct switch this throw try typeof unchecked" +
|
||||
" unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
|
||||
" global group into join let orderby partial remove select set value var yield"),
|
||||
blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
|
||||
builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
|
||||
" Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
|
||||
" UInt64 bool byte char decimal double short int long object" +
|
||||
" sbyte float string ushort uint ulong"),
|
||||
atoms: words("true false null"),
|
||||
hooks: {
|
||||
"@": function(stream, state) {
|
||||
if (stream.eat('"')) {
|
||||
state.tokenize = tokenAtString;
|
||||
return tokenAtString(stream, state);
|
||||
}
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
return "meta";
|
||||
}
|
||||
}
|
||||
});
|
||||
CodeMirror.defineMIME("text/x-scala", {
|
||||
name: "clike",
|
||||
keywords: words(
|
||||
|
||||
/* scala */
|
||||
"abstract case catch class def do else extends false final finally for forSome if " +
|
||||
"implicit import lazy match new null object override package private protected return " +
|
||||
"sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
|
||||
"<% >: # @ " +
|
||||
|
||||
/* package scala */
|
||||
"assert assume require print println printf readLine readBoolean readByte readShort " +
|
||||
"readChar readInt readLong readFloat readDouble " +
|
||||
|
||||
"AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
|
||||
"Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
|
||||
"Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
|
||||
"Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
|
||||
"StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
|
||||
|
||||
/* package java.lang */
|
||||
"Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
|
||||
"Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
|
||||
"Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
|
||||
"StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
|
||||
|
||||
|
||||
),
|
||||
blockKeywords: words("catch class do else finally for forSome if match switch try while"),
|
||||
atoms: words("true false null"),
|
||||
hooks: {
|
||||
"@": function(stream) {
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
return "meta";
|
||||
}
|
||||
}
|
||||
});
|
||||
mimes(["x-shader/x-vertex", "x-shader/x-fragment"], {
|
||||
name: "clike",
|
||||
keywords: words("float int bool void " +
|
||||
"vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
|
||||
"mat2 mat3 mat4 " +
|
||||
"sampler1D sampler2D sampler3D samplerCube " +
|
||||
"sampler1DShadow sampler2DShadow" +
|
||||
"const attribute uniform varying " +
|
||||
"break continue discard return " +
|
||||
"for while do if else struct " +
|
||||
"in out inout"),
|
||||
blockKeywords: words("for while do if else struct"),
|
||||
builtin: words("radians degrees sin cos tan asin acos atan " +
|
||||
"pow exp log exp2 sqrt inversesqrt " +
|
||||
"abs sign floor ceil fract mod min max clamp mix step smootstep " +
|
||||
"length distance dot cross normalize ftransform faceforward " +
|
||||
"reflect refract matrixCompMult " +
|
||||
"lessThan lessThanEqual greaterThan greaterThanEqual " +
|
||||
"equal notEqual any all not " +
|
||||
"texture1D texture1DProj texture1DLod texture1DProjLod " +
|
||||
"texture2D texture2DProj texture2DLod texture2DProjLod " +
|
||||
"texture3D texture3DProj texture3DLod texture3DProjLod " +
|
||||
"textureCube textureCubeLod " +
|
||||
"shadow1D shadow2D shadow1DProj shadow2DProj " +
|
||||
"shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
|
||||
"dFdx dFdy fwidth " +
|
||||
"noise1 noise2 noise3 noise4"),
|
||||
atoms: words("true false " +
|
||||
"gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
|
||||
"gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
|
||||
"gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
|
||||
"gl_FogCoord " +
|
||||
"gl_Position gl_PointSize gl_ClipVertex " +
|
||||
"gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
|
||||
"gl_TexCoord gl_FogFragCoord " +
|
||||
"gl_FragCoord gl_FrontFacing " +
|
||||
"gl_FragColor gl_FragData gl_FragDepth " +
|
||||
"gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
|
||||
"gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
|
||||
"gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
|
||||
"gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
|
||||
"gl_ProjectionMatrixInverseTranspose " +
|
||||
"gl_ModelViewProjectionMatrixInverseTranspose " +
|
||||
"gl_TextureMatrixInverseTranspose " +
|
||||
"gl_NormalScale gl_DepthRange gl_ClipPlane " +
|
||||
"gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
|
||||
"gl_FrontLightModelProduct gl_BackLightModelProduct " +
|
||||
"gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
|
||||
"gl_FogParameters " +
|
||||
"gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
|
||||
"gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
|
||||
"gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
|
||||
"gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
|
||||
"gl_MaxDrawBuffers"),
|
||||
hooks: {"#": cppHook}
|
||||
});
|
||||
}());
|
||||
@@ -1,195 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: C-like mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/edit/matchbrackets.js"></script>
|
||||
<script src="clike.js"></script>
|
||||
<style>.CodeMirror {border: 2px inset #dee;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">C-like</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>C-like mode</h2>
|
||||
|
||||
<div><textarea id="c-code">
|
||||
/* C demo code */
|
||||
|
||||
#include <zmq.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <time.h>
|
||||
#include <stdio.h>
|
||||
#include <fcntl.h>
|
||||
#include <malloc.h>
|
||||
|
||||
typedef struct {
|
||||
void* arg_socket;
|
||||
zmq_msg_t* arg_msg;
|
||||
char* arg_string;
|
||||
unsigned long arg_len;
|
||||
int arg_int, arg_command;
|
||||
|
||||
int signal_fd;
|
||||
int pad;
|
||||
void* context;
|
||||
sem_t sem;
|
||||
} acl_zmq_context;
|
||||
|
||||
#define p(X) (context->arg_##X)
|
||||
|
||||
void* zmq_thread(void* context_pointer) {
|
||||
acl_zmq_context* context = (acl_zmq_context*)context_pointer;
|
||||
char ok = 'K', err = 'X';
|
||||
int res;
|
||||
|
||||
while (1) {
|
||||
while ((res = sem_wait(&context->sem)) == EINTR);
|
||||
if (res) {write(context->signal_fd, &err, 1); goto cleanup;}
|
||||
switch(p(command)) {
|
||||
case 0: goto cleanup;
|
||||
case 1: p(socket) = zmq_socket(context->context, p(int)); break;
|
||||
case 2: p(int) = zmq_close(p(socket)); break;
|
||||
case 3: p(int) = zmq_bind(p(socket), p(string)); break;
|
||||
case 4: p(int) = zmq_connect(p(socket), p(string)); break;
|
||||
case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &p(len)); break;
|
||||
case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
|
||||
case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
|
||||
case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
|
||||
case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
|
||||
}
|
||||
p(command) = errno;
|
||||
write(context->signal_fd, &ok, 1);
|
||||
}
|
||||
cleanup:
|
||||
close(context->signal_fd);
|
||||
free(context_pointer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void* zmq_thread_init(void* zmq_context, int signal_fd) {
|
||||
acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
|
||||
pthread_t thread;
|
||||
|
||||
context->context = zmq_context;
|
||||
context->signal_fd = signal_fd;
|
||||
sem_init(&context->sem, 1, 0);
|
||||
pthread_create(&thread, 0, &zmq_thread, context);
|
||||
pthread_detach(thread);
|
||||
return context;
|
||||
}
|
||||
</textarea></div>
|
||||
|
||||
<h2>C++ example</h2>
|
||||
|
||||
<div><textarea id="cpp-code">
|
||||
#include <iostream>
|
||||
#include "mystuff/util.h"
|
||||
|
||||
namespace {
|
||||
enum Enum {
|
||||
VAL1, VAL2, VAL3
|
||||
};
|
||||
|
||||
int Helper(const MyType& param) {
|
||||
return 0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class ForwardDec;
|
||||
|
||||
template <class T, class V>
|
||||
class Class : public BaseClass {
|
||||
const MyType<T, V> member_;
|
||||
|
||||
public:
|
||||
const MyType<T, V>& Method() const {
|
||||
return member_;
|
||||
}
|
||||
|
||||
void Method2(MyType<T, V>* value);
|
||||
}
|
||||
|
||||
template <class T, class V>
|
||||
void Class::Method2(MyType<T, V>* value) {
|
||||
std::out << 1 >> method();
|
||||
value->Method3(member_);
|
||||
member_ = value;
|
||||
}
|
||||
</textarea></div>
|
||||
|
||||
<h2>Java example</h2>
|
||||
|
||||
<div><textarea id="java-code">
|
||||
import com.demo.util.MyType;
|
||||
import com.demo.util.MyInterface;
|
||||
|
||||
public enum Enum {
|
||||
VAL1, VAL2, VAL3
|
||||
}
|
||||
|
||||
public class Class<T, V> implements MyInterface {
|
||||
public static final MyType<T, V> member;
|
||||
|
||||
private class InnerClass {
|
||||
public int zero() {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public MyType method() {
|
||||
return member;
|
||||
}
|
||||
|
||||
public void method2(MyType<T, V> value) {
|
||||
method();
|
||||
value.method3();
|
||||
member = value;
|
||||
}
|
||||
}
|
||||
</textarea></div>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("c-code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
mode: "text/x-csrc"
|
||||
});
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("cpp-code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
mode: "text/x-c++src"
|
||||
});
|
||||
var javaEditor = CodeMirror.fromTextArea(document.getElementById("java-code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
mode: "text/x-java"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p>Simple mode that tries to handle C-like languages as well as it
|
||||
can. Takes two configuration parameters: <code>keywords</code>, an
|
||||
object whose property names are the keywords in the language,
|
||||
and <code>useCPP</code>, which determines whether C preprocessor
|
||||
directives are recognized.</p>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-csrc</code>
|
||||
(C code), <code>text/x-c++src</code> (C++
|
||||
code), <code>text/x-java</code> (Java
|
||||
code), <code>text/x-csharp</code> (C#).</p>
|
||||
</article>
|
||||
@@ -1,767 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Scala mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<link rel="stylesheet" href="../../theme/ambiance.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/edit/matchbrackets.js"></script>
|
||||
<script src="clike.js"></script>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Scala</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Scala mode</h2>
|
||||
<form>
|
||||
<textarea id="code" name="code">
|
||||
|
||||
/* __ *\
|
||||
** ________ ___ / / ___ Scala API **
|
||||
** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL **
|
||||
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
|
||||
** /____/\___/_/ |_/____/_/ | | **
|
||||
** |/ **
|
||||
\* */
|
||||
|
||||
package scala.collection
|
||||
|
||||
import generic._
|
||||
import mutable.{ Builder, ListBuffer }
|
||||
import annotation.{tailrec, migration, bridge}
|
||||
import annotation.unchecked.{ uncheckedVariance => uV }
|
||||
import parallel.ParIterable
|
||||
|
||||
/** A template trait for traversable collections of type `Traversable[A]`.
|
||||
*
|
||||
* $traversableInfo
|
||||
* @define mutability
|
||||
* @define traversableInfo
|
||||
* This is a base trait of all kinds of $mutability Scala collections. It
|
||||
* implements the behavior common to all collections, in terms of a method
|
||||
* `foreach` with signature:
|
||||
* {{{
|
||||
* def foreach[U](f: Elem => U): Unit
|
||||
* }}}
|
||||
* Collection classes mixing in this trait provide a concrete
|
||||
* `foreach` method which traverses all the
|
||||
* elements contained in the collection, applying a given function to each.
|
||||
* They also need to provide a method `newBuilder`
|
||||
* which creates a builder for collections of the same kind.
|
||||
*
|
||||
* A traversable class might or might not have two properties: strictness
|
||||
* and orderedness. Neither is represented as a type.
|
||||
*
|
||||
* The instances of a strict collection class have all their elements
|
||||
* computed before they can be used as values. By contrast, instances of
|
||||
* a non-strict collection class may defer computation of some of their
|
||||
* elements until after the instance is available as a value.
|
||||
* A typical example of a non-strict collection class is a
|
||||
* <a href="../immutable/Stream.html" target="ContentFrame">
|
||||
* `scala.collection.immutable.Stream`</a>.
|
||||
* A more general class of examples are `TraversableViews`.
|
||||
*
|
||||
* If a collection is an instance of an ordered collection class, traversing
|
||||
* its elements with `foreach` will always visit elements in the
|
||||
* same order, even for different runs of the program. If the class is not
|
||||
* ordered, `foreach` can visit elements in different orders for
|
||||
* different runs (but it will keep the same order in the same run).'
|
||||
*
|
||||
* A typical example of a collection class which is not ordered is a
|
||||
* `HashMap` of objects. The traversal order for hash maps will
|
||||
* depend on the hash codes of its elements, and these hash codes might
|
||||
* differ from one run to the next. By contrast, a `LinkedHashMap`
|
||||
* is ordered because it's `foreach` method visits elements in the
|
||||
* order they were inserted into the `HashMap`.
|
||||
*
|
||||
* @author Martin Odersky
|
||||
* @version 2.8
|
||||
* @since 2.8
|
||||
* @tparam A the element type of the collection
|
||||
* @tparam Repr the type of the actual collection containing the elements.
|
||||
*
|
||||
* @define Coll Traversable
|
||||
* @define coll traversable collection
|
||||
*/
|
||||
trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr]
|
||||
with FilterMonadic[A, Repr]
|
||||
with TraversableOnce[A]
|
||||
with GenTraversableLike[A, Repr]
|
||||
with Parallelizable[A, ParIterable[A]]
|
||||
{
|
||||
self =>
|
||||
|
||||
import Traversable.breaks._
|
||||
|
||||
/** The type implementing this traversable */
|
||||
protected type Self = Repr
|
||||
|
||||
/** The collection of type $coll underlying this `TraversableLike` object.
|
||||
* By default this is implemented as the `TraversableLike` object itself,
|
||||
* but this can be overridden.
|
||||
*/
|
||||
def repr: Repr = this.asInstanceOf[Repr]
|
||||
|
||||
/** The underlying collection seen as an instance of `$Coll`.
|
||||
* By default this is implemented as the current collection object itself,
|
||||
* but this can be overridden.
|
||||
*/
|
||||
protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]]
|
||||
|
||||
/** A conversion from collections of type `Repr` to `$Coll` objects.
|
||||
* By default this is implemented as just a cast, but this can be overridden.
|
||||
*/
|
||||
protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]]
|
||||
|
||||
/** Creates a new builder for this collection type.
|
||||
*/
|
||||
protected[this] def newBuilder: Builder[A, Repr]
|
||||
|
||||
protected[this] def parCombiner = ParIterable.newCombiner[A]
|
||||
|
||||
/** Applies a function `f` to all elements of this $coll.
|
||||
*
|
||||
* Note: this method underlies the implementation of most other bulk operations.
|
||||
* It's important to implement this method in an efficient way.
|
||||
*
|
||||
*
|
||||
* @param f the function that is applied for its side-effect to every element.
|
||||
* The result of function `f` is discarded.
|
||||
*
|
||||
* @tparam U the type parameter describing the result of function `f`.
|
||||
* This result will always be ignored. Typically `U` is `Unit`,
|
||||
* but this is not necessary.
|
||||
*
|
||||
* @usecase def foreach(f: A => Unit): Unit
|
||||
*/
|
||||
def foreach[U](f: A => U): Unit
|
||||
|
||||
/** Tests whether this $coll is empty.
|
||||
*
|
||||
* @return `true` if the $coll contain no elements, `false` otherwise.
|
||||
*/
|
||||
def isEmpty: Boolean = {
|
||||
var result = true
|
||||
breakable {
|
||||
for (x <- this) {
|
||||
result = false
|
||||
break
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/** Tests whether this $coll is known to have a finite size.
|
||||
* All strict collections are known to have finite size. For a non-strict collection
|
||||
* such as `Stream`, the predicate returns `true` if all elements have been computed.
|
||||
* It returns `false` if the stream is not yet evaluated to the end.
|
||||
*
|
||||
* Note: many collection methods will not work on collections of infinite sizes.
|
||||
*
|
||||
* @return `true` if this collection is known to have finite size, `false` otherwise.
|
||||
*/
|
||||
def hasDefiniteSize = true
|
||||
|
||||
def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
val b = bf(repr)
|
||||
if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size)
|
||||
b ++= thisCollection
|
||||
b ++= that.seq
|
||||
b.result
|
||||
}
|
||||
|
||||
@bridge
|
||||
def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
|
||||
++(that: GenTraversableOnce[B])(bf)
|
||||
|
||||
/** Concatenates this $coll with the elements of a traversable collection.
|
||||
* It differs from ++ in that the right operand determines the type of the
|
||||
* resulting collection rather than the left one.
|
||||
*
|
||||
* @param that the traversable to append.
|
||||
* @tparam B the element type of the returned collection.
|
||||
* @tparam That $thatinfo
|
||||
* @param bf $bfinfo
|
||||
* @return a new collection of type `That` which contains all elements
|
||||
* of this $coll followed by all elements of `that`.
|
||||
*
|
||||
* @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B]
|
||||
*
|
||||
* @return a new $coll which contains all elements of this $coll
|
||||
* followed by all elements of `that`.
|
||||
*/
|
||||
def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
val b = bf(repr)
|
||||
if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)
|
||||
b ++= that
|
||||
b ++= thisCollection
|
||||
b.result
|
||||
}
|
||||
|
||||
/** This overload exists because: for the implementation of ++: we should reuse
|
||||
* that of ++ because many collections override it with more efficient versions.
|
||||
* Since TraversableOnce has no '++' method, we have to implement that directly,
|
||||
* but Traversable and down can use the overload.
|
||||
*/
|
||||
def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
|
||||
(that ++ seq)(breakOut)
|
||||
|
||||
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
val b = bf(repr)
|
||||
b.sizeHint(this)
|
||||
for (x <- this) b += f(x)
|
||||
b.result
|
||||
}
|
||||
|
||||
def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
val b = bf(repr)
|
||||
for (x <- this) b ++= f(x).seq
|
||||
b.result
|
||||
}
|
||||
|
||||
/** Selects all elements of this $coll which satisfy a predicate.
|
||||
*
|
||||
* @param p the predicate used to test elements.
|
||||
* @return a new $coll consisting of all elements of this $coll that satisfy the given
|
||||
* predicate `p`. The order of the elements is preserved.
|
||||
*/
|
||||
def filter(p: A => Boolean): Repr = {
|
||||
val b = newBuilder
|
||||
for (x <- this)
|
||||
if (p(x)) b += x
|
||||
b.result
|
||||
}
|
||||
|
||||
/** Selects all elements of this $coll which do not satisfy a predicate.
|
||||
*
|
||||
* @param p the predicate used to test elements.
|
||||
* @return a new $coll consisting of all elements of this $coll that do not satisfy the given
|
||||
* predicate `p`. The order of the elements is preserved.
|
||||
*/
|
||||
def filterNot(p: A => Boolean): Repr = filter(!p(_))
|
||||
|
||||
def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
val b = bf(repr)
|
||||
for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)
|
||||
b.result
|
||||
}
|
||||
|
||||
/** Builds a new collection by applying an option-valued function to all
|
||||
* elements of this $coll on which the function is defined.
|
||||
*
|
||||
* @param f the option-valued function which filters and maps the $coll.
|
||||
* @tparam B the element type of the returned collection.
|
||||
* @tparam That $thatinfo
|
||||
* @param bf $bfinfo
|
||||
* @return a new collection of type `That` resulting from applying the option-valued function
|
||||
* `f` to each element and collecting all defined results.
|
||||
* The order of the elements is preserved.
|
||||
*
|
||||
* @usecase def filterMap[B](f: A => Option[B]): $Coll[B]
|
||||
*
|
||||
* @param pf the partial function which filters and maps the $coll.
|
||||
* @return a new $coll resulting from applying the given option-valued function
|
||||
* `f` to each element and collecting all defined results.
|
||||
* The order of the elements is preserved.
|
||||
def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
val b = bf(repr)
|
||||
for (x <- this)
|
||||
f(x) match {
|
||||
case Some(y) => b += y
|
||||
case _ =>
|
||||
}
|
||||
b.result
|
||||
}
|
||||
*/
|
||||
|
||||
/** Partitions this $coll in two ${coll}s according to a predicate.
|
||||
*
|
||||
* @param p the predicate on which to partition.
|
||||
* @return a pair of ${coll}s: the first $coll consists of all elements that
|
||||
* satisfy the predicate `p` and the second $coll consists of all elements
|
||||
* that don't. The relative order of the elements in the resulting ${coll}s
|
||||
* is the same as in the original $coll.
|
||||
*/
|
||||
def partition(p: A => Boolean): (Repr, Repr) = {
|
||||
val l, r = newBuilder
|
||||
for (x <- this) (if (p(x)) l else r) += x
|
||||
(l.result, r.result)
|
||||
}
|
||||
|
||||
def groupBy[K](f: A => K): immutable.Map[K, Repr] = {
|
||||
val m = mutable.Map.empty[K, Builder[A, Repr]]
|
||||
for (elem <- this) {
|
||||
val key = f(elem)
|
||||
val bldr = m.getOrElseUpdate(key, newBuilder)
|
||||
bldr += elem
|
||||
}
|
||||
val b = immutable.Map.newBuilder[K, Repr]
|
||||
for ((k, v) <- m)
|
||||
b += ((k, v.result))
|
||||
|
||||
b.result
|
||||
}
|
||||
|
||||
/** Tests whether a predicate holds for all elements of this $coll.
|
||||
*
|
||||
* $mayNotTerminateInf
|
||||
*
|
||||
* @param p the predicate used to test elements.
|
||||
* @return `true` if the given predicate `p` holds for all elements
|
||||
* of this $coll, otherwise `false`.
|
||||
*/
|
||||
def forall(p: A => Boolean): Boolean = {
|
||||
var result = true
|
||||
breakable {
|
||||
for (x <- this)
|
||||
if (!p(x)) { result = false; break }
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/** Tests whether a predicate holds for some of the elements of this $coll.
|
||||
*
|
||||
* $mayNotTerminateInf
|
||||
*
|
||||
* @param p the predicate used to test elements.
|
||||
* @return `true` if the given predicate `p` holds for some of the
|
||||
* elements of this $coll, otherwise `false`.
|
||||
*/
|
||||
def exists(p: A => Boolean): Boolean = {
|
||||
var result = false
|
||||
breakable {
|
||||
for (x <- this)
|
||||
if (p(x)) { result = true; break }
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/** Finds the first element of the $coll satisfying a predicate, if any.
|
||||
*
|
||||
* $mayNotTerminateInf
|
||||
* $orderDependent
|
||||
*
|
||||
* @param p the predicate used to test elements.
|
||||
* @return an option value containing the first element in the $coll
|
||||
* that satisfies `p`, or `None` if none exists.
|
||||
*/
|
||||
def find(p: A => Boolean): Option[A] = {
|
||||
var result: Option[A] = None
|
||||
breakable {
|
||||
for (x <- this)
|
||||
if (p(x)) { result = Some(x); break }
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op)
|
||||
|
||||
def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
val b = bf(repr)
|
||||
b.sizeHint(this, 1)
|
||||
var acc = z
|
||||
b += acc
|
||||
for (x <- this) { acc = op(acc, x); b += acc }
|
||||
b.result
|
||||
}
|
||||
|
||||
@migration(2, 9,
|
||||
"This scanRight definition has changed in 2.9.\n" +
|
||||
"The previous behavior can be reproduced with scanRight.reverse."
|
||||
)
|
||||
def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
var scanned = List(z)
|
||||
var acc = z
|
||||
for (x <- reversed) {
|
||||
acc = op(x, acc)
|
||||
scanned ::= acc
|
||||
}
|
||||
val b = bf(repr)
|
||||
for (elem <- scanned) b += elem
|
||||
b.result
|
||||
}
|
||||
|
||||
/** Selects the first element of this $coll.
|
||||
* $orderDependent
|
||||
* @return the first element of this $coll.
|
||||
* @throws `NoSuchElementException` if the $coll is empty.
|
||||
*/
|
||||
def head: A = {
|
||||
var result: () => A = () => throw new NoSuchElementException
|
||||
breakable {
|
||||
for (x <- this) {
|
||||
result = () => x
|
||||
break
|
||||
}
|
||||
}
|
||||
result()
|
||||
}
|
||||
|
||||
/** Optionally selects the first element.
|
||||
* $orderDependent
|
||||
* @return the first element of this $coll if it is nonempty, `None` if it is empty.
|
||||
*/
|
||||
def headOption: Option[A] = if (isEmpty) None else Some(head)
|
||||
|
||||
/** Selects all elements except the first.
|
||||
* $orderDependent
|
||||
* @return a $coll consisting of all elements of this $coll
|
||||
* except the first one.
|
||||
* @throws `UnsupportedOperationException` if the $coll is empty.
|
||||
*/
|
||||
override def tail: Repr = {
|
||||
if (isEmpty) throw new UnsupportedOperationException("empty.tail")
|
||||
drop(1)
|
||||
}
|
||||
|
||||
/** Selects the last element.
|
||||
* $orderDependent
|
||||
* @return The last element of this $coll.
|
||||
* @throws NoSuchElementException If the $coll is empty.
|
||||
*/
|
||||
def last: A = {
|
||||
var lst = head
|
||||
for (x <- this)
|
||||
lst = x
|
||||
lst
|
||||
}
|
||||
|
||||
/** Optionally selects the last element.
|
||||
* $orderDependent
|
||||
* @return the last element of this $coll$ if it is nonempty, `None` if it is empty.
|
||||
*/
|
||||
def lastOption: Option[A] = if (isEmpty) None else Some(last)
|
||||
|
||||
/** Selects all elements except the last.
|
||||
* $orderDependent
|
||||
* @return a $coll consisting of all elements of this $coll
|
||||
* except the last one.
|
||||
* @throws `UnsupportedOperationException` if the $coll is empty.
|
||||
*/
|
||||
def init: Repr = {
|
||||
if (isEmpty) throw new UnsupportedOperationException("empty.init")
|
||||
var lst = head
|
||||
var follow = false
|
||||
val b = newBuilder
|
||||
b.sizeHint(this, -1)
|
||||
for (x <- this.seq) {
|
||||
if (follow) b += lst
|
||||
else follow = true
|
||||
lst = x
|
||||
}
|
||||
b.result
|
||||
}
|
||||
|
||||
def take(n: Int): Repr = slice(0, n)
|
||||
|
||||
def drop(n: Int): Repr =
|
||||
if (n <= 0) {
|
||||
val b = newBuilder
|
||||
b.sizeHint(this)
|
||||
b ++= thisCollection result
|
||||
}
|
||||
else sliceWithKnownDelta(n, Int.MaxValue, -n)
|
||||
|
||||
def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until)
|
||||
|
||||
// Precondition: from >= 0, until > 0, builder already configured for building.
|
||||
private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = {
|
||||
var i = 0
|
||||
breakable {
|
||||
for (x <- this.seq) {
|
||||
if (i >= from) b += x
|
||||
i += 1
|
||||
if (i >= until) break
|
||||
}
|
||||
}
|
||||
b.result
|
||||
}
|
||||
// Precondition: from >= 0
|
||||
private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = {
|
||||
val b = newBuilder
|
||||
if (until <= from) b.result
|
||||
else {
|
||||
b.sizeHint(this, delta)
|
||||
sliceInternal(from, until, b)
|
||||
}
|
||||
}
|
||||
// Precondition: from >= 0
|
||||
private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = {
|
||||
val b = newBuilder
|
||||
if (until <= from) b.result
|
||||
else {
|
||||
b.sizeHintBounded(until - from, this)
|
||||
sliceInternal(from, until, b)
|
||||
}
|
||||
}
|
||||
|
||||
def takeWhile(p: A => Boolean): Repr = {
|
||||
val b = newBuilder
|
||||
breakable {
|
||||
for (x <- this) {
|
||||
if (!p(x)) break
|
||||
b += x
|
||||
}
|
||||
}
|
||||
b.result
|
||||
}
|
||||
|
||||
def dropWhile(p: A => Boolean): Repr = {
|
||||
val b = newBuilder
|
||||
var go = false
|
||||
for (x <- this) {
|
||||
if (!p(x)) go = true
|
||||
if (go) b += x
|
||||
}
|
||||
b.result
|
||||
}
|
||||
|
||||
def span(p: A => Boolean): (Repr, Repr) = {
|
||||
val l, r = newBuilder
|
||||
var toLeft = true
|
||||
for (x <- this) {
|
||||
toLeft = toLeft && p(x)
|
||||
(if (toLeft) l else r) += x
|
||||
}
|
||||
(l.result, r.result)
|
||||
}
|
||||
|
||||
def splitAt(n: Int): (Repr, Repr) = {
|
||||
val l, r = newBuilder
|
||||
l.sizeHintBounded(n, this)
|
||||
if (n >= 0) r.sizeHint(this, -n)
|
||||
var i = 0
|
||||
for (x <- this) {
|
||||
(if (i < n) l else r) += x
|
||||
i += 1
|
||||
}
|
||||
(l.result, r.result)
|
||||
}
|
||||
|
||||
/** Iterates over the tails of this $coll. The first value will be this
|
||||
* $coll and the final one will be an empty $coll, with the intervening
|
||||
* values the results of successive applications of `tail`.
|
||||
*
|
||||
* @return an iterator over all the tails of this $coll
|
||||
* @example `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)`
|
||||
*/
|
||||
def tails: Iterator[Repr] = iterateUntilEmpty(_.tail)
|
||||
|
||||
/** Iterates over the inits of this $coll. The first value will be this
|
||||
* $coll and the final one will be an empty $coll, with the intervening
|
||||
* values the results of successive applications of `init`.
|
||||
*
|
||||
* @return an iterator over all the inits of this $coll
|
||||
* @example `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)`
|
||||
*/
|
||||
def inits: Iterator[Repr] = iterateUntilEmpty(_.init)
|
||||
|
||||
/** Copies elements of this $coll to an array.
|
||||
* Fills the given array `xs` with at most `len` elements of
|
||||
* this $coll, starting at position `start`.
|
||||
* Copying will stop once either the end of the current $coll is reached,
|
||||
* or the end of the array is reached, or `len` elements have been copied.
|
||||
*
|
||||
* $willNotTerminateInf
|
||||
*
|
||||
* @param xs the array to fill.
|
||||
* @param start the starting index.
|
||||
* @param len the maximal number of elements to copy.
|
||||
* @tparam B the type of the elements of the array.
|
||||
*
|
||||
*
|
||||
* @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
|
||||
*/
|
||||
def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
|
||||
var i = start
|
||||
val end = (start + len) min xs.length
|
||||
breakable {
|
||||
for (x <- this) {
|
||||
if (i >= end) break
|
||||
xs(i) = x
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def toTraversable: Traversable[A] = thisCollection
|
||||
def toIterator: Iterator[A] = toStream.iterator
|
||||
def toStream: Stream[A] = toBuffer.toStream
|
||||
|
||||
/** Converts this $coll to a string.
|
||||
*
|
||||
* @return a string representation of this collection. By default this
|
||||
* string consists of the `stringPrefix` of this $coll,
|
||||
* followed by all elements separated by commas and enclosed in parentheses.
|
||||
*/
|
||||
override def toString = mkString(stringPrefix + "(", ", ", ")")
|
||||
|
||||
/** Defines the prefix of this object's `toString` representation.
|
||||
*
|
||||
* @return a string representation which starts the result of `toString`
|
||||
* applied to this $coll. By default the string prefix is the
|
||||
* simple name of the collection class $coll.
|
||||
*/
|
||||
def stringPrefix : String = {
|
||||
var string = repr.asInstanceOf[AnyRef].getClass.getName
|
||||
val idx1 = string.lastIndexOf('.' : Int)
|
||||
if (idx1 != -1) string = string.substring(idx1 + 1)
|
||||
val idx2 = string.indexOf('$')
|
||||
if (idx2 != -1) string = string.substring(0, idx2)
|
||||
string
|
||||
}
|
||||
|
||||
/** Creates a non-strict view of this $coll.
|
||||
*
|
||||
* @return a non-strict view of this $coll.
|
||||
*/
|
||||
def view = new TraversableView[A, Repr] {
|
||||
protected lazy val underlying = self.repr
|
||||
override def foreach[U](f: A => U) = self foreach f
|
||||
}
|
||||
|
||||
/** Creates a non-strict view of a slice of this $coll.
|
||||
*
|
||||
* Note: the difference between `view` and `slice` is that `view` produces
|
||||
* a view of the current $coll, whereas `slice` produces a new $coll.
|
||||
*
|
||||
* Note: `view(from, to)` is equivalent to `view.slice(from, to)`
|
||||
* $orderDependent
|
||||
*
|
||||
* @param from the index of the first element of the view
|
||||
* @param until the index of the element following the view
|
||||
* @return a non-strict view of a slice of this $coll, starting at index `from`
|
||||
* and extending up to (but not including) index `until`.
|
||||
*/
|
||||
def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until)
|
||||
|
||||
/** Creates a non-strict filter of this $coll.
|
||||
*
|
||||
* Note: the difference between `c filter p` and `c withFilter p` is that
|
||||
* the former creates a new collection, whereas the latter only
|
||||
* restricts the domain of subsequent `map`, `flatMap`, `foreach`,
|
||||
* and `withFilter` operations.
|
||||
* $orderDependent
|
||||
*
|
||||
* @param p the predicate used to test elements.
|
||||
* @return an object of class `WithFilter`, which supports
|
||||
* `map`, `flatMap`, `foreach`, and `withFilter` operations.
|
||||
* All these operations apply to those elements of this $coll which
|
||||
* satisfy the predicate `p`.
|
||||
*/
|
||||
def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p)
|
||||
|
||||
/** A class supporting filtered operations. Instances of this class are
|
||||
* returned by method `withFilter`.
|
||||
*/
|
||||
class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] {
|
||||
|
||||
/** Builds a new collection by applying a function to all elements of the
|
||||
* outer $coll containing this `WithFilter` instance that satisfy predicate `p`.
|
||||
*
|
||||
* @param f the function to apply to each element.
|
||||
* @tparam B the element type of the returned collection.
|
||||
* @tparam That $thatinfo
|
||||
* @param bf $bfinfo
|
||||
* @return a new collection of type `That` resulting from applying
|
||||
* the given function `f` to each element of the outer $coll
|
||||
* that satisfies predicate `p` and collecting the results.
|
||||
*
|
||||
* @usecase def map[B](f: A => B): $Coll[B]
|
||||
*
|
||||
* @return a new $coll resulting from applying the given function
|
||||
* `f` to each element of the outer $coll that satisfies
|
||||
* predicate `p` and collecting the results.
|
||||
*/
|
||||
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
val b = bf(repr)
|
||||
for (x <- self)
|
||||
if (p(x)) b += f(x)
|
||||
b.result
|
||||
}
|
||||
|
||||
/** Builds a new collection by applying a function to all elements of the
|
||||
* outer $coll containing this `WithFilter` instance that satisfy
|
||||
* predicate `p` and concatenating the results.
|
||||
*
|
||||
* @param f the function to apply to each element.
|
||||
* @tparam B the element type of the returned collection.
|
||||
* @tparam That $thatinfo
|
||||
* @param bf $bfinfo
|
||||
* @return a new collection of type `That` resulting from applying
|
||||
* the given collection-valued function `f` to each element
|
||||
* of the outer $coll that satisfies predicate `p` and
|
||||
* concatenating the results.
|
||||
*
|
||||
* @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B]
|
||||
*
|
||||
* @return a new $coll resulting from applying the given collection-valued function
|
||||
* `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
|
||||
*/
|
||||
def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
|
||||
val b = bf(repr)
|
||||
for (x <- self)
|
||||
if (p(x)) b ++= f(x).seq
|
||||
b.result
|
||||
}
|
||||
|
||||
/** Applies a function `f` to all elements of the outer $coll containing
|
||||
* this `WithFilter` instance that satisfy predicate `p`.
|
||||
*
|
||||
* @param f the function that is applied for its side-effect to every element.
|
||||
* The result of function `f` is discarded.
|
||||
*
|
||||
* @tparam U the type parameter describing the result of function `f`.
|
||||
* This result will always be ignored. Typically `U` is `Unit`,
|
||||
* but this is not necessary.
|
||||
*
|
||||
* @usecase def foreach(f: A => Unit): Unit
|
||||
*/
|
||||
def foreach[U](f: A => U): Unit =
|
||||
for (x <- self)
|
||||
if (p(x)) f(x)
|
||||
|
||||
/** Further refines the filter for this $coll.
|
||||
*
|
||||
* @param q the predicate used to test elements.
|
||||
* @return an object of class `WithFilter`, which supports
|
||||
* `map`, `flatMap`, `foreach`, and `withFilter` operations.
|
||||
* All these operations apply to those elements of this $coll which
|
||||
* satisfy the predicate `q` in addition to the predicate `p`.
|
||||
*/
|
||||
def withFilter(q: A => Boolean): WithFilter =
|
||||
new WithFilter(x => p(x) && q(x))
|
||||
}
|
||||
|
||||
// A helper for tails and inits.
|
||||
private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = {
|
||||
val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty)
|
||||
it ++ Iterator(Nil) map (newBuilder ++= _ result)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
</textarea>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
theme: "ambiance",
|
||||
mode: "text/x-scala"
|
||||
});
|
||||
</script>
|
||||
</article>
|
||||
File diff suppressed because one or more lines are too long
@@ -1,88 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Clojure mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="clojure.js"></script>
|
||||
<style>.CodeMirror {background: #f8f8f8;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Clojure</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Clojure mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
; Conway's Game of Life, based on the work of:
|
||||
;; Laurent Petit https://gist.github.com/1200343
|
||||
;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
|
||||
|
||||
(ns ^{:doc "Conway's Game of Life."}
|
||||
game-of-life)
|
||||
|
||||
;; Core game of life's algorithm functions
|
||||
|
||||
(defn neighbours
|
||||
"Given a cell's coordinates, returns the coordinates of its neighbours."
|
||||
[[x y]]
|
||||
(for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
|
||||
[(+ dx x) (+ dy y)]))
|
||||
|
||||
(defn step
|
||||
"Given a set of living cells, computes the new set of living cells."
|
||||
[cells]
|
||||
(set (for [[cell n] (frequencies (mapcat neighbours cells))
|
||||
:when (or (= n 3) (and (= n 2) (cells cell)))]
|
||||
cell)))
|
||||
|
||||
;; Utility methods for displaying game on a text terminal
|
||||
|
||||
(defn print-board
|
||||
"Prints a board on *out*, representing a step in the game."
|
||||
[board w h]
|
||||
(doseq [x (range (inc w)) y (range (inc h))]
|
||||
(if (= y 0) (print "\n"))
|
||||
(print (if (board [x y]) "[X]" " . "))))
|
||||
|
||||
(defn display-grids
|
||||
"Prints a squence of boards on *out*, representing several steps."
|
||||
[grids w h]
|
||||
(doseq [board grids]
|
||||
(print-board board w h)
|
||||
(print "\n")))
|
||||
|
||||
;; Launches an example board
|
||||
|
||||
(def
|
||||
^{:doc "board represents the initial set of living cells"}
|
||||
board #{[2 1] [2 2] [2 3]})
|
||||
|
||||
(display-grids (take 3 (iterate step board)) 5 5)
|
||||
|
||||
;; Let's play with characters
|
||||
(println \1 \a \# \\
|
||||
\" \( \newline
|
||||
\} \" \space
|
||||
\tab \return \backspace
|
||||
\u1000 \uAaAa \u9F9F)
|
||||
|
||||
</textarea></form>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-clojure</code>.</p>
|
||||
|
||||
</article>
|
||||
@@ -1,240 +0,0 @@
|
||||
/**
|
||||
* Author: Gautam Mehta
|
||||
* Branched from CodeMirror's Scheme mode
|
||||
*/
|
||||
CodeMirror.defineMode("cobol", function () {
|
||||
var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
|
||||
ATOM = "atom", NUMBER = "number", KEYWORD = "keyword", MODTAG = "header",
|
||||
COBOLLINENUM = "def", PERIOD = "link";
|
||||
function makeKeywords(str) {
|
||||
var obj = {}, words = str.split(" ");
|
||||
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
|
||||
return obj;
|
||||
}
|
||||
var atoms = makeKeywords("TRUE FALSE ZEROES ZEROS ZERO SPACES SPACE LOW-VALUE LOW-VALUES ");
|
||||
var keywords = makeKeywords(
|
||||
"ACCEPT ACCESS ACQUIRE ADD ADDRESS " +
|
||||
"ADVANCING AFTER ALIAS ALL ALPHABET " +
|
||||
"ALPHABETIC ALPHABETIC-LOWER ALPHABETIC-UPPER ALPHANUMERIC ALPHANUMERIC-EDITED " +
|
||||
"ALSO ALTER ALTERNATE AND ANY " +
|
||||
"ARE AREA AREAS ARITHMETIC ASCENDING " +
|
||||
"ASSIGN AT ATTRIBUTE AUTHOR AUTO " +
|
||||
"AUTO-SKIP AUTOMATIC B-AND B-EXOR B-LESS " +
|
||||
"B-NOT B-OR BACKGROUND-COLOR BACKGROUND-COLOUR BEEP " +
|
||||
"BEFORE BELL BINARY BIT BITS " +
|
||||
"BLANK BLINK BLOCK BOOLEAN BOTTOM " +
|
||||
"BY CALL CANCEL CD CF " +
|
||||
"CH CHARACTER CHARACTERS CLASS CLOCK-UNITS " +
|
||||
"CLOSE COBOL CODE CODE-SET COL " +
|
||||
"COLLATING COLUMN COMMA COMMIT COMMITMENT " +
|
||||
"COMMON COMMUNICATION COMP COMP-0 COMP-1 " +
|
||||
"COMP-2 COMP-3 COMP-4 COMP-5 COMP-6 " +
|
||||
"COMP-7 COMP-8 COMP-9 COMPUTATIONAL COMPUTATIONAL-0 " +
|
||||
"COMPUTATIONAL-1 COMPUTATIONAL-2 COMPUTATIONAL-3 COMPUTATIONAL-4 COMPUTATIONAL-5 " +
|
||||
"COMPUTATIONAL-6 COMPUTATIONAL-7 COMPUTATIONAL-8 COMPUTATIONAL-9 COMPUTE " +
|
||||
"CONFIGURATION CONNECT CONSOLE CONTAINED CONTAINS " +
|
||||
"CONTENT CONTINUE CONTROL CONTROL-AREA CONTROLS " +
|
||||
"CONVERTING COPY CORR CORRESPONDING COUNT " +
|
||||
"CRT CRT-UNDER CURRENCY CURRENT CURSOR " +
|
||||
"DATA DATE DATE-COMPILED DATE-WRITTEN DAY " +
|
||||
"DAY-OF-WEEK DB DB-ACCESS-CONTROL-KEY DB-DATA-NAME DB-EXCEPTION " +
|
||||
"DB-FORMAT-NAME DB-RECORD-NAME DB-SET-NAME DB-STATUS DBCS " +
|
||||
"DBCS-EDITED DE DEBUG-CONTENTS DEBUG-ITEM DEBUG-LINE " +
|
||||
"DEBUG-NAME DEBUG-SUB-1 DEBUG-SUB-2 DEBUG-SUB-3 DEBUGGING " +
|
||||
"DECIMAL-POINT DECLARATIVES DEFAULT DELETE DELIMITED " +
|
||||
"DELIMITER DEPENDING DESCENDING DESCRIBED DESTINATION " +
|
||||
"DETAIL DISABLE DISCONNECT DISPLAY DISPLAY-1 " +
|
||||
"DISPLAY-2 DISPLAY-3 DISPLAY-4 DISPLAY-5 DISPLAY-6 " +
|
||||
"DISPLAY-7 DISPLAY-8 DISPLAY-9 DIVIDE DIVISION " +
|
||||
"DOWN DROP DUPLICATE DUPLICATES DYNAMIC " +
|
||||
"EBCDIC EGI EJECT ELSE EMI " +
|
||||
"EMPTY EMPTY-CHECK ENABLE END END. END-ACCEPT END-ACCEPT. " +
|
||||
"END-ADD END-CALL END-COMPUTE END-DELETE END-DISPLAY " +
|
||||
"END-DIVIDE END-EVALUATE END-IF END-INVOKE END-MULTIPLY " +
|
||||
"END-OF-PAGE END-PERFORM END-READ END-RECEIVE END-RETURN " +
|
||||
"END-REWRITE END-SEARCH END-START END-STRING END-SUBTRACT " +
|
||||
"END-UNSTRING END-WRITE END-XML ENTER ENTRY " +
|
||||
"ENVIRONMENT EOP EQUAL EQUALS ERASE " +
|
||||
"ERROR ESI EVALUATE EVERY EXCEEDS " +
|
||||
"EXCEPTION EXCLUSIVE EXIT EXTEND EXTERNAL " +
|
||||
"EXTERNALLY-DESCRIBED-KEY FD FETCH FILE FILE-CONTROL " +
|
||||
"FILE-STREAM FILES FILLER FINAL FIND " +
|
||||
"FINISH FIRST FOOTING FOR FOREGROUND-COLOR " +
|
||||
"FOREGROUND-COLOUR FORMAT FREE FROM FULL " +
|
||||
"FUNCTION GENERATE GET GIVING GLOBAL " +
|
||||
"GO GOBACK GREATER GROUP HEADING " +
|
||||
"HIGH-VALUE HIGH-VALUES HIGHLIGHT I-O I-O-CONTROL " +
|
||||
"ID IDENTIFICATION IF IN INDEX " +
|
||||
"INDEX-1 INDEX-2 INDEX-3 INDEX-4 INDEX-5 " +
|
||||
"INDEX-6 INDEX-7 INDEX-8 INDEX-9 INDEXED " +
|
||||
"INDIC INDICATE INDICATOR INDICATORS INITIAL " +
|
||||
"INITIALIZE INITIATE INPUT INPUT-OUTPUT INSPECT " +
|
||||
"INSTALLATION INTO INVALID INVOKE IS " +
|
||||
"JUST JUSTIFIED KANJI KEEP KEY " +
|
||||
"LABEL LAST LD LEADING LEFT " +
|
||||
"LEFT-JUSTIFY LENGTH LENGTH-CHECK LESS LIBRARY " +
|
||||
"LIKE LIMIT LIMITS LINAGE LINAGE-COUNTER " +
|
||||
"LINE LINE-COUNTER LINES LINKAGE LOCAL-STORAGE " +
|
||||
"LOCALE LOCALLY LOCK " +
|
||||
"MEMBER MEMORY MERGE MESSAGE METACLASS " +
|
||||
"MODE MODIFIED MODIFY MODULES MOVE " +
|
||||
"MULTIPLE MULTIPLY NATIONAL NATIVE NEGATIVE " +
|
||||
"NEXT NO NO-ECHO NONE NOT " +
|
||||
"NULL NULL-KEY-MAP NULL-MAP NULLS NUMBER " +
|
||||
"NUMERIC NUMERIC-EDITED OBJECT OBJECT-COMPUTER OCCURS " +
|
||||
"OF OFF OMITTED ON ONLY " +
|
||||
"OPEN OPTIONAL OR ORDER ORGANIZATION " +
|
||||
"OTHER OUTPUT OVERFLOW OWNER PACKED-DECIMAL " +
|
||||
"PADDING PAGE PAGE-COUNTER PARSE PERFORM " +
|
||||
"PF PH PIC PICTURE PLUS " +
|
||||
"POINTER POSITION POSITIVE PREFIX PRESENT " +
|
||||
"PRINTING PRIOR PROCEDURE PROCEDURE-POINTER PROCEDURES " +
|
||||
"PROCEED PROCESS PROCESSING PROGRAM PROGRAM-ID " +
|
||||
"PROMPT PROTECTED PURGE QUEUE QUOTE " +
|
||||
"QUOTES RANDOM RD READ READY " +
|
||||
"REALM RECEIVE RECONNECT RECORD RECORD-NAME " +
|
||||
"RECORDS RECURSIVE REDEFINES REEL REFERENCE " +
|
||||
"REFERENCE-MONITOR REFERENCES RELATION RELATIVE RELEASE " +
|
||||
"REMAINDER REMOVAL RENAMES REPEATED REPLACE " +
|
||||
"REPLACING REPORT REPORTING REPORTS REPOSITORY " +
|
||||
"REQUIRED RERUN RESERVE RESET RETAINING " +
|
||||
"RETRIEVAL RETURN RETURN-CODE RETURNING REVERSE-VIDEO " +
|
||||
"REVERSED REWIND REWRITE RF RH " +
|
||||
"RIGHT RIGHT-JUSTIFY ROLLBACK ROLLING ROUNDED " +
|
||||
"RUN SAME SCREEN SD SEARCH " +
|
||||
"SECTION SECURE SECURITY SEGMENT SEGMENT-LIMIT " +
|
||||
"SELECT SEND SENTENCE SEPARATE SEQUENCE " +
|
||||
"SEQUENTIAL SET SHARED SIGN SIZE " +
|
||||
"SKIP1 SKIP2 SKIP3 SORT SORT-MERGE " +
|
||||
"SORT-RETURN SOURCE SOURCE-COMPUTER SPACE-FILL " +
|
||||
"SPECIAL-NAMES STANDARD STANDARD-1 STANDARD-2 " +
|
||||
"START STARTING STATUS STOP STORE " +
|
||||
"STRING SUB-QUEUE-1 SUB-QUEUE-2 SUB-QUEUE-3 SUB-SCHEMA " +
|
||||
"SUBFILE SUBSTITUTE SUBTRACT SUM SUPPRESS " +
|
||||
"SYMBOLIC SYNC SYNCHRONIZED SYSIN SYSOUT " +
|
||||
"TABLE TALLYING TAPE TENANT TERMINAL " +
|
||||
"TERMINATE TEST TEXT THAN THEN " +
|
||||
"THROUGH THRU TIME TIMES TITLE " +
|
||||
"TO TOP TRAILING TRAILING-SIGN TRANSACTION " +
|
||||
"TYPE TYPEDEF UNDERLINE UNEQUAL UNIT " +
|
||||
"UNSTRING UNTIL UP UPDATE UPON " +
|
||||
"USAGE USAGE-MODE USE USING VALID " +
|
||||
"VALIDATE VALUE VALUES VARYING VLR " +
|
||||
"WAIT WHEN WHEN-COMPILED WITH WITHIN " +
|
||||
"WORDS WORKING-STORAGE WRITE XML XML-CODE " +
|
||||
"XML-EVENT XML-NTEXT XML-TEXT ZERO ZERO-FILL " );
|
||||
|
||||
var builtins = makeKeywords("- * ** / + < <= = > >= ");
|
||||
var tests = {
|
||||
digit: /\d/,
|
||||
digit_or_colon: /[\d:]/,
|
||||
hex: /[0-9a-f]/i,
|
||||
sign: /[+-]/,
|
||||
exponent: /e/i,
|
||||
keyword_char: /[^\s\(\[\;\)\]]/,
|
||||
symbol: /[\w*+\-]/
|
||||
};
|
||||
function isNumber(ch, stream){
|
||||
// hex
|
||||
if ( ch === '0' && stream.eat(/x/i) ) {
|
||||
stream.eatWhile(tests.hex);
|
||||
return true;
|
||||
}
|
||||
// leading sign
|
||||
if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
|
||||
stream.eat(tests.sign);
|
||||
ch = stream.next();
|
||||
}
|
||||
if ( tests.digit.test(ch) ) {
|
||||
stream.eat(ch);
|
||||
stream.eatWhile(tests.digit);
|
||||
if ( '.' == stream.peek()) {
|
||||
stream.eat('.');
|
||||
stream.eatWhile(tests.digit);
|
||||
}
|
||||
if ( stream.eat(tests.exponent) ) {
|
||||
stream.eat(tests.sign);
|
||||
stream.eatWhile(tests.digit);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return {
|
||||
startState: function () {
|
||||
return {
|
||||
indentStack: null,
|
||||
indentation: 0,
|
||||
mode: false
|
||||
};
|
||||
},
|
||||
token: function (stream, state) {
|
||||
if (state.indentStack == null && stream.sol()) {
|
||||
// update indentation, but only if indentStack is empty
|
||||
state.indentation = 6 ; //stream.indentation();
|
||||
}
|
||||
// skip spaces
|
||||
if (stream.eatSpace()) {
|
||||
return null;
|
||||
}
|
||||
var returnType = null;
|
||||
switch(state.mode){
|
||||
case "string": // multi-line string parsing mode
|
||||
var next = false;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == "\"" || next == "\'") {
|
||||
state.mode = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
returnType = STRING; // continue on in string mode
|
||||
break;
|
||||
default: // default parsing mode
|
||||
var ch = stream.next();
|
||||
var col = stream.column();
|
||||
if (col >= 0 && col <= 5) {
|
||||
returnType = COBOLLINENUM;
|
||||
} else if (col >= 72 && col <= 79) {
|
||||
stream.skipToEnd();
|
||||
returnType = MODTAG;
|
||||
} else if (ch == "*" && col == 6) { // comment
|
||||
stream.skipToEnd(); // rest of the line is a comment
|
||||
returnType = COMMENT;
|
||||
} else if (ch == "\"" || ch == "\'") {
|
||||
state.mode = "string";
|
||||
returnType = STRING;
|
||||
} else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
|
||||
returnType = ATOM;
|
||||
} else if (ch == ".") {
|
||||
returnType = PERIOD;
|
||||
} else if (isNumber(ch,stream)){
|
||||
returnType = NUMBER;
|
||||
} else {
|
||||
if (stream.current().match(tests.symbol)) {
|
||||
while (col < 71) {
|
||||
if (stream.eat(tests.symbol) === undefined) {
|
||||
break;
|
||||
} else {
|
||||
col++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {
|
||||
returnType = KEYWORD;
|
||||
} else if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) {
|
||||
returnType = BUILTIN;
|
||||
} else if (atoms && atoms.propertyIsEnumerable(stream.current().toUpperCase())) {
|
||||
returnType = ATOM;
|
||||
} else returnType = null;
|
||||
}
|
||||
}
|
||||
return returnType;
|
||||
},
|
||||
indent: function (state) {
|
||||
if (state.indentStack == null) return state.indentation;
|
||||
return state.indentStack.indent;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-cobol", "cobol");
|
||||
@@ -1,210 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: COBOL mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<link rel="stylesheet" href="../../theme/neat.css">
|
||||
<link rel="stylesheet" href="../../theme/elegant.css">
|
||||
<link rel="stylesheet" href="../../theme/erlang-dark.css">
|
||||
<link rel="stylesheet" href="../../theme/night.css">
|
||||
<link rel="stylesheet" href="../../theme/monokai.css">
|
||||
<link rel="stylesheet" href="../../theme/cobalt.css">
|
||||
<link rel="stylesheet" href="../../theme/eclipse.css">
|
||||
<link rel="stylesheet" href="../../theme/rubyblue.css">
|
||||
<link rel="stylesheet" href="../../theme/lesser-dark.css">
|
||||
<link rel="stylesheet" href="../../theme/xq-dark.css">
|
||||
<link rel="stylesheet" href="../../theme/xq-light.css">
|
||||
<link rel="stylesheet" href="../../theme/ambiance.css">
|
||||
<link rel="stylesheet" href="../../theme/blackboard.css">
|
||||
<link rel="stylesheet" href="../../theme/vibrant-ink.css">
|
||||
<link rel="stylesheet" href="../../theme/solarized.css">
|
||||
<link rel="stylesheet" href="../../theme/twilight.css">
|
||||
<link rel="stylesheet" href="../../theme/midnight.css">
|
||||
<link rel="stylesheet" href="../../addon/dialog/dialog.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/edit/matchbrackets.js"></script>
|
||||
<script src="cobol.js"></script>
|
||||
<script src="../../addon/selection/active-line.js"></script>
|
||||
<script src="../../addon/search/search.js"></script>
|
||||
<script src="../../addon/dialog/dialog.js"></script>
|
||||
<script src="../../addon/search/searchcursor.js"></script>
|
||||
<style>
|
||||
.CodeMirror {
|
||||
border: 1px solid #eee;
|
||||
font-size : 20px;
|
||||
height : auto !important;
|
||||
}
|
||||
.CodeMirror-activeline-background {background: #555555 !important;}
|
||||
</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">COBOL</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>COBOL mode</h2>
|
||||
|
||||
<p> Select Theme <select onchange="selectTheme()" id="selectTheme">
|
||||
<option>default</option>
|
||||
<option>ambiance</option>
|
||||
<option>blackboard</option>
|
||||
<option>cobalt</option>
|
||||
<option>eclipse</option>
|
||||
<option>elegant</option>
|
||||
<option>erlang-dark</option>
|
||||
<option>lesser-dark</option>
|
||||
<option>midnight</option>
|
||||
<option>monokai</option>
|
||||
<option>neat</option>
|
||||
<option>night</option>
|
||||
<option>rubyblue</option>
|
||||
<option>solarized dark</option>
|
||||
<option>solarized light</option>
|
||||
<option selected>twilight</option>
|
||||
<option>vibrant-ink</option>
|
||||
<option>xq-dark</option>
|
||||
<option>xq-light</option>
|
||||
</select> Select Font Size <select onchange="selectFontsize()" id="selectFontSize">
|
||||
<option value="13px">13px</option>
|
||||
<option value="14px">14px</option>
|
||||
<option value="16px">16px</option>
|
||||
<option value="18px">18px</option>
|
||||
<option value="20px" selected="selected">20px</option>
|
||||
<option value="24px">24px</option>
|
||||
<option value="26px">26px</option>
|
||||
<option value="28px">28px</option>
|
||||
<option value="30px">30px</option>
|
||||
<option value="32px">32px</option>
|
||||
<option value="34px">34px</option>
|
||||
<option value="36px">36px</option>
|
||||
</select>
|
||||
<label for="checkBoxReadOnly">Read-only</label>
|
||||
<input type="checkbox" id="checkBoxReadOnly" onchange="selectReadOnly()">
|
||||
<label for="id_tabToIndentSpace">Insert Spaces on Tab</label>
|
||||
<input type="checkbox" id="id_tabToIndentSpace" onchange="tabToIndentSpace()">
|
||||
</p>
|
||||
<textarea id="code" name="code">
|
||||
---------1---------2---------3---------4---------5---------6---------7---------8
|
||||
12345678911234567892123456789312345678941234567895123456789612345678971234567898
|
||||
000010 IDENTIFICATION DIVISION. MODTGHERE
|
||||
000020 PROGRAM-ID. SAMPLE.
|
||||
000030 AUTHOR. TEST SAM.
|
||||
000040 DATE-WRITTEN. 5 February 2013
|
||||
000041
|
||||
000042* A sample program just to show the form.
|
||||
000043* The program copies its input to the output,
|
||||
000044* and counts the number of records.
|
||||
000045* At the end this number is printed.
|
||||
000046
|
||||
000050 ENVIRONMENT DIVISION.
|
||||
000060 INPUT-OUTPUT SECTION.
|
||||
000070 FILE-CONTROL.
|
||||
000080 SELECT STUDENT-FILE ASSIGN TO SYSIN
|
||||
000090 ORGANIZATION IS LINE SEQUENTIAL.
|
||||
000100 SELECT PRINT-FILE ASSIGN TO SYSOUT
|
||||
000110 ORGANIZATION IS LINE SEQUENTIAL.
|
||||
000120
|
||||
000130 DATA DIVISION.
|
||||
000140 FILE SECTION.
|
||||
000150 FD STUDENT-FILE
|
||||
000160 RECORD CONTAINS 43 CHARACTERS
|
||||
000170 DATA RECORD IS STUDENT-IN.
|
||||
000180 01 STUDENT-IN PIC X(43).
|
||||
000190
|
||||
000200 FD PRINT-FILE
|
||||
000210 RECORD CONTAINS 80 CHARACTERS
|
||||
000220 DATA RECORD IS PRINT-LINE.
|
||||
000230 01 PRINT-LINE PIC X(80).
|
||||
000240
|
||||
000250 WORKING-STORAGE SECTION.
|
||||
000260 01 DATA-REMAINS-SWITCH PIC X(2) VALUE SPACES.
|
||||
000261 01 RECORDS-WRITTEN PIC 99.
|
||||
000270
|
||||
000280 01 DETAIL-LINE.
|
||||
000290 05 FILLER PIC X(7) VALUE SPACES.
|
||||
000300 05 RECORD-IMAGE PIC X(43).
|
||||
000310 05 FILLER PIC X(30) VALUE SPACES.
|
||||
000311
|
||||
000312 01 SUMMARY-LINE.
|
||||
000313 05 FILLER PIC X(7) VALUE SPACES.
|
||||
000314 05 TOTAL-READ PIC 99.
|
||||
000315 05 FILLER PIC X VALUE SPACE.
|
||||
000316 05 FILLER PIC X(17)
|
||||
000317 VALUE 'Records were read'.
|
||||
000318 05 FILLER PIC X(53) VALUE SPACES.
|
||||
000319
|
||||
000320 PROCEDURE DIVISION.
|
||||
000321
|
||||
000330 PREPARE-SENIOR-REPORT.
|
||||
000340 OPEN INPUT STUDENT-FILE
|
||||
000350 OUTPUT PRINT-FILE.
|
||||
000351 MOVE ZERO TO RECORDS-WRITTEN.
|
||||
000360 READ STUDENT-FILE
|
||||
000370 AT END MOVE 'NO' TO DATA-REMAINS-SWITCH
|
||||
000380 END-READ.
|
||||
000390 PERFORM PROCESS-RECORDS
|
||||
000410 UNTIL DATA-REMAINS-SWITCH = 'NO'.
|
||||
000411 PERFORM PRINT-SUMMARY.
|
||||
000420 CLOSE STUDENT-FILE
|
||||
000430 PRINT-FILE.
|
||||
000440 STOP RUN.
|
||||
000450
|
||||
000460 PROCESS-RECORDS.
|
||||
000470 MOVE STUDENT-IN TO RECORD-IMAGE.
|
||||
000480 MOVE DETAIL-LINE TO PRINT-LINE.
|
||||
000490 WRITE PRINT-LINE.
|
||||
000500 ADD 1 TO RECORDS-WRITTEN.
|
||||
000510 READ STUDENT-FILE
|
||||
000520 AT END MOVE 'NO' TO DATA-REMAINS-SWITCH
|
||||
000530 END-READ.
|
||||
000540
|
||||
000550 PRINT-SUMMARY.
|
||||
000560 MOVE RECORDS-WRITTEN TO TOTAL-READ.
|
||||
000570 MOVE SUMMARY-LINE TO PRINT-LINE.
|
||||
000571 WRITE PRINT-LINE.
|
||||
000572
|
||||
000580
|
||||
</textarea>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
mode: "text/x-cobol",
|
||||
theme : "twilight",
|
||||
styleActiveLine: true,
|
||||
showCursorWhenSelecting : true,
|
||||
});
|
||||
function selectTheme() {
|
||||
var themeInput = document.getElementById("selectTheme");
|
||||
var theme = themeInput.options[themeInput.selectedIndex].innerHTML;
|
||||
editor.setOption("theme", theme);
|
||||
}
|
||||
function selectFontsize() {
|
||||
var fontSizeInput = document.getElementById("selectFontSize");
|
||||
var fontSize = fontSizeInput.options[fontSizeInput.selectedIndex].innerHTML;
|
||||
editor.getWrapperElement().style["font-size"] = fontSize;
|
||||
editor.refresh();
|
||||
}
|
||||
function selectReadOnly() {
|
||||
editor.setOption("readOnly", document.getElementById("checkBoxReadOnly").checked);
|
||||
}
|
||||
function tabToIndentSpace() {
|
||||
if (document.getElementById("id_tabToIndentSpace").checked) {
|
||||
editor.setOption("extraKeys", {Tab: function(cm) { cm.replaceSelection(" ", "end"); }});
|
||||
} else {
|
||||
editor.setOption("extraKeys", {Tab: function(cm) { cm.replaceSelection(" ", "end"); }});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</article>
|
||||
@@ -1,348 +0,0 @@
|
||||
/**
|
||||
* Link to the project's GitHub page:
|
||||
* https://github.com/pickhardt/coffeescript-codemirror-mode
|
||||
*/
|
||||
CodeMirror.defineMode('coffeescript', function(conf) {
|
||||
var ERRORCLASS = 'error';
|
||||
|
||||
function wordRegexp(words) {
|
||||
return new RegExp("^((" + words.join(")|(") + "))\\b");
|
||||
}
|
||||
|
||||
var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\?]");
|
||||
var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\},:`=;\\.]');
|
||||
var doubleOperators = new RegExp("^((\->)|(\=>)|(\\+\\+)|(\\+\\=)|(\\-\\-)|(\\-\\=)|(\\*\\*)|(\\*\\=)|(\\/\\/)|(\\/\\=)|(==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//))");
|
||||
var doubleDelimiters = new RegExp("^((\\.\\.)|(\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
|
||||
var tripleDelimiters = new RegExp("^((\\.\\.\\.)|(//=)|(>>=)|(<<=)|(\\*\\*=))");
|
||||
var identifiers = new RegExp("^[_A-Za-z$][_A-Za-z$0-9]*");
|
||||
var properties = new RegExp("^(@|this\.)[_A-Za-z$][_A-Za-z$0-9]*");
|
||||
|
||||
var wordOperators = wordRegexp(['and', 'or', 'not',
|
||||
'is', 'isnt', 'in',
|
||||
'instanceof', 'typeof']);
|
||||
var indentKeywords = ['for', 'while', 'loop', 'if', 'unless', 'else',
|
||||
'switch', 'try', 'catch', 'finally', 'class'];
|
||||
var commonKeywords = ['break', 'by', 'continue', 'debugger', 'delete',
|
||||
'do', 'in', 'of', 'new', 'return', 'then',
|
||||
'this', 'throw', 'when', 'until'];
|
||||
|
||||
var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
|
||||
|
||||
indentKeywords = wordRegexp(indentKeywords);
|
||||
|
||||
|
||||
var stringPrefixes = new RegExp("^('{3}|\"{3}|['\"])");
|
||||
var regexPrefixes = new RegExp("^(/{3}|/)");
|
||||
var commonConstants = ['Infinity', 'NaN', 'undefined', 'null', 'true', 'false', 'on', 'off', 'yes', 'no'];
|
||||
var constants = wordRegexp(commonConstants);
|
||||
|
||||
// Tokenizers
|
||||
function tokenBase(stream, state) {
|
||||
// Handle scope changes
|
||||
if (stream.sol()) {
|
||||
var scopeOffset = state.scopes[0].offset;
|
||||
if (stream.eatSpace()) {
|
||||
var lineOffset = stream.indentation();
|
||||
if (lineOffset > scopeOffset) {
|
||||
return 'indent';
|
||||
} else if (lineOffset < scopeOffset) {
|
||||
return 'dedent';
|
||||
}
|
||||
return null;
|
||||
} else {
|
||||
if (scopeOffset > 0) {
|
||||
dedent(stream, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stream.eatSpace()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var ch = stream.peek();
|
||||
|
||||
// Handle docco title comment (single line)
|
||||
if (stream.match("####")) {
|
||||
stream.skipToEnd();
|
||||
return 'comment';
|
||||
}
|
||||
|
||||
// Handle multi line comments
|
||||
if (stream.match("###")) {
|
||||
state.tokenize = longComment;
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
|
||||
// Single line comment
|
||||
if (ch === '#') {
|
||||
stream.skipToEnd();
|
||||
return 'comment';
|
||||
}
|
||||
|
||||
// Handle number literals
|
||||
if (stream.match(/^-?[0-9\.]/, false)) {
|
||||
var floatLiteral = false;
|
||||
// Floats
|
||||
if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) {
|
||||
floatLiteral = true;
|
||||
}
|
||||
if (stream.match(/^-?\d+\.\d*/)) {
|
||||
floatLiteral = true;
|
||||
}
|
||||
if (stream.match(/^-?\.\d+/)) {
|
||||
floatLiteral = true;
|
||||
}
|
||||
|
||||
if (floatLiteral) {
|
||||
// prevent from getting extra . on 1..
|
||||
if (stream.peek() == "."){
|
||||
stream.backUp(1);
|
||||
}
|
||||
return 'number';
|
||||
}
|
||||
// Integers
|
||||
var intLiteral = false;
|
||||
// Hex
|
||||
if (stream.match(/^-?0x[0-9a-f]+/i)) {
|
||||
intLiteral = true;
|
||||
}
|
||||
// Decimal
|
||||
if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
|
||||
intLiteral = true;
|
||||
}
|
||||
// Zero by itself with no other piece of number.
|
||||
if (stream.match(/^-?0(?![\dx])/i)) {
|
||||
intLiteral = true;
|
||||
}
|
||||
if (intLiteral) {
|
||||
return 'number';
|
||||
}
|
||||
}
|
||||
|
||||
// Handle strings
|
||||
if (stream.match(stringPrefixes)) {
|
||||
state.tokenize = tokenFactory(stream.current(), 'string');
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
// Handle regex literals
|
||||
if (stream.match(regexPrefixes)) {
|
||||
if (stream.current() != '/' || stream.match(/^.*\//, false)) { // prevent highlight of division
|
||||
state.tokenize = tokenFactory(stream.current(), 'string-2');
|
||||
return state.tokenize(stream, state);
|
||||
} else {
|
||||
stream.backUp(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle operators and delimiters
|
||||
if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
|
||||
return 'punctuation';
|
||||
}
|
||||
if (stream.match(doubleOperators)
|
||||
|| stream.match(singleOperators)
|
||||
|| stream.match(wordOperators)) {
|
||||
return 'operator';
|
||||
}
|
||||
if (stream.match(singleDelimiters)) {
|
||||
return 'punctuation';
|
||||
}
|
||||
|
||||
if (stream.match(constants)) {
|
||||
return 'atom';
|
||||
}
|
||||
|
||||
if (stream.match(keywords)) {
|
||||
return 'keyword';
|
||||
}
|
||||
|
||||
if (stream.match(identifiers)) {
|
||||
return 'variable';
|
||||
}
|
||||
|
||||
if (stream.match(properties)) {
|
||||
return 'property';
|
||||
}
|
||||
|
||||
// Handle non-detected items
|
||||
stream.next();
|
||||
return ERRORCLASS;
|
||||
}
|
||||
|
||||
function tokenFactory(delimiter, outclass) {
|
||||
var singleline = delimiter.length == 1;
|
||||
return function(stream, state) {
|
||||
while (!stream.eol()) {
|
||||
stream.eatWhile(/[^'"\/\\]/);
|
||||
if (stream.eat('\\')) {
|
||||
stream.next();
|
||||
if (singleline && stream.eol()) {
|
||||
return outclass;
|
||||
}
|
||||
} else if (stream.match(delimiter)) {
|
||||
state.tokenize = tokenBase;
|
||||
return outclass;
|
||||
} else {
|
||||
stream.eat(/['"\/]/);
|
||||
}
|
||||
}
|
||||
if (singleline) {
|
||||
if (conf.mode.singleLineStringErrors) {
|
||||
outclass = ERRORCLASS;
|
||||
} else {
|
||||
state.tokenize = tokenBase;
|
||||
}
|
||||
}
|
||||
return outclass;
|
||||
};
|
||||
}
|
||||
|
||||
function longComment(stream, state) {
|
||||
while (!stream.eol()) {
|
||||
stream.eatWhile(/[^#]/);
|
||||
if (stream.match("###")) {
|
||||
state.tokenize = tokenBase;
|
||||
break;
|
||||
}
|
||||
stream.eatWhile("#");
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function indent(stream, state, type) {
|
||||
type = type || 'coffee';
|
||||
var indentUnit = 0;
|
||||
if (type === 'coffee') {
|
||||
for (var i = 0; i < state.scopes.length; i++) {
|
||||
if (state.scopes[i].type === 'coffee') {
|
||||
indentUnit = state.scopes[i].offset + conf.indentUnit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
indentUnit = stream.column() + stream.current().length;
|
||||
}
|
||||
state.scopes.unshift({
|
||||
offset: indentUnit,
|
||||
type: type
|
||||
});
|
||||
}
|
||||
|
||||
function dedent(stream, state) {
|
||||
if (state.scopes.length == 1) return;
|
||||
if (state.scopes[0].type === 'coffee') {
|
||||
var _indent = stream.indentation();
|
||||
var _indent_index = -1;
|
||||
for (var i = 0; i < state.scopes.length; ++i) {
|
||||
if (_indent === state.scopes[i].offset) {
|
||||
_indent_index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (_indent_index === -1) {
|
||||
return true;
|
||||
}
|
||||
while (state.scopes[0].offset !== _indent) {
|
||||
state.scopes.shift();
|
||||
}
|
||||
return false;
|
||||
} else {
|
||||
state.scopes.shift();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function tokenLexer(stream, state) {
|
||||
var style = state.tokenize(stream, state);
|
||||
var current = stream.current();
|
||||
|
||||
// Handle '.' connected identifiers
|
||||
if (current === '.') {
|
||||
style = state.tokenize(stream, state);
|
||||
current = stream.current();
|
||||
if (/^\.[\w$]+$/.test(current)) {
|
||||
return 'variable';
|
||||
} else {
|
||||
return ERRORCLASS;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle scope changes.
|
||||
if (current === 'return') {
|
||||
state.dedent += 1;
|
||||
}
|
||||
if (((current === '->' || current === '=>') &&
|
||||
!state.lambda &&
|
||||
state.scopes[0].type == 'coffee' &&
|
||||
stream.peek() === '')
|
||||
|| style === 'indent') {
|
||||
indent(stream, state);
|
||||
}
|
||||
var delimiter_index = '[({'.indexOf(current);
|
||||
if (delimiter_index !== -1) {
|
||||
indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
|
||||
}
|
||||
if (indentKeywords.exec(current)){
|
||||
indent(stream, state);
|
||||
}
|
||||
if (current == 'then'){
|
||||
dedent(stream, state);
|
||||
}
|
||||
|
||||
|
||||
if (style === 'dedent') {
|
||||
if (dedent(stream, state)) {
|
||||
return ERRORCLASS;
|
||||
}
|
||||
}
|
||||
delimiter_index = '])}'.indexOf(current);
|
||||
if (delimiter_index !== -1) {
|
||||
if (dedent(stream, state)) {
|
||||
return ERRORCLASS;
|
||||
}
|
||||
}
|
||||
if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'coffee') {
|
||||
if (state.scopes.length > 1) state.scopes.shift();
|
||||
state.dedent -= 1;
|
||||
}
|
||||
|
||||
return style;
|
||||
}
|
||||
|
||||
var external = {
|
||||
startState: function(basecolumn) {
|
||||
return {
|
||||
tokenize: tokenBase,
|
||||
scopes: [{offset:basecolumn || 0, type:'coffee'}],
|
||||
lastToken: null,
|
||||
lambda: false,
|
||||
dedent: 0
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
var style = tokenLexer(stream, state);
|
||||
|
||||
state.lastToken = {style:style, content: stream.current()};
|
||||
|
||||
if (stream.eol() && stream.lambda) {
|
||||
state.lambda = false;
|
||||
}
|
||||
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function(state) {
|
||||
if (state.tokenize != tokenBase) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return state.scopes[0].offset;
|
||||
},
|
||||
|
||||
lineComment: "#",
|
||||
fold: "indent"
|
||||
};
|
||||
return external;
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME('text/x-coffeescript', 'coffeescript');
|
||||
@@ -1,740 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: CoffeeScript mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="coffeescript.js"></script>
|
||||
<style>.CodeMirror {border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">CoffeeScript</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>CoffeeScript mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
# CoffeeScript mode for CodeMirror
|
||||
# Copyright (c) 2011 Jeff Pickhardt, released under
|
||||
# the MIT License.
|
||||
#
|
||||
# Modified from the Python CodeMirror mode, which also is
|
||||
# under the MIT License Copyright (c) 2010 Timothy Farrell.
|
||||
#
|
||||
# The following script, Underscore.coffee, is used to
|
||||
# demonstrate CoffeeScript mode for CodeMirror.
|
||||
#
|
||||
# To download CoffeeScript mode for CodeMirror, go to:
|
||||
# https://github.com/pickhardt/coffeescript-codemirror-mode
|
||||
|
||||
# **Underscore.coffee
|
||||
# (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**
|
||||
# Underscore is freely distributable under the terms of the
|
||||
# [MIT license](http://en.wikipedia.org/wiki/MIT_License).
|
||||
# Portions of Underscore are inspired by or borrowed from
|
||||
# [Prototype.js](http://prototypejs.org/api), Oliver Steele's
|
||||
# [Functional](http://osteele.com), and John Resig's
|
||||
# [Micro-Templating](http://ejohn.org).
|
||||
# For all details and documentation:
|
||||
# http://documentcloud.github.com/underscore/
|
||||
|
||||
|
||||
# Baseline setup
|
||||
# --------------
|
||||
|
||||
# Establish the root object, `window` in the browser, or `global` on the server.
|
||||
root = this
|
||||
|
||||
|
||||
# Save the previous value of the `_` variable.
|
||||
previousUnderscore = root._
|
||||
|
||||
### Multiline
|
||||
comment
|
||||
###
|
||||
|
||||
# Establish the object that gets thrown to break out of a loop iteration.
|
||||
# `StopIteration` is SOP on Mozilla.
|
||||
breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
|
||||
|
||||
|
||||
#### Docco style single line comment (title)
|
||||
|
||||
|
||||
# Helper function to escape **RegExp** contents, because JS doesn't have one.
|
||||
escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1')
|
||||
|
||||
|
||||
# Save bytes in the minified (but not gzipped) version:
|
||||
ArrayProto = Array.prototype
|
||||
ObjProto = Object.prototype
|
||||
|
||||
|
||||
# Create quick reference variables for speed access to core prototypes.
|
||||
slice = ArrayProto.slice
|
||||
unshift = ArrayProto.unshift
|
||||
toString = ObjProto.toString
|
||||
hasOwnProperty = ObjProto.hasOwnProperty
|
||||
propertyIsEnumerable = ObjProto.propertyIsEnumerable
|
||||
|
||||
|
||||
# All **ECMA5** native implementations we hope to use are declared here.
|
||||
nativeForEach = ArrayProto.forEach
|
||||
nativeMap = ArrayProto.map
|
||||
nativeReduce = ArrayProto.reduce
|
||||
nativeReduceRight = ArrayProto.reduceRight
|
||||
nativeFilter = ArrayProto.filter
|
||||
nativeEvery = ArrayProto.every
|
||||
nativeSome = ArrayProto.some
|
||||
nativeIndexOf = ArrayProto.indexOf
|
||||
nativeLastIndexOf = ArrayProto.lastIndexOf
|
||||
nativeIsArray = Array.isArray
|
||||
nativeKeys = Object.keys
|
||||
|
||||
|
||||
# Create a safe reference to the Underscore object for use below.
|
||||
_ = (obj) -> new wrapper(obj)
|
||||
|
||||
|
||||
# Export the Underscore object for **CommonJS**.
|
||||
if typeof(exports) != 'undefined' then exports._ = _
|
||||
|
||||
|
||||
# Export Underscore to global scope.
|
||||
root._ = _
|
||||
|
||||
|
||||
# Current version.
|
||||
_.VERSION = '1.1.0'
|
||||
|
||||
|
||||
# Collection Functions
|
||||
# --------------------
|
||||
|
||||
# The cornerstone, an **each** implementation.
|
||||
# Handles objects implementing **forEach**, arrays, and raw objects.
|
||||
_.each = (obj, iterator, context) ->
|
||||
try
|
||||
if nativeForEach and obj.forEach is nativeForEach
|
||||
obj.forEach iterator, context
|
||||
else if _.isNumber obj.length
|
||||
iterator.call context, obj[i], i, obj for i in [0...obj.length]
|
||||
else
|
||||
iterator.call context, val, key, obj for own key, val of obj
|
||||
catch e
|
||||
throw e if e isnt breaker
|
||||
obj
|
||||
|
||||
|
||||
# Return the results of applying the iterator to each element. Use JavaScript
|
||||
# 1.6's version of **map**, if possible.
|
||||
_.map = (obj, iterator, context) ->
|
||||
return obj.map(iterator, context) if nativeMap and obj.map is nativeMap
|
||||
results = []
|
||||
_.each obj, (value, index, list) ->
|
||||
results.push iterator.call context, value, index, list
|
||||
results
|
||||
|
||||
|
||||
# **Reduce** builds up a single result from a list of values. Also known as
|
||||
# **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.
|
||||
_.reduce = (obj, iterator, memo, context) ->
|
||||
if nativeReduce and obj.reduce is nativeReduce
|
||||
iterator = _.bind iterator, context if context
|
||||
return obj.reduce iterator, memo
|
||||
_.each obj, (value, index, list) ->
|
||||
memo = iterator.call context, memo, value, index, list
|
||||
memo
|
||||
|
||||
|
||||
# The right-associative version of **reduce**, also known as **foldr**. Uses
|
||||
# JavaScript 1.8's version of **reduceRight**, if available.
|
||||
_.reduceRight = (obj, iterator, memo, context) ->
|
||||
if nativeReduceRight and obj.reduceRight is nativeReduceRight
|
||||
iterator = _.bind iterator, context if context
|
||||
return obj.reduceRight iterator, memo
|
||||
reversed = _.clone(_.toArray(obj)).reverse()
|
||||
_.reduce reversed, iterator, memo, context
|
||||
|
||||
|
||||
# Return the first value which passes a truth test.
|
||||
_.detect = (obj, iterator, context) ->
|
||||
result = null
|
||||
_.each obj, (value, index, list) ->
|
||||
if iterator.call context, value, index, list
|
||||
result = value
|
||||
_.breakLoop()
|
||||
result
|
||||
|
||||
|
||||
# Return all the elements that pass a truth test. Use JavaScript 1.6's
|
||||
# **filter**, if it exists.
|
||||
_.filter = (obj, iterator, context) ->
|
||||
return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter
|
||||
results = []
|
||||
_.each obj, (value, index, list) ->
|
||||
results.push value if iterator.call context, value, index, list
|
||||
results
|
||||
|
||||
|
||||
# Return all the elements for which a truth test fails.
|
||||
_.reject = (obj, iterator, context) ->
|
||||
results = []
|
||||
_.each obj, (value, index, list) ->
|
||||
results.push value if not iterator.call context, value, index, list
|
||||
results
|
||||
|
||||
|
||||
# Determine whether all of the elements match a truth test. Delegate to
|
||||
# JavaScript 1.6's **every**, if it is present.
|
||||
_.every = (obj, iterator, context) ->
|
||||
iterator ||= _.identity
|
||||
return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
|
||||
result = true
|
||||
_.each obj, (value, index, list) ->
|
||||
_.breakLoop() unless (result = result and iterator.call(context, value, index, list))
|
||||
result
|
||||
|
||||
|
||||
# Determine if at least one element in the object matches a truth test. Use
|
||||
# JavaScript 1.6's **some**, if it exists.
|
||||
_.some = (obj, iterator, context) ->
|
||||
iterator ||= _.identity
|
||||
return obj.some iterator, context if nativeSome and obj.some is nativeSome
|
||||
result = false
|
||||
_.each obj, (value, index, list) ->
|
||||
_.breakLoop() if (result = iterator.call(context, value, index, list))
|
||||
result
|
||||
|
||||
|
||||
# Determine if a given value is included in the array or object,
|
||||
# based on `===`.
|
||||
_.include = (obj, target) ->
|
||||
return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf
|
||||
return true for own key, val of obj when val is target
|
||||
false
|
||||
|
||||
|
||||
# Invoke a method with arguments on every item in a collection.
|
||||
_.invoke = (obj, method) ->
|
||||
args = _.rest arguments, 2
|
||||
(if method then val[method] else val).apply(val, args) for val in obj
|
||||
|
||||
|
||||
# Convenience version of a common use case of **map**: fetching a property.
|
||||
_.pluck = (obj, key) ->
|
||||
_.map(obj, (val) -> val[key])
|
||||
|
||||
|
||||
# Return the maximum item or (item-based computation).
|
||||
_.max = (obj, iterator, context) ->
|
||||
return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
|
||||
result = computed: -Infinity
|
||||
_.each obj, (value, index, list) ->
|
||||
computed = if iterator then iterator.call(context, value, index, list) else value
|
||||
computed >= result.computed and (result = {value: value, computed: computed})
|
||||
result.value
|
||||
|
||||
|
||||
# Return the minimum element (or element-based computation).
|
||||
_.min = (obj, iterator, context) ->
|
||||
return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
|
||||
result = computed: Infinity
|
||||
_.each obj, (value, index, list) ->
|
||||
computed = if iterator then iterator.call(context, value, index, list) else value
|
||||
computed < result.computed and (result = {value: value, computed: computed})
|
||||
result.value
|
||||
|
||||
|
||||
# Sort the object's values by a criterion produced by an iterator.
|
||||
_.sortBy = (obj, iterator, context) ->
|
||||
_.pluck(((_.map obj, (value, index, list) ->
|
||||
{value: value, criteria: iterator.call(context, value, index, list)}
|
||||
).sort((left, right) ->
|
||||
a = left.criteria; b = right.criteria
|
||||
if a < b then -1 else if a > b then 1 else 0
|
||||
)), 'value')
|
||||
|
||||
|
||||
# Use a comparator function to figure out at what index an object should
|
||||
# be inserted so as to maintain order. Uses binary search.
|
||||
_.sortedIndex = (array, obj, iterator) ->
|
||||
iterator ||= _.identity
|
||||
low = 0
|
||||
high = array.length
|
||||
while low < high
|
||||
mid = (low + high) >> 1
|
||||
if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
|
||||
low
|
||||
|
||||
|
||||
# Convert anything iterable into a real, live array.
|
||||
_.toArray = (iterable) ->
|
||||
return [] if (!iterable)
|
||||
return iterable.toArray() if (iterable.toArray)
|
||||
return iterable if (_.isArray(iterable))
|
||||
return slice.call(iterable) if (_.isArguments(iterable))
|
||||
_.values(iterable)
|
||||
|
||||
|
||||
# Return the number of elements in an object.
|
||||
_.size = (obj) -> _.toArray(obj).length
|
||||
|
||||
|
||||
# Array Functions
|
||||
# ---------------
|
||||
|
||||
# Get the first element of an array. Passing `n` will return the first N
|
||||
# values in the array. Aliased as **head**. The `guard` check allows it to work
|
||||
# with **map**.
|
||||
_.first = (array, n, guard) ->
|
||||
if n and not guard then slice.call(array, 0, n) else array[0]
|
||||
|
||||
|
||||
# Returns everything but the first entry of the array. Aliased as **tail**.
|
||||
# Especially useful on the arguments object. Passing an `index` will return
|
||||
# the rest of the values in the array from that index onward. The `guard`
|
||||
# check allows it to work with **map**.
|
||||
_.rest = (array, index, guard) ->
|
||||
slice.call(array, if _.isUndefined(index) or guard then 1 else index)
|
||||
|
||||
|
||||
# Get the last element of an array.
|
||||
_.last = (array) -> array[array.length - 1]
|
||||
|
||||
|
||||
# Trim out all falsy values from an array.
|
||||
_.compact = (array) -> item for item in array when item
|
||||
|
||||
|
||||
# Return a completely flattened version of an array.
|
||||
_.flatten = (array) ->
|
||||
_.reduce array, (memo, value) ->
|
||||
return memo.concat(_.flatten(value)) if _.isArray value
|
||||
memo.push value
|
||||
memo
|
||||
, []
|
||||
|
||||
|
||||
# Return a version of the array that does not contain the specified value(s).
|
||||
_.without = (array) ->
|
||||
values = _.rest arguments
|
||||
val for val in _.toArray(array) when not _.include values, val
|
||||
|
||||
|
||||
# Produce a duplicate-free version of the array. If the array has already
|
||||
# been sorted, you have the option of using a faster algorithm.
|
||||
_.uniq = (array, isSorted) ->
|
||||
memo = []
|
||||
for el, i in _.toArray array
|
||||
memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
|
||||
memo
|
||||
|
||||
|
||||
# Produce an array that contains every item shared between all the
|
||||
# passed-in arrays.
|
||||
_.intersect = (array) ->
|
||||
rest = _.rest arguments
|
||||
_.select _.uniq(array), (item) ->
|
||||
_.all rest, (other) ->
|
||||
_.indexOf(other, item) >= 0
|
||||
|
||||
|
||||
# Zip together multiple lists into a single array -- elements that share
|
||||
# an index go together.
|
||||
_.zip = ->
|
||||
length = _.max _.pluck arguments, 'length'
|
||||
results = new Array length
|
||||
for i in [0...length]
|
||||
results[i] = _.pluck arguments, String i
|
||||
results
|
||||
|
||||
|
||||
# If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),
|
||||
# we need this function. Return the position of the first occurrence of an
|
||||
# item in an array, or -1 if the item is not included in the array.
|
||||
_.indexOf = (array, item) ->
|
||||
return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
|
||||
i = 0; l = array.length
|
||||
while l - i
|
||||
if array[i] is item then return i else i++
|
||||
-1
|
||||
|
||||
|
||||
# Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,
|
||||
# if possible.
|
||||
_.lastIndexOf = (array, item) ->
|
||||
return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf
|
||||
i = array.length
|
||||
while i
|
||||
if array[i] is item then return i else i--
|
||||
-1
|
||||
|
||||
|
||||
# Generate an integer Array containing an arithmetic progression. A port of
|
||||
# [the native Python **range** function](http://docs.python.org/library/functions.html#range).
|
||||
_.range = (start, stop, step) ->
|
||||
a = arguments
|
||||
solo = a.length <= 1
|
||||
i = start = if solo then 0 else a[0]
|
||||
stop = if solo then a[0] else a[1]
|
||||
step = a[2] or 1
|
||||
len = Math.ceil((stop - start) / step)
|
||||
return [] if len <= 0
|
||||
range = new Array len
|
||||
idx = 0
|
||||
loop
|
||||
return range if (if step > 0 then i - stop else stop - i) >= 0
|
||||
range[idx] = i
|
||||
idx++
|
||||
i+= step
|
||||
|
||||
|
||||
# Function Functions
|
||||
# ------------------
|
||||
|
||||
# Create a function bound to a given object (assigning `this`, and arguments,
|
||||
# optionally). Binding with arguments is also known as **curry**.
|
||||
_.bind = (func, obj) ->
|
||||
args = _.rest arguments, 2
|
||||
-> func.apply obj or root, args.concat arguments
|
||||
|
||||
|
||||
# Bind all of an object's methods to that object. Useful for ensuring that
|
||||
# all callbacks defined on an object belong to it.
|
||||
_.bindAll = (obj) ->
|
||||
funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
|
||||
_.each funcs, (f) -> obj[f] = _.bind obj[f], obj
|
||||
obj
|
||||
|
||||
|
||||
# Delays a function for the given number of milliseconds, and then calls
|
||||
# it with the arguments supplied.
|
||||
_.delay = (func, wait) ->
|
||||
args = _.rest arguments, 2
|
||||
setTimeout((-> func.apply(func, args)), wait)
|
||||
|
||||
|
||||
# Memoize an expensive function by storing its results.
|
||||
_.memoize = (func, hasher) ->
|
||||
memo = {}
|
||||
hasher or= _.identity
|
||||
->
|
||||
key = hasher.apply this, arguments
|
||||
return memo[key] if key of memo
|
||||
memo[key] = func.apply this, arguments
|
||||
|
||||
|
||||
# Defers a function, scheduling it to run after the current call stack has
|
||||
# cleared.
|
||||
_.defer = (func) ->
|
||||
_.delay.apply _, [func, 1].concat _.rest arguments
|
||||
|
||||
|
||||
# Returns the first function passed as an argument to the second,
|
||||
# allowing you to adjust arguments, run code before and after, and
|
||||
# conditionally execute the original function.
|
||||
_.wrap = (func, wrapper) ->
|
||||
-> wrapper.apply wrapper, [func].concat arguments
|
||||
|
||||
|
||||
# Returns a function that is the composition of a list of functions, each
|
||||
# consuming the return value of the function that follows.
|
||||
_.compose = ->
|
||||
funcs = arguments
|
||||
->
|
||||
args = arguments
|
||||
for i in [funcs.length - 1..0] by -1
|
||||
args = [funcs[i].apply(this, args)]
|
||||
args[0]
|
||||
|
||||
|
||||
# Object Functions
|
||||
# ----------------
|
||||
|
||||
# Retrieve the names of an object's properties.
|
||||
_.keys = nativeKeys or (obj) ->
|
||||
return _.range 0, obj.length if _.isArray(obj)
|
||||
key for key, val of obj
|
||||
|
||||
|
||||
# Retrieve the values of an object's properties.
|
||||
_.values = (obj) ->
|
||||
_.map obj, _.identity
|
||||
|
||||
|
||||
# Return a sorted list of the function names available in Underscore.
|
||||
_.functions = (obj) ->
|
||||
_.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
|
||||
|
||||
|
||||
# Extend a given object with all of the properties in a source object.
|
||||
_.extend = (obj) ->
|
||||
for source in _.rest(arguments)
|
||||
obj[key] = val for key, val of source
|
||||
obj
|
||||
|
||||
|
||||
# Create a (shallow-cloned) duplicate of an object.
|
||||
_.clone = (obj) ->
|
||||
return obj.slice 0 if _.isArray obj
|
||||
_.extend {}, obj
|
||||
|
||||
|
||||
# Invokes interceptor with the obj, and then returns obj.
|
||||
# The primary purpose of this method is to "tap into" a method chain,
|
||||
# in order to perform operations on intermediate results within
|
||||
the chain.
|
||||
_.tap = (obj, interceptor) ->
|
||||
interceptor obj
|
||||
obj
|
||||
|
||||
|
||||
# Perform a deep comparison to check if two objects are equal.
|
||||
_.isEqual = (a, b) ->
|
||||
# Check object identity.
|
||||
return true if a is b
|
||||
# Different types?
|
||||
atype = typeof(a); btype = typeof(b)
|
||||
return false if atype isnt btype
|
||||
# Basic equality test (watch out for coercions).
|
||||
return true if `a == b`
|
||||
# One is falsy and the other truthy.
|
||||
return false if (!a and b) or (a and !b)
|
||||
# One of them implements an `isEqual()`?
|
||||
return a.isEqual(b) if a.isEqual
|
||||
# Check dates' integer values.
|
||||
return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)
|
||||
# Both are NaN?
|
||||
return false if _.isNaN(a) and _.isNaN(b)
|
||||
# Compare regular expressions.
|
||||
if _.isRegExp(a) and _.isRegExp(b)
|
||||
return a.source is b.source and
|
||||
a.global is b.global and
|
||||
a.ignoreCase is b.ignoreCase and
|
||||
a.multiline is b.multiline
|
||||
# If a is not an object by this point, we can't handle it.
|
||||
return false if atype isnt 'object'
|
||||
# Check for different array lengths before comparing contents.
|
||||
return false if a.length and (a.length isnt b.length)
|
||||
# Nothing else worked, deep compare the contents.
|
||||
aKeys = _.keys(a); bKeys = _.keys(b)
|
||||
# Different object sizes?
|
||||
return false if aKeys.length isnt bKeys.length
|
||||
# Recursive comparison of contents.
|
||||
return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])
|
||||
true
|
||||
|
||||
|
||||
# Is a given array or object empty?
|
||||
_.isEmpty = (obj) ->
|
||||
return obj.length is 0 if _.isArray(obj) or _.isString(obj)
|
||||
return false for own key of obj
|
||||
true
|
||||
|
||||
|
||||
# Is a given value a DOM element?
|
||||
_.isElement = (obj) -> obj and obj.nodeType is 1
|
||||
|
||||
|
||||
# Is a given value an array?
|
||||
_.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)
|
||||
|
||||
|
||||
# Is a given variable an arguments object?
|
||||
_.isArguments = (obj) -> obj and obj.callee
|
||||
|
||||
|
||||
# Is the given value a function?
|
||||
_.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
|
||||
|
||||
|
||||
# Is the given value a string?
|
||||
_.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
|
||||
|
||||
|
||||
# Is a given value a number?
|
||||
_.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
|
||||
|
||||
|
||||
# Is a given value a boolean?
|
||||
_.isBoolean = (obj) -> obj is true or obj is false
|
||||
|
||||
|
||||
# Is a given value a Date?
|
||||
_.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
|
||||
|
||||
|
||||
# Is the given value a regular expression?
|
||||
_.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
|
||||
|
||||
|
||||
# Is the given value NaN -- this one is interesting. `NaN != NaN`, and
|
||||
# `isNaN(undefined) == true`, so we make sure it's a number first.
|
||||
_.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)
|
||||
|
||||
|
||||
# Is a given value equal to null?
|
||||
_.isNull = (obj) -> obj is null
|
||||
|
||||
|
||||
# Is a given variable undefined?
|
||||
_.isUndefined = (obj) -> typeof obj is 'undefined'
|
||||
|
||||
|
||||
# Utility Functions
|
||||
# -----------------
|
||||
|
||||
# Run Underscore.js in noConflict mode, returning the `_` variable to its
|
||||
# previous owner. Returns a reference to the Underscore object.
|
||||
_.noConflict = ->
|
||||
root._ = previousUnderscore
|
||||
this
|
||||
|
||||
|
||||
# Keep the identity function around for default iterators.
|
||||
_.identity = (value) -> value
|
||||
|
||||
|
||||
# Run a function `n` times.
|
||||
_.times = (n, iterator, context) ->
|
||||
iterator.call context, i for i in [0...n]
|
||||
|
||||
|
||||
# Break out of the middle of an iteration.
|
||||
_.breakLoop = -> throw breaker
|
||||
|
||||
|
||||
# Add your own custom functions to the Underscore object, ensuring that
|
||||
# they're correctly added to the OOP wrapper as well.
|
||||
_.mixin = (obj) ->
|
||||
for name in _.functions(obj)
|
||||
addToWrapper name, _[name] = obj[name]
|
||||
|
||||
|
||||
# Generate a unique integer id (unique within the entire client session).
|
||||
# Useful for temporary DOM ids.
|
||||
idCounter = 0
|
||||
_.uniqueId = (prefix) ->
|
||||
(prefix or '') + idCounter++
|
||||
|
||||
|
||||
# By default, Underscore uses **ERB**-style template delimiters, change the
|
||||
# following template settings to use alternative delimiters.
|
||||
_.templateSettings = {
|
||||
start: '<%'
|
||||
end: '%>'
|
||||
interpolate: /<%=(.+?)%>/g
|
||||
}
|
||||
|
||||
|
||||
# JavaScript templating a-la **ERB**, pilfered from John Resig's
|
||||
# *Secrets of the JavaScript Ninja*, page 83.
|
||||
# Single-quote fix from Rick Strahl.
|
||||
# With alterations for arbitrary delimiters, and to preserve whitespace.
|
||||
_.template = (str, data) ->
|
||||
c = _.templateSettings
|
||||
endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g")
|
||||
fn = new Function 'obj',
|
||||
'var p=[],print=function(){p.push.apply(p,arguments);};' +
|
||||
'with(obj||{}){p.push(\'' +
|
||||
str.replace(/\r/g, '\\r')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\t/g, '\\t')
|
||||
.replace(endMatch,"<22><><EFBFBD>")
|
||||
.split("'").join("\\'")
|
||||
.split("<22><><EFBFBD>").join("'")
|
||||
.replace(c.interpolate, "',$1,'")
|
||||
.split(c.start).join("');")
|
||||
.split(c.end).join("p.push('") +
|
||||
"');}return p.join('');"
|
||||
if data then fn(data) else fn
|
||||
|
||||
|
||||
# Aliases
|
||||
# -------
|
||||
|
||||
_.forEach = _.each
|
||||
_.foldl = _.inject = _.reduce
|
||||
_.foldr = _.reduceRight
|
||||
_.select = _.filter
|
||||
_.all = _.every
|
||||
_.any = _.some
|
||||
_.contains = _.include
|
||||
_.head = _.first
|
||||
_.tail = _.rest
|
||||
_.methods = _.functions
|
||||
|
||||
|
||||
# Setup the OOP Wrapper
|
||||
# ---------------------
|
||||
|
||||
# If Underscore is called as a function, it returns a wrapped object that
|
||||
# can be used OO-style. This wrapper holds altered versions of all the
|
||||
# underscore functions. Wrapped objects may be chained.
|
||||
wrapper = (obj) ->
|
||||
this._wrapped = obj
|
||||
this
|
||||
|
||||
|
||||
# Helper function to continue chaining intermediate results.
|
||||
result = (obj, chain) ->
|
||||
if chain then _(obj).chain() else obj
|
||||
|
||||
|
||||
# A method to easily add functions to the OOP wrapper.
|
||||
addToWrapper = (name, func) ->
|
||||
wrapper.prototype[name] = ->
|
||||
args = _.toArray arguments
|
||||
unshift.call args, this._wrapped
|
||||
result func.apply(_, args), this._chain
|
||||
|
||||
|
||||
# Add all ofthe Underscore functions to the wrapper object.
|
||||
_.mixin _
|
||||
|
||||
|
||||
# Add all mutator Array functions to the wrapper.
|
||||
_.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
|
||||
method = Array.prototype[name]
|
||||
wrapper.prototype[name] = ->
|
||||
method.apply(this._wrapped, arguments)
|
||||
result(this._wrapped, this._chain)
|
||||
|
||||
|
||||
# Add all accessor Array functions to the wrapper.
|
||||
_.each ['concat', 'join', 'slice'], (name) ->
|
||||
method = Array.prototype[name]
|
||||
wrapper.prototype[name] = ->
|
||||
result(method.apply(this._wrapped, arguments), this._chain)
|
||||
|
||||
|
||||
# Start chaining a wrapped Underscore object.
|
||||
wrapper::chain = ->
|
||||
this._chain = true
|
||||
this
|
||||
|
||||
|
||||
# Extracts the result from a wrapped and chained object.
|
||||
wrapper::value = -> this._wrapped
|
||||
</textarea></form>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-coffeescript</code>.</p>
|
||||
|
||||
<p>The CoffeeScript mode was written by Jeff Pickhardt (<a href="LICENSE">license</a>).</p>
|
||||
|
||||
</article>
|
||||
@@ -1,105 +0,0 @@
|
||||
CodeMirror.defineMode("commonlisp", function (config) {
|
||||
var assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/;
|
||||
var numLiteral = /^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/;
|
||||
var symbol = /[^\s'`,@()\[\]";]/;
|
||||
var type;
|
||||
|
||||
function readSym(stream) {
|
||||
var ch;
|
||||
while (ch = stream.next()) {
|
||||
if (ch == "\\") stream.next();
|
||||
else if (!symbol.test(ch)) { stream.backUp(1); break; }
|
||||
}
|
||||
return stream.current();
|
||||
}
|
||||
|
||||
function base(stream, state) {
|
||||
if (stream.eatSpace()) {type = "ws"; return null;}
|
||||
if (stream.match(numLiteral)) return "number";
|
||||
var ch = stream.next();
|
||||
if (ch == "\\") ch = stream.next();
|
||||
|
||||
if (ch == '"') return (state.tokenize = inString)(stream, state);
|
||||
else if (ch == "(") { type = "open"; return "bracket"; }
|
||||
else if (ch == ")" || ch == "]") { type = "close"; return "bracket"; }
|
||||
else if (ch == ";") { stream.skipToEnd(); type = "ws"; return "comment"; }
|
||||
else if (/['`,@]/.test(ch)) return null;
|
||||
else if (ch == "|") {
|
||||
if (stream.skipTo("|")) { stream.next(); return "symbol"; }
|
||||
else { stream.skipToEnd(); return "error"; }
|
||||
} else if (ch == "#") {
|
||||
var ch = stream.next();
|
||||
if (ch == "[") { type = "open"; return "bracket"; }
|
||||
else if (/[+\-=\.']/.test(ch)) return null;
|
||||
else if (/\d/.test(ch) && stream.match(/^\d*#/)) return null;
|
||||
else if (ch == "|") return (state.tokenize = inComment)(stream, state);
|
||||
else if (ch == ":") { readSym(stream); return "meta"; }
|
||||
else return "error";
|
||||
} else {
|
||||
var name = readSym(stream);
|
||||
if (name == ".") return null;
|
||||
type = "symbol";
|
||||
if (name == "nil" || name == "t") return "atom";
|
||||
if (name.charAt(0) == ":") return "keyword";
|
||||
if (name.charAt(0) == "&") return "variable-2";
|
||||
return "variable";
|
||||
}
|
||||
}
|
||||
|
||||
function inString(stream, state) {
|
||||
var escaped = false, next;
|
||||
while (next = stream.next()) {
|
||||
if (next == '"' && !escaped) { state.tokenize = base; break; }
|
||||
escaped = !escaped && next == "\\";
|
||||
}
|
||||
return "string";
|
||||
}
|
||||
|
||||
function inComment(stream, state) {
|
||||
var next, last;
|
||||
while (next = stream.next()) {
|
||||
if (next == "#" && last == "|") { state.tokenize = base; break; }
|
||||
last = next;
|
||||
}
|
||||
type = "ws";
|
||||
return "comment";
|
||||
}
|
||||
|
||||
return {
|
||||
startState: function () {
|
||||
return {ctx: {prev: null, start: 0, indentTo: 0}, tokenize: base};
|
||||
},
|
||||
|
||||
token: function (stream, state) {
|
||||
if (stream.sol() && typeof state.ctx.indentTo != "number")
|
||||
state.ctx.indentTo = state.ctx.start + 1;
|
||||
|
||||
type = null;
|
||||
var style = state.tokenize(stream, state);
|
||||
if (type != "ws") {
|
||||
if (state.ctx.indentTo == null) {
|
||||
if (type == "symbol" && assumeBody.test(stream.current()))
|
||||
state.ctx.indentTo = state.ctx.start + config.indentUnit;
|
||||
else
|
||||
state.ctx.indentTo = "next";
|
||||
} else if (state.ctx.indentTo == "next") {
|
||||
state.ctx.indentTo = stream.column();
|
||||
}
|
||||
}
|
||||
if (type == "open") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};
|
||||
else if (type == "close") state.ctx = state.ctx.prev || state.ctx;
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function (state, _textAfter) {
|
||||
var i = state.ctx.indentTo;
|
||||
return typeof i == "number" ? i : state.ctx.start + 1;
|
||||
},
|
||||
|
||||
lineComment: ";;",
|
||||
blockCommentStart: "#|",
|
||||
blockCommentEnd: "|#"
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-common-lisp", "commonlisp");
|
||||
@@ -1,177 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Common Lisp mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="commonlisp.js"></script>
|
||||
<style>.CodeMirror {background: #f8f8f8;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Common Lisp</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Common Lisp mode</h2>
|
||||
<form><textarea id="code" name="code">(in-package :cl-postgres)
|
||||
|
||||
;; These are used to synthesize reader and writer names for integer
|
||||
;; reading/writing functions when the amount of bytes and the
|
||||
;; signedness is known. Both the macro that creates the functions and
|
||||
;; some macros that use them create names this way.
|
||||
(eval-when (:compile-toplevel :load-toplevel :execute)
|
||||
(defun integer-reader-name (bytes signed)
|
||||
(intern (with-standard-io-syntax
|
||||
(format nil "~a~a~a~a" '#:read- (if signed "" '#:u) '#:int bytes))))
|
||||
(defun integer-writer-name (bytes signed)
|
||||
(intern (with-standard-io-syntax
|
||||
(format nil "~a~a~a~a" '#:write- (if signed "" '#:u) '#:int bytes)))))
|
||||
|
||||
(defmacro integer-reader (bytes)
|
||||
"Create a function to read integers from a binary stream."
|
||||
(let ((bits (* bytes 8)))
|
||||
(labels ((return-form (signed)
|
||||
(if signed
|
||||
`(if (logbitp ,(1- bits) result)
|
||||
(dpb result (byte ,(1- bits) 0) -1)
|
||||
result)
|
||||
`result))
|
||||
(generate-reader (signed)
|
||||
`(defun ,(integer-reader-name bytes signed) (socket)
|
||||
(declare (type stream socket)
|
||||
#.*optimize*)
|
||||
,(if (= bytes 1)
|
||||
`(let ((result (the (unsigned-byte 8) (read-byte socket))))
|
||||
(declare (type (unsigned-byte 8) result))
|
||||
,(return-form signed))
|
||||
`(let ((result 0))
|
||||
(declare (type (unsigned-byte ,bits) result))
|
||||
,@(loop :for byte :from (1- bytes) :downto 0
|
||||
:collect `(setf (ldb (byte 8 ,(* 8 byte)) result)
|
||||
(the (unsigned-byte 8) (read-byte socket))))
|
||||
,(return-form signed))))))
|
||||
`(progn
|
||||
;; This causes weird errors on SBCL in some circumstances. Disabled for now.
|
||||
;; (declaim (inline ,(integer-reader-name bytes t)
|
||||
;; ,(integer-reader-name bytes nil)))
|
||||
(declaim (ftype (function (t) (signed-byte ,bits))
|
||||
,(integer-reader-name bytes t)))
|
||||
,(generate-reader t)
|
||||
(declaim (ftype (function (t) (unsigned-byte ,bits))
|
||||
,(integer-reader-name bytes nil)))
|
||||
,(generate-reader nil)))))
|
||||
|
||||
(defmacro integer-writer (bytes)
|
||||
"Create a function to write integers to a binary stream."
|
||||
(let ((bits (* 8 bytes)))
|
||||
`(progn
|
||||
(declaim (inline ,(integer-writer-name bytes t)
|
||||
,(integer-writer-name bytes nil)))
|
||||
(defun ,(integer-writer-name bytes nil) (socket value)
|
||||
(declare (type stream socket)
|
||||
(type (unsigned-byte ,bits) value)
|
||||
#.*optimize*)
|
||||
,@(if (= bytes 1)
|
||||
`((write-byte value socket))
|
||||
(loop :for byte :from (1- bytes) :downto 0
|
||||
:collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)
|
||||
socket)))
|
||||
(values))
|
||||
(defun ,(integer-writer-name bytes t) (socket value)
|
||||
(declare (type stream socket)
|
||||
(type (signed-byte ,bits) value)
|
||||
#.*optimize*)
|
||||
,@(if (= bytes 1)
|
||||
`((write-byte (ldb (byte 8 0) value) socket))
|
||||
(loop :for byte :from (1- bytes) :downto 0
|
||||
:collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)
|
||||
socket)))
|
||||
(values)))))
|
||||
|
||||
;; All the instances of the above that we need.
|
||||
|
||||
(integer-reader 1)
|
||||
(integer-reader 2)
|
||||
(integer-reader 4)
|
||||
(integer-reader 8)
|
||||
|
||||
(integer-writer 1)
|
||||
(integer-writer 2)
|
||||
(integer-writer 4)
|
||||
|
||||
(defun write-bytes (socket bytes)
|
||||
"Write a byte-array to a stream."
|
||||
(declare (type stream socket)
|
||||
(type (simple-array (unsigned-byte 8)) bytes)
|
||||
#.*optimize*)
|
||||
(write-sequence bytes socket))
|
||||
|
||||
(defun write-str (socket string)
|
||||
"Write a null-terminated string to a stream \(encoding it when UTF-8
|
||||
support is enabled.)."
|
||||
(declare (type stream socket)
|
||||
(type string string)
|
||||
#.*optimize*)
|
||||
(enc-write-string string socket)
|
||||
(write-uint1 socket 0))
|
||||
|
||||
(declaim (ftype (function (t unsigned-byte)
|
||||
(simple-array (unsigned-byte 8) (*)))
|
||||
read-bytes))
|
||||
(defun read-bytes (socket length)
|
||||
"Read a byte array of the given length from a stream."
|
||||
(declare (type stream socket)
|
||||
(type fixnum length)
|
||||
#.*optimize*)
|
||||
(let ((result (make-array length :element-type '(unsigned-byte 8))))
|
||||
(read-sequence result socket)
|
||||
result))
|
||||
|
||||
(declaim (ftype (function (t) string) read-str))
|
||||
(defun read-str (socket)
|
||||
"Read a null-terminated string from a stream. Takes care of encoding
|
||||
when UTF-8 support is enabled."
|
||||
(declare (type stream socket)
|
||||
#.*optimize*)
|
||||
(enc-read-string socket :null-terminated t))
|
||||
|
||||
(defun skip-bytes (socket length)
|
||||
"Skip a given number of bytes in a binary stream."
|
||||
(declare (type stream socket)
|
||||
(type (unsigned-byte 32) length)
|
||||
#.*optimize*)
|
||||
(dotimes (i length)
|
||||
(read-byte socket)))
|
||||
|
||||
(defun skip-str (socket)
|
||||
"Skip a null-terminated string."
|
||||
(declare (type stream socket)
|
||||
#.*optimize*)
|
||||
(loop :for char :of-type fixnum = (read-byte socket)
|
||||
:until (zerop char)))
|
||||
|
||||
(defun ensure-socket-is-closed (socket &key abort)
|
||||
(when (open-stream-p socket)
|
||||
(handler-case
|
||||
(close socket :abort abort)
|
||||
(error (error)
|
||||
(warn "Ignoring the error which happened while trying to close PostgreSQL socket: ~A" error)))))
|
||||
</textarea></form>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {lineNumbers: true});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-common-lisp</code>.</p>
|
||||
|
||||
</article>
|
||||
636
applications/admin/static/codemirror/mode/css/css.js
vendored
636
applications/admin/static/codemirror/mode/css/css.js
vendored
@@ -4,86 +4,79 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
|
||||
if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
|
||||
|
||||
var indentUnit = config.indentUnit,
|
||||
hooks = parserConfig.hooks || {},
|
||||
atMediaTypes = parserConfig.atMediaTypes || {},
|
||||
atMediaFeatures = parserConfig.atMediaFeatures || {},
|
||||
tokenHooks = parserConfig.tokenHooks,
|
||||
mediaTypes = parserConfig.mediaTypes || {},
|
||||
mediaFeatures = parserConfig.mediaFeatures || {},
|
||||
propertyKeywords = parserConfig.propertyKeywords || {},
|
||||
colorKeywords = parserConfig.colorKeywords || {},
|
||||
valueKeywords = parserConfig.valueKeywords || {},
|
||||
allowNested = !!parserConfig.allowNested,
|
||||
type = null;
|
||||
fontProperties = parserConfig.fontProperties || {},
|
||||
allowNested = parserConfig.allowNested;
|
||||
|
||||
var type, override;
|
||||
function ret(style, tp) { type = tp; return style; }
|
||||
|
||||
// Tokenizers
|
||||
|
||||
function tokenBase(stream, state) {
|
||||
var ch = stream.next();
|
||||
if (hooks[ch]) {
|
||||
// result[0] is style and result[1] is type
|
||||
var result = hooks[ch](stream, state);
|
||||
if (tokenHooks[ch]) {
|
||||
var result = tokenHooks[ch](stream, state);
|
||||
if (result !== false) return result;
|
||||
}
|
||||
if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current());}
|
||||
else if (ch == "=") ret(null, "compare");
|
||||
else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
|
||||
else if (ch == "\"" || ch == "'") {
|
||||
if (ch == "@") {
|
||||
stream.eatWhile(/[\w\\\-]/);
|
||||
return ret("def", stream.current());
|
||||
} else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
|
||||
return ret(null, "compare");
|
||||
} else if (ch == "\"" || ch == "'") {
|
||||
state.tokenize = tokenString(ch);
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
else if (ch == "#") {
|
||||
} else if (ch == "#") {
|
||||
stream.eatWhile(/[\w\\\-]/);
|
||||
return ret("atom", "hash");
|
||||
}
|
||||
else if (ch == "!") {
|
||||
} else if (ch == "!") {
|
||||
stream.match(/^\s*\w*/);
|
||||
return ret("keyword", "important");
|
||||
}
|
||||
else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
|
||||
} else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
|
||||
stream.eatWhile(/[\w.%]/);
|
||||
return ret("number", "unit");
|
||||
}
|
||||
else if (ch === "-") {
|
||||
if (/\d/.test(stream.peek())) {
|
||||
} else if (ch === "-") {
|
||||
if (/[\d.]/.test(stream.peek())) {
|
||||
stream.eatWhile(/[\w.%]/);
|
||||
return ret("number", "unit");
|
||||
} else if (stream.match(/^[^-]+-/)) {
|
||||
return ret("meta", "meta");
|
||||
}
|
||||
}
|
||||
else if (/[,+>*\/]/.test(ch)) {
|
||||
} else if (/[,+>*\/]/.test(ch)) {
|
||||
return ret(null, "select-op");
|
||||
}
|
||||
else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
|
||||
} else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
|
||||
return ret("qualifier", "qualifier");
|
||||
}
|
||||
else if (ch == ":") {
|
||||
return ret("operator", ch);
|
||||
}
|
||||
else if (/[;{}\[\]\(\)]/.test(ch)) {
|
||||
} else if (/[:;{}\[\]\(\)]/.test(ch)) {
|
||||
return ret(null, ch);
|
||||
}
|
||||
else if (ch == "u" && stream.match("rl(")) {
|
||||
} else if (ch == "u" && stream.match("rl(")) {
|
||||
stream.backUp(1);
|
||||
state.tokenize = tokenParenthesized;
|
||||
return ret("property", "variable");
|
||||
}
|
||||
else {
|
||||
return ret("property", "word");
|
||||
} else if (/[\w\\\-]/.test(ch)) {
|
||||
stream.eatWhile(/[\w\\\-]/);
|
||||
return ret("property", "variable");
|
||||
return ret("property", "word");
|
||||
} else {
|
||||
return ret(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
function tokenString(quote, nonInclusive) {
|
||||
function tokenString(quote) {
|
||||
return function(stream, state) {
|
||||
var escaped = false, ch;
|
||||
while ((ch = stream.next()) != null) {
|
||||
if (ch == quote && !escaped)
|
||||
if (ch == quote && !escaped) {
|
||||
if (quote == ")") stream.backUp(1);
|
||||
break;
|
||||
}
|
||||
escaped = !escaped && ch == "\\";
|
||||
}
|
||||
if (!escaped) {
|
||||
if (nonInclusive) stream.backUp(1);
|
||||
state.tokenize = tokenBase;
|
||||
}
|
||||
if (ch == quote || !escaped && quote != ")") state.tokenize = null;
|
||||
return ret("string", "string");
|
||||
};
|
||||
}
|
||||
@@ -91,211 +84,238 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
|
||||
function tokenParenthesized(stream, state) {
|
||||
stream.next(); // Must be '('
|
||||
if (!stream.match(/\s*[\"\']/, false))
|
||||
state.tokenize = tokenString(")", true);
|
||||
state.tokenize = tokenString(")");
|
||||
else
|
||||
state.tokenize = tokenBase;
|
||||
state.tokenize = null;
|
||||
return ret(null, "(");
|
||||
}
|
||||
|
||||
// Context management
|
||||
|
||||
function Context(type, indent, prev) {
|
||||
this.type = type;
|
||||
this.indent = indent;
|
||||
this.prev = prev;
|
||||
}
|
||||
|
||||
function pushContext(state, stream, type) {
|
||||
state.context = new Context(type, stream.indentation() + indentUnit, state.context);
|
||||
return type;
|
||||
}
|
||||
|
||||
function popContext(state) {
|
||||
state.context = state.context.prev;
|
||||
return state.context.type;
|
||||
}
|
||||
|
||||
function pass(type, stream, state) {
|
||||
return states[state.context.type](type, stream, state);
|
||||
}
|
||||
function popAndPass(type, stream, state, n) {
|
||||
for (var i = n || 1; i > 0; i--)
|
||||
state.context = state.context.prev;
|
||||
return pass(type, stream, state);
|
||||
}
|
||||
|
||||
// Parser
|
||||
|
||||
function wordAsValue(stream) {
|
||||
var word = stream.current().toLowerCase();
|
||||
if (valueKeywords.hasOwnProperty(word))
|
||||
override = "atom";
|
||||
else if (colorKeywords.hasOwnProperty(word))
|
||||
override = "keyword";
|
||||
else
|
||||
override = "variable";
|
||||
}
|
||||
|
||||
var states = {};
|
||||
|
||||
states.top = function(type, stream, state) {
|
||||
if (type == "{") {
|
||||
return pushContext(state, stream, "block");
|
||||
} else if (type == "}" && state.context.prev) {
|
||||
return popContext(state);
|
||||
} else if (type == "@media") {
|
||||
return pushContext(state, stream, "media");
|
||||
} else if (type == "@font-face") {
|
||||
return "font_face_before";
|
||||
} else if (type && type.charAt(0) == "@") {
|
||||
return pushContext(state, stream, "at");
|
||||
} else if (type == "hash") {
|
||||
override = "builtin";
|
||||
} else if (type == "word") {
|
||||
override = "tag";
|
||||
} else if (type == "variable-definition") {
|
||||
return "maybeprop";
|
||||
} else if (type == "interpolation") {
|
||||
return pushContext(state, stream, "interpolation");
|
||||
} else if (type == ":") {
|
||||
return "pseudo";
|
||||
} else if (allowNested && type == "(") {
|
||||
return pushContext(state, stream, "params");
|
||||
}
|
||||
return state.context.type;
|
||||
};
|
||||
|
||||
states.block = function(type, stream, state) {
|
||||
if (type == "word") {
|
||||
if (propertyKeywords.hasOwnProperty(stream.current().toLowerCase())) {
|
||||
override = "property";
|
||||
return "maybeprop";
|
||||
} else if (allowNested) {
|
||||
override = stream.match(/^\s*:/, false) ? "property" : "tag";
|
||||
return "block";
|
||||
} else {
|
||||
override += " error";
|
||||
return "maybeprop";
|
||||
}
|
||||
} else if (type == "meta") {
|
||||
return "block";
|
||||
} else if (!allowNested && (type == "hash" || type == "qualifier")) {
|
||||
override = "error";
|
||||
return "block";
|
||||
} else {
|
||||
return states.top(type, stream, state);
|
||||
}
|
||||
};
|
||||
|
||||
states.maybeprop = function(type, stream, state) {
|
||||
if (type == ":") return pushContext(state, stream, "prop");
|
||||
return pass(type, stream, state);
|
||||
};
|
||||
|
||||
states.prop = function(type, stream, state) {
|
||||
if (type == ";") return popContext(state);
|
||||
if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
|
||||
if (type == "}" || type == "{") return popAndPass(type, stream, state);
|
||||
if (type == "(") return pushContext(state, stream, "parens");
|
||||
|
||||
if (type == "hash" && !/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) {
|
||||
override += " error";
|
||||
} else if (type == "word") {
|
||||
wordAsValue(stream);
|
||||
} else if (type == "interpolation") {
|
||||
return pushContext(state, stream, "interpolation");
|
||||
}
|
||||
return "prop";
|
||||
};
|
||||
|
||||
states.propBlock = function(type, _stream, state) {
|
||||
if (type == "}") return popContext(state);
|
||||
if (type == "word") { override = "property"; return "maybeprop"; }
|
||||
return state.context.type;
|
||||
};
|
||||
|
||||
states.parens = function(type, stream, state) {
|
||||
if (type == "{" || type == "}") return popAndPass(type, stream, state);
|
||||
if (type == ")") return popContext(state);
|
||||
return "parens";
|
||||
};
|
||||
|
||||
states.pseudo = function(type, stream, state) {
|
||||
if (type == "word") {
|
||||
override = "variable-3";
|
||||
return state.context.type;
|
||||
}
|
||||
return pass(type, stream, state);
|
||||
};
|
||||
|
||||
states.media = function(type, stream, state) {
|
||||
if (type == "(") return pushContext(state, stream, "media_parens");
|
||||
if (type == "}") return popAndPass(type, stream, state);
|
||||
if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
|
||||
|
||||
if (type == "word") {
|
||||
var word = stream.current().toLowerCase();
|
||||
if (word == "only" || word == "not" || word == "and")
|
||||
override = "keyword";
|
||||
else if (mediaTypes.hasOwnProperty(word))
|
||||
override = "attribute";
|
||||
else if (mediaFeatures.hasOwnProperty(word))
|
||||
override = "property";
|
||||
else
|
||||
override = "error";
|
||||
}
|
||||
return state.context.type;
|
||||
};
|
||||
|
||||
states.media_parens = function(type, stream, state) {
|
||||
if (type == ")") return popContext(state);
|
||||
if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
|
||||
return states.media(type, stream, state);
|
||||
};
|
||||
|
||||
states.font_face_before = function(type, stream, state) {
|
||||
if (type == "{")
|
||||
return pushContext(state, stream, "font_face");
|
||||
return pass(type, stream, state);
|
||||
};
|
||||
|
||||
states.font_face = function(type, stream, state) {
|
||||
if (type == "}") return popContext(state);
|
||||
if (type == "word") {
|
||||
if (!fontProperties.hasOwnProperty(stream.current().toLowerCase()))
|
||||
override = "error";
|
||||
else
|
||||
override = "property";
|
||||
return "maybeprop";
|
||||
}
|
||||
return "font_face";
|
||||
};
|
||||
|
||||
states.at = function(type, stream, state) {
|
||||
if (type == ";") return popContext(state);
|
||||
if (type == "{" || type == "}") return popAndPass(type, stream, state);
|
||||
if (type == "word") override = "tag";
|
||||
else if (type == "hash") override = "builtin";
|
||||
return "at";
|
||||
};
|
||||
|
||||
states.interpolation = function(type, stream, state) {
|
||||
if (type == "}") return popContext(state);
|
||||
if (type == "{" || type == ";") return popAndPass(type, stream, state);
|
||||
if (type != "variable") override = "error";
|
||||
return "interpolation";
|
||||
};
|
||||
|
||||
states.params = function(type, stream, state) {
|
||||
if (type == ")") return popContext(state);
|
||||
if (type == "{" || type == "}") return popAndPass(type, stream, state);
|
||||
if (type == "word") wordAsValue(stream);
|
||||
return "params";
|
||||
};
|
||||
|
||||
return {
|
||||
startState: function(base) {
|
||||
return {tokenize: tokenBase,
|
||||
baseIndent: base || 0,
|
||||
stack: [],
|
||||
lastToken: null};
|
||||
return {tokenize: null,
|
||||
state: "top",
|
||||
context: new Context("top", base || 0, null)};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
|
||||
// Use these terms when applicable (see http://www.xanthir.com/blog/b4E50)
|
||||
//
|
||||
// rule** or **ruleset:
|
||||
// A selector + braces combo, or an at-rule.
|
||||
//
|
||||
// declaration block:
|
||||
// A sequence of declarations.
|
||||
//
|
||||
// declaration:
|
||||
// A property + colon + value combo.
|
||||
//
|
||||
// property value:
|
||||
// The entire value of a property.
|
||||
//
|
||||
// component value:
|
||||
// A single piece of a property value. Like the 5px in
|
||||
// text-shadow: 0 0 5px blue;. Can also refer to things that are
|
||||
// multiple terms, like the 1-4 terms that make up the background-size
|
||||
// portion of the background shorthand.
|
||||
//
|
||||
// term:
|
||||
// The basic unit of author-facing CSS, like a single number (5),
|
||||
// dimension (5px), string ("foo"), or function. Officially defined
|
||||
// by the CSS 2.1 grammar (look for the 'term' production)
|
||||
//
|
||||
//
|
||||
// simple selector:
|
||||
// A single atomic selector, like a type selector, an attr selector, a
|
||||
// class selector, etc.
|
||||
//
|
||||
// compound selector:
|
||||
// One or more simple selectors without a combinator. div.example is
|
||||
// compound, div > .example is not.
|
||||
//
|
||||
// complex selector:
|
||||
// One or more compound selectors chained with combinators.
|
||||
//
|
||||
// combinator:
|
||||
// The parts of selectors that express relationships. There are four
|
||||
// currently - the space (descendant combinator), the greater-than
|
||||
// bracket (child combinator), the plus sign (next sibling combinator),
|
||||
// and the tilda (following sibling combinator).
|
||||
//
|
||||
// sequence of selectors:
|
||||
// One or more of the named type of selector chained with commas.
|
||||
|
||||
state.tokenize = state.tokenize || tokenBase;
|
||||
if (state.tokenize == tokenBase && stream.eatSpace()) return null;
|
||||
var style = state.tokenize(stream, state);
|
||||
if (style && typeof style != "string") style = ret(style[0], style[1]);
|
||||
|
||||
// Changing style returned based on context
|
||||
var context = state.stack[state.stack.length-1];
|
||||
if (style == "variable") {
|
||||
if (type == "variable-definition") state.stack.push("propertyValue");
|
||||
return state.lastToken = "variable-2";
|
||||
} else if (style == "property") {
|
||||
var word = stream.current().toLowerCase();
|
||||
if (context == "propertyValue") {
|
||||
if (valueKeywords.hasOwnProperty(word)) {
|
||||
style = "string-2";
|
||||
} else if (colorKeywords.hasOwnProperty(word)) {
|
||||
style = "keyword";
|
||||
} else {
|
||||
style = "variable-2";
|
||||
}
|
||||
} else if (context == "rule") {
|
||||
if (!propertyKeywords.hasOwnProperty(word)) {
|
||||
style += " error";
|
||||
}
|
||||
} else if (context == "block") {
|
||||
// if a value is present in both property, value, or color, the order
|
||||
// of preference is property -> color -> value
|
||||
if (propertyKeywords.hasOwnProperty(word)) {
|
||||
style = "property";
|
||||
} else if (colorKeywords.hasOwnProperty(word)) {
|
||||
style = "keyword";
|
||||
} else if (valueKeywords.hasOwnProperty(word)) {
|
||||
style = "string-2";
|
||||
} else {
|
||||
style = "tag";
|
||||
}
|
||||
} else if (!context || context == "@media{") {
|
||||
style = "tag";
|
||||
} else if (context == "@media") {
|
||||
if (atMediaTypes[stream.current()]) {
|
||||
style = "attribute"; // Known attribute
|
||||
} else if (/^(only|not)$/.test(word)) {
|
||||
style = "keyword";
|
||||
} else if (word == "and") {
|
||||
style = "error"; // "and" is only allowed in @mediaType
|
||||
} else if (atMediaFeatures.hasOwnProperty(word)) {
|
||||
style = "error"; // Known property, should be in @mediaType(
|
||||
} else {
|
||||
// Unknown, expecting keyword or attribute, assuming attribute
|
||||
style = "attribute error";
|
||||
}
|
||||
} else if (context == "@mediaType") {
|
||||
if (atMediaTypes.hasOwnProperty(word)) {
|
||||
style = "attribute";
|
||||
} else if (word == "and") {
|
||||
style = "operator";
|
||||
} else if (/^(only|not)$/.test(word)) {
|
||||
style = "error"; // Only allowed in @media
|
||||
} else {
|
||||
// Unknown attribute or property, but expecting property (preceded
|
||||
// by "and"). Should be in parentheses
|
||||
style = "error";
|
||||
}
|
||||
} else if (context == "@mediaType(") {
|
||||
if (propertyKeywords.hasOwnProperty(word)) {
|
||||
// do nothing, remains "property"
|
||||
} else if (atMediaTypes.hasOwnProperty(word)) {
|
||||
style = "error"; // Known property, should be in parentheses
|
||||
} else if (word == "and") {
|
||||
style = "operator";
|
||||
} else if (/^(only|not)$/.test(word)) {
|
||||
style = "error"; // Only allowed in @media
|
||||
} else {
|
||||
style += " error";
|
||||
}
|
||||
} else if (context == "@import") {
|
||||
style = "tag";
|
||||
} else {
|
||||
style = "error";
|
||||
}
|
||||
} else if (style == "atom") {
|
||||
if(!context || context == "@media{" || context == "block") {
|
||||
style = "builtin";
|
||||
} else if (context == "propertyValue") {
|
||||
if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) {
|
||||
style += " error";
|
||||
}
|
||||
} else {
|
||||
style = "error";
|
||||
}
|
||||
} else if (context == "@media" && type == "{") {
|
||||
style = "error";
|
||||
if (!state.tokenize && stream.eatSpace()) return null;
|
||||
var style = (state.tokenize || tokenBase)(stream, state);
|
||||
if (style && typeof style == "object") {
|
||||
type = style[1];
|
||||
style = style[0];
|
||||
}
|
||||
|
||||
// Push/pop context stack
|
||||
if (type == "{") {
|
||||
if (context == "@media" || context == "@mediaType") {
|
||||
state.stack[state.stack.length-1] = "@media{";
|
||||
}
|
||||
else {
|
||||
var newContext = allowNested ? "block" : "rule";
|
||||
state.stack.push(newContext);
|
||||
}
|
||||
}
|
||||
else if (type == "}") {
|
||||
if (context == "interpolation") style = "operator";
|
||||
state.stack.pop();
|
||||
if (context == "propertyValue") state.stack.pop();
|
||||
}
|
||||
else if (type == "interpolation") state.stack.push("interpolation");
|
||||
else if (type == "@media") state.stack.push("@media");
|
||||
else if (type == "@import") state.stack.push("@import");
|
||||
else if (context == "@media" && /\b(keyword|attribute)\b/.test(style))
|
||||
state.stack[state.stack.length-1] = "@mediaType";
|
||||
else if (context == "@mediaType" && stream.current() == ",")
|
||||
state.stack[state.stack.length-1] = "@media";
|
||||
else if (type == "(") {
|
||||
if (context == "@media" || context == "@mediaType") {
|
||||
// Make sure @mediaType is used to avoid error on {
|
||||
state.stack[state.stack.length-1] = "@mediaType";
|
||||
state.stack.push("@mediaType(");
|
||||
}
|
||||
else state.stack.push("(");
|
||||
}
|
||||
else if (type == ")") {
|
||||
if (context == "propertyValue") {
|
||||
// In @mediaType( without closing ; after propertyValue
|
||||
state.stack.pop();
|
||||
}
|
||||
state.stack.pop();
|
||||
}
|
||||
else if (type == ":" && state.lastToken == "property") state.stack.push("propertyValue");
|
||||
else if (context == "propertyValue" && type == ";") state.stack.pop();
|
||||
else if (context == "@import" && type == ";") state.stack.pop();
|
||||
|
||||
return state.lastToken = style;
|
||||
override = style;
|
||||
state.state = states[state.state](type, stream, state);
|
||||
return override;
|
||||
},
|
||||
|
||||
indent: function(state, textAfter) {
|
||||
var n = state.stack.length;
|
||||
if (/^\}/.test(textAfter))
|
||||
n -= state.stack[n-1] == "propertyValue" ? 2 : 1;
|
||||
return state.baseIndent + n * indentUnit;
|
||||
var cx = state.context, ch = textAfter && textAfter.charAt(0);
|
||||
var indent = cx.indent;
|
||||
if (cx.prev &&
|
||||
(ch == "}" && (cx.type == "block" || cx.type == "top" || cx.type == "interpolation" || cx.type == "font_face") ||
|
||||
ch == ")" && (cx.type == "parens" || cx.type == "params" || cx.type == "media_parens") ||
|
||||
ch == "{" && (cx.type == "at" || cx.type == "media"))) {
|
||||
indent = cx.indent - indentUnit;
|
||||
cx = cx.prev;
|
||||
}
|
||||
return indent;
|
||||
},
|
||||
|
||||
electricChars: "}",
|
||||
@@ -314,12 +334,12 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
|
||||
return keys;
|
||||
}
|
||||
|
||||
var atMediaTypes = keySet([
|
||||
var mediaTypes_ = [
|
||||
"all", "aural", "braille", "handheld", "print", "projection", "screen",
|
||||
"tty", "tv", "embossed"
|
||||
]);
|
||||
], mediaTypes = keySet(mediaTypes_);
|
||||
|
||||
var atMediaFeatures = keySet([
|
||||
var mediaFeatures_ = [
|
||||
"width", "min-width", "max-width", "height", "min-height", "max-height",
|
||||
"device-width", "min-device-width", "max-device-width", "device-height",
|
||||
"min-device-height", "max-device-height", "aspect-ratio",
|
||||
@@ -328,9 +348,9 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
|
||||
"max-color", "color-index", "min-color-index", "max-color-index",
|
||||
"monochrome", "min-monochrome", "max-monochrome", "resolution",
|
||||
"min-resolution", "max-resolution", "scan", "grid"
|
||||
]);
|
||||
], mediaFeatures = keySet(mediaFeatures_);
|
||||
|
||||
var propertyKeywords = keySet([
|
||||
var propertyKeywords_ = [
|
||||
"align-content", "align-items", "align-self", "alignment-adjust",
|
||||
"alignment-baseline", "anchor-point", "animation", "animation-delay",
|
||||
"animation-direction", "animation-duration", "animation-iteration-count",
|
||||
@@ -418,9 +438,9 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
|
||||
"stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
|
||||
"baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
|
||||
"glyph-orientation-vertical", "kerning", "text-anchor", "writing-mode"
|
||||
]);
|
||||
], propertyKeywords = keySet(propertyKeywords_);
|
||||
|
||||
var colorKeywords = keySet([
|
||||
var colorKeywords_ = [
|
||||
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
|
||||
"bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
|
||||
"burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
|
||||
@@ -447,9 +467,9 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
|
||||
"slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
|
||||
"teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
|
||||
"whitesmoke", "yellow", "yellowgreen"
|
||||
]);
|
||||
], colorKeywords = keySet(colorKeywords_);
|
||||
|
||||
var valueKeywords = keySet([
|
||||
var valueKeywords_ = [
|
||||
"above", "absolute", "activeborder", "activecaption", "afar",
|
||||
"after-white-space", "ahead", "alias", "all", "all-scroll", "alternate",
|
||||
"always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
|
||||
@@ -532,7 +552,15 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
|
||||
"visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
|
||||
"window", "windowframe", "windowtext", "x-large", "x-small", "xor",
|
||||
"xx-large", "xx-small"
|
||||
]);
|
||||
], valueKeywords = keySet(valueKeywords_);
|
||||
|
||||
var fontProperties_ = [
|
||||
"font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
|
||||
"font-stretch", "font-weight", "font-style"
|
||||
], fontProperties = keySet(fontProperties_);
|
||||
|
||||
var allWords = mediaTypes_.concat(mediaFeatures_).concat(propertyKeywords_).concat(colorKeywords_).concat(valueKeywords_);
|
||||
CodeMirror.registerHelper("hintWords", "css", allWords);
|
||||
|
||||
function tokenCComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
@@ -546,62 +574,47 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
|
||||
return ["comment", "comment"];
|
||||
}
|
||||
|
||||
function tokenSGMLComment(stream, state) {
|
||||
if (stream.skipTo("-->")) {
|
||||
stream.match("-->");
|
||||
state.tokenize = null;
|
||||
} else {
|
||||
stream.skipToEnd();
|
||||
}
|
||||
return ["comment", "comment"];
|
||||
}
|
||||
|
||||
CodeMirror.defineMIME("text/css", {
|
||||
atMediaTypes: atMediaTypes,
|
||||
atMediaFeatures: atMediaFeatures,
|
||||
mediaTypes: mediaTypes,
|
||||
mediaFeatures: mediaFeatures,
|
||||
propertyKeywords: propertyKeywords,
|
||||
colorKeywords: colorKeywords,
|
||||
valueKeywords: valueKeywords,
|
||||
hooks: {
|
||||
fontProperties: fontProperties,
|
||||
tokenHooks: {
|
||||
"<": function(stream, state) {
|
||||
function tokenSGMLComment(stream, state) {
|
||||
var dashes = 0, ch;
|
||||
while ((ch = stream.next()) != null) {
|
||||
if (dashes >= 2 && ch == ">") {
|
||||
state.tokenize = null;
|
||||
break;
|
||||
}
|
||||
dashes = (ch == "-") ? dashes + 1 : 0;
|
||||
}
|
||||
return ["comment", "comment"];
|
||||
}
|
||||
if (stream.eat("!")) {
|
||||
state.tokenize = tokenSGMLComment;
|
||||
return tokenSGMLComment(stream, state);
|
||||
}
|
||||
if (!stream.match("!--")) return false;
|
||||
state.tokenize = tokenSGMLComment;
|
||||
return tokenSGMLComment(stream, state);
|
||||
},
|
||||
"/": function(stream, state) {
|
||||
if (stream.eat("*")) {
|
||||
state.tokenize = tokenCComment;
|
||||
return tokenCComment(stream, state);
|
||||
}
|
||||
return false;
|
||||
if (!stream.eat("*")) return false;
|
||||
state.tokenize = tokenCComment;
|
||||
return tokenCComment(stream, state);
|
||||
}
|
||||
},
|
||||
name: "css"
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-scss", {
|
||||
atMediaTypes: atMediaTypes,
|
||||
atMediaFeatures: atMediaFeatures,
|
||||
mediaTypes: mediaTypes,
|
||||
mediaFeatures: mediaFeatures,
|
||||
propertyKeywords: propertyKeywords,
|
||||
colorKeywords: colorKeywords,
|
||||
valueKeywords: valueKeywords,
|
||||
fontProperties: fontProperties,
|
||||
allowNested: true,
|
||||
hooks: {
|
||||
":": function(stream) {
|
||||
if (stream.match(/\s*{/)) {
|
||||
return [null, "{"];
|
||||
}
|
||||
return false;
|
||||
},
|
||||
"$": function(stream) {
|
||||
stream.match(/^[\w-]+/);
|
||||
if (stream.peek() == ":") {
|
||||
return ["variable", "variable-definition"];
|
||||
}
|
||||
return ["variable", "variable"];
|
||||
},
|
||||
tokenHooks: {
|
||||
"/": function(stream, state) {
|
||||
if (stream.eat("/")) {
|
||||
stream.skipToEnd();
|
||||
@@ -613,15 +626,58 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
|
||||
return ["operator", "operator"];
|
||||
}
|
||||
},
|
||||
":": function(stream) {
|
||||
if (stream.match(/\s*{/))
|
||||
return [null, "{"];
|
||||
return false;
|
||||
},
|
||||
"$": function(stream) {
|
||||
stream.match(/^[\w-]+/);
|
||||
if (stream.match(/^\s*:/, false))
|
||||
return ["variable-2", "variable-definition"];
|
||||
return ["variable-2", "variable"];
|
||||
},
|
||||
"#": function(stream) {
|
||||
if (stream.eat("{")) {
|
||||
return ["operator", "interpolation"];
|
||||
} else {
|
||||
stream.eatWhile(/[\w\\\-]/);
|
||||
return ["atom", "hash"];
|
||||
}
|
||||
if (!stream.eat("{")) return false;
|
||||
return [null, "interpolation"];
|
||||
}
|
||||
},
|
||||
name: "css"
|
||||
name: "css",
|
||||
helperType: "scss"
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-less", {
|
||||
mediaTypes: mediaTypes,
|
||||
mediaFeatures: mediaFeatures,
|
||||
propertyKeywords: propertyKeywords,
|
||||
colorKeywords: colorKeywords,
|
||||
valueKeywords: valueKeywords,
|
||||
fontProperties: fontProperties,
|
||||
allowNested: true,
|
||||
tokenHooks: {
|
||||
"/": function(stream, state) {
|
||||
if (stream.eat("/")) {
|
||||
stream.skipToEnd();
|
||||
return ["comment", "comment"];
|
||||
} else if (stream.eat("*")) {
|
||||
state.tokenize = tokenCComment;
|
||||
return tokenCComment(stream, state);
|
||||
} else {
|
||||
return ["operator", "operator"];
|
||||
}
|
||||
},
|
||||
"@": function(stream) {
|
||||
if (stream.match(/^(charset|document|font-face|import|keyframes|media|namespace|page|supports)\b/, false)) return false;
|
||||
stream.eatWhile(/[\w\\\-]/);
|
||||
if (stream.match(/^\s*:/, false))
|
||||
return ["variable-2", "variable-definition"];
|
||||
return ["variable-2", "variable"];
|
||||
},
|
||||
"&": function() {
|
||||
return ["atom", "atom"];
|
||||
}
|
||||
},
|
||||
name: "css",
|
||||
helperType: "less"
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: CSS mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="css.js"></script>
|
||||
<style>.CodeMirror {background: #f8f8f8;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">CSS</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>CSS mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
/* Some example CSS */
|
||||
|
||||
@import url("something.css");
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 3em 6em;
|
||||
font-family: tahoma, arial, sans-serif;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
#navigation a {
|
||||
font-weight: bold;
|
||||
text-decoration: none !important;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 2.5em;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.7em;
|
||||
}
|
||||
|
||||
h1:before, h2:before {
|
||||
content: "::";
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: courier, monospace;
|
||||
font-size: 80%;
|
||||
color: #418A8A;
|
||||
}
|
||||
</textarea></form>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/css</code>.</p>
|
||||
|
||||
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#css_*">normal</a>, <a href="../../test/index.html#verbose,css_*">verbose</a>.</p>
|
||||
|
||||
</article>
|
||||
@@ -150,7 +150,7 @@ code {
|
||||
});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/scss</code>.</p>
|
||||
<p>The SCSS mode is a sub-mode of the <a href="index.html">CSS mode</a> (defined in <code>css.js</code>.</p>
|
||||
|
||||
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#scss_*">normal</a>, <a href="../../test/index.html#verbose,scss_*">verbose</a>.</p>
|
||||
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
(function() {
|
||||
var mode = CodeMirror.getMode({tabSize: 4}, "text/x-scss");
|
||||
var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-scss");
|
||||
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); }
|
||||
|
||||
MT('url_with_quotation',
|
||||
"[tag foo] { [property background][operator :][string-2 url]([string test.jpg]) }");
|
||||
"[tag foo] { [property background]:[atom url]([string test.jpg]) }");
|
||||
|
||||
MT('url_with_double_quotes',
|
||||
"[tag foo] { [property background][operator :][string-2 url]([string \"test.jpg\"]) }");
|
||||
"[tag foo] { [property background]:[atom url]([string \"test.jpg\"]) }");
|
||||
|
||||
MT('url_with_single_quotes',
|
||||
"[tag foo] { [property background][operator :][string-2 url]([string \'test.jpg\']) }");
|
||||
"[tag foo] { [property background]:[atom url]([string \'test.jpg\']) }");
|
||||
|
||||
MT('string',
|
||||
"[def @import] [string \"compass/css3\"]");
|
||||
|
||||
MT('important_keyword',
|
||||
"[tag foo] { [property background][operator :][string-2 url]([string \'test.jpg\']) [keyword !important] }");
|
||||
"[tag foo] { [property background]:[atom url]([string \'test.jpg\']) [keyword !important] }");
|
||||
|
||||
MT('variable',
|
||||
"[variable-2 $blue][operator :][atom #333]");
|
||||
"[variable-2 $blue]:[atom #333]");
|
||||
|
||||
MT('variable_as_attribute',
|
||||
"[tag foo] { [property color][operator :][variable-2 $blue] }");
|
||||
"[tag foo] { [property color]:[variable-2 $blue] }");
|
||||
|
||||
MT('numbers',
|
||||
"[tag foo] { [property padding][operator :][number 10px] [number 10] [number 10em] [number 8in] }");
|
||||
"[tag foo] { [property padding]:[number 10px] [number 10] [number 10em] [number 8in] }");
|
||||
|
||||
MT('number_percentage',
|
||||
"[tag foo] { [property width][operator :][number 80%] }");
|
||||
"[tag foo] { [property width]:[number 80%] }");
|
||||
|
||||
MT('selector',
|
||||
"[builtin #hello][qualifier .world]{}");
|
||||
@@ -39,42 +39,69 @@
|
||||
"[comment /*foobar*/]");
|
||||
|
||||
MT('attribute_with_hyphen',
|
||||
"[tag foo] { [property font-size][operator :][number 10px] }");
|
||||
"[tag foo] { [property font-size]:[number 10px] }");
|
||||
|
||||
MT('string_after_attribute',
|
||||
"[tag foo] { [property content][operator :][string \"::\"] }");
|
||||
"[tag foo] { [property content]:[string \"::\"] }");
|
||||
|
||||
MT('directives',
|
||||
"[def @include] [qualifier .mixin]");
|
||||
|
||||
MT('basic_structure',
|
||||
"[tag p] { [property background][operator :][keyword red]; }");
|
||||
"[tag p] { [property background]:[keyword red]; }");
|
||||
|
||||
MT('nested_structure',
|
||||
"[tag p] { [tag a] { [property color][operator :][keyword red]; } }");
|
||||
"[tag p] { [tag a] { [property color]:[keyword red]; } }");
|
||||
|
||||
MT('mixin',
|
||||
"[def @mixin] [tag table-base] {}");
|
||||
|
||||
MT('number_without_semicolon',
|
||||
"[tag p] {[property width][operator :][number 12]}",
|
||||
"[tag a] {[property color][operator :][keyword red];}");
|
||||
"[tag p] {[property width]:[number 12]}",
|
||||
"[tag a] {[property color]:[keyword red];}");
|
||||
|
||||
MT('atom_in_nested_block',
|
||||
"[tag p] { [tag a] { [property color][operator :][atom #000]; } }");
|
||||
"[tag p] { [tag a] { [property color]:[atom #000]; } }");
|
||||
|
||||
MT('interpolation_in_property',
|
||||
"[tag foo] { [operator #{][variable-2 $hello][operator }:][number 2]; }");
|
||||
"[tag foo] { #{[variable-2 $hello]}:[number 2]; }");
|
||||
|
||||
MT('interpolation_in_selector',
|
||||
"[tag foo][operator #{][variable-2 $hello][operator }] { [property color][operator :][atom #000]; }");
|
||||
"[tag foo]#{[variable-2 $hello]} { [property color]:[atom #000]; }");
|
||||
|
||||
MT('interpolation_error',
|
||||
"[tag foo][operator #{][error foo][operator }] { [property color][operator :][atom #000]; }");
|
||||
"[tag foo]#{[error foo]} { [property color]:[atom #000]; }");
|
||||
|
||||
MT("divide_operator",
|
||||
"[tag foo] { [property width][operator :][number 4] [operator /] [number 2] }");
|
||||
"[tag foo] { [property width]:[number 4] [operator /] [number 2] }");
|
||||
|
||||
MT('nested_structure_with_id_selector',
|
||||
"[tag p] { [builtin #hello] { [property color][operator :][keyword red]; } }");
|
||||
"[tag p] { [builtin #hello] { [property color]:[keyword red]; } }");
|
||||
|
||||
MT('indent_mixin',
|
||||
"[def @mixin] [tag container] (",
|
||||
" [variable-2 $a]: [number 10],",
|
||||
" [variable-2 $b]: [number 10])",
|
||||
"{}");
|
||||
|
||||
MT('indent_nested',
|
||||
"[tag foo] {",
|
||||
" [tag bar] {",
|
||||
" }",
|
||||
"}");
|
||||
|
||||
MT('indent_parentheses',
|
||||
"[tag foo] {",
|
||||
" [property color]: [variable darken]([variable-2 $blue],",
|
||||
" [number 9%]);",
|
||||
"}");
|
||||
|
||||
MT('indent_vardef',
|
||||
"[variable-2 $name]:",
|
||||
" [string 'val'];",
|
||||
"[tag tag] {",
|
||||
" [tag inner] {",
|
||||
" [property margin]: [number 3px];",
|
||||
" }",
|
||||
"}");
|
||||
})();
|
||||
|
||||
@@ -1,67 +1,19 @@
|
||||
(function() {
|
||||
var mode = CodeMirror.getMode({tabSize: 4}, "css");
|
||||
var mode = CodeMirror.getMode({indentUnit: 2}, "css");
|
||||
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
|
||||
|
||||
// Requires at least one media query
|
||||
MT("atMediaEmpty",
|
||||
"[def @media] [error {] }");
|
||||
|
||||
MT("atMediaMultiple",
|
||||
"[def @media] [keyword not] [attribute screen] [operator and] ([property color]), [keyword not] [attribute print] [operator and] ([property color]) { }");
|
||||
|
||||
MT("atMediaCheckStack",
|
||||
"[def @media] [attribute screen] { } [tag foo] { }");
|
||||
|
||||
MT("atMediaCheckStack",
|
||||
"[def @media] [attribute screen] ([property color]) { } [tag foo] { }");
|
||||
|
||||
MT("atMediaPropertyOnly",
|
||||
"[def @media] ([property color]) { } [tag foo] { }");
|
||||
|
||||
MT("atMediaCheckStackInvalidAttribute",
|
||||
"[def @media] [attribute&error foobarhello] { [tag foo] { } }");
|
||||
|
||||
MT("atMediaCheckStackInvalidAttribute",
|
||||
"[def @media] [attribute&error foobarhello] { } [tag foo] { }");
|
||||
|
||||
// Error, because "and" is only allowed immediately preceding a media expression
|
||||
MT("atMediaInvalidAttribute",
|
||||
"[def @media] [attribute&error foobarhello] { }");
|
||||
|
||||
// Error, because "and" is only allowed immediately preceding a media expression
|
||||
MT("atMediaInvalidAnd",
|
||||
"[def @media] [error and] [attribute screen] { }");
|
||||
|
||||
// Error, because "not" is only allowed as the first item in each media query
|
||||
MT("atMediaInvalidNot",
|
||||
"[def @media] [attribute screen] [error not] ([error not]) { }");
|
||||
|
||||
// Error, because "only" is only allowed as the first item in each media query
|
||||
MT("atMediaInvalidOnly",
|
||||
"[def @media] [attribute screen] [error only] ([error only]) { }");
|
||||
|
||||
// Error, because "foobarhello" is neither a known type or property, but
|
||||
// property was expected (after "and"), and it should be in parenthese.
|
||||
MT("atMediaUnknownType",
|
||||
"[def @media] [attribute screen] [operator and] [error foobarhello] { }");
|
||||
|
||||
// Error, because "color" is not a known type, but is a known property, and
|
||||
// should be in parentheses.
|
||||
MT("atMediaInvalidType",
|
||||
"[def @media] [attribute screen] [operator and] [error color] { }");
|
||||
|
||||
// Error, because "print" is not a known property, but is a known type,
|
||||
// and should not be in parenthese.
|
||||
MT("atMediaInvalidProperty",
|
||||
"[def @media] [attribute screen] [operator and] ([error print]) { }");
|
||||
"[def @media] [attribute screen] [keyword and] [error foobarhello] { }");
|
||||
|
||||
// Soft error, because "foobarhello" is not a known property or type.
|
||||
MT("atMediaUnknownProperty",
|
||||
"[def @media] [attribute screen] [operator and] ([property&error foobarhello]) { }");
|
||||
"[def @media] [attribute screen] [keyword and] ([error foobarhello]) { }");
|
||||
|
||||
// Make sure nesting works with media queries
|
||||
MT("atMediaMaxWidthNested",
|
||||
"[def @media] [attribute screen] [operator and] ([property max-width][operator :] [number 25px]) { [tag foo] { } }");
|
||||
"[def @media] [attribute screen] [keyword and] ([property max-width]: [number 25px]) { [tag foo] { } }");
|
||||
|
||||
MT("tagSelector",
|
||||
"[tag foo] { }");
|
||||
@@ -73,54 +25,95 @@
|
||||
"[builtin #foo] { [error #foo] }");
|
||||
|
||||
MT("tagSelectorUnclosed",
|
||||
"[tag foo] { [property margin][operator :] [number 0] } [tag bar] { }");
|
||||
"[tag foo] { [property margin]: [number 0] } [tag bar] { }");
|
||||
|
||||
MT("tagStringNoQuotes",
|
||||
"[tag foo] { [property font-family][operator :] [variable-2 hello] [variable-2 world]; }");
|
||||
"[tag foo] { [property font-family]: [variable hello] [variable world]; }");
|
||||
|
||||
MT("tagStringDouble",
|
||||
"[tag foo] { [property font-family][operator :] [string \"hello world\"]; }");
|
||||
"[tag foo] { [property font-family]: [string \"hello world\"]; }");
|
||||
|
||||
MT("tagStringSingle",
|
||||
"[tag foo] { [property font-family][operator :] [string 'hello world']; }");
|
||||
"[tag foo] { [property font-family]: [string 'hello world']; }");
|
||||
|
||||
MT("tagColorKeyword",
|
||||
"[tag foo] {" +
|
||||
"[property color][operator :] [keyword black];" +
|
||||
"[property color][operator :] [keyword navy];" +
|
||||
"[property color][operator :] [keyword yellow];" +
|
||||
"}");
|
||||
"[tag foo] {",
|
||||
" [property color]: [keyword black];",
|
||||
" [property color]: [keyword navy];",
|
||||
" [property color]: [keyword yellow];",
|
||||
"}");
|
||||
|
||||
MT("tagColorHex3",
|
||||
"[tag foo] { [property background][operator :] [atom #fff]; }");
|
||||
"[tag foo] { [property background]: [atom #fff]; }");
|
||||
|
||||
MT("tagColorHex6",
|
||||
"[tag foo] { [property background][operator :] [atom #ffffff]; }");
|
||||
"[tag foo] { [property background]: [atom #ffffff]; }");
|
||||
|
||||
MT("tagColorHex4",
|
||||
"[tag foo] { [property background][operator :] [atom&error #ffff]; }");
|
||||
"[tag foo] { [property background]: [atom&error #ffff]; }");
|
||||
|
||||
MT("tagColorHexInvalid",
|
||||
"[tag foo] { [property background][operator :] [atom&error #ffg]; }");
|
||||
"[tag foo] { [property background]: [atom&error #ffg]; }");
|
||||
|
||||
MT("tagNegativeNumber",
|
||||
"[tag foo] { [property margin][operator :] [number -5px]; }");
|
||||
"[tag foo] { [property margin]: [number -5px]; }");
|
||||
|
||||
MT("tagPositiveNumber",
|
||||
"[tag foo] { [property padding][operator :] [number 5px]; }");
|
||||
"[tag foo] { [property padding]: [number 5px]; }");
|
||||
|
||||
MT("tagVendor",
|
||||
"[tag foo] { [meta -foo-][property box-sizing][operator :] [meta -foo-][string-2 border-box]; }");
|
||||
"[tag foo] { [meta -foo-][property box-sizing]: [meta -foo-][atom border-box]; }");
|
||||
|
||||
MT("tagBogusProperty",
|
||||
"[tag foo] { [property&error barhelloworld][operator :] [number 0]; }");
|
||||
"[tag foo] { [property&error barhelloworld]: [number 0]; }");
|
||||
|
||||
MT("tagTwoProperties",
|
||||
"[tag foo] { [property margin][operator :] [number 0]; [property padding][operator :] [number 0]; }");
|
||||
"[tag foo] { [property margin]: [number 0]; [property padding]: [number 0]; }");
|
||||
|
||||
MT("tagTwoPropertiesURL",
|
||||
"[tag foo] { [property background][operator :] [string-2 url]([string //example.com/foo.png]); [property padding][operator :] [number 0]; }");
|
||||
"[tag foo] { [property background]: [atom url]([string //example.com/foo.png]); [property padding]: [number 0]; }");
|
||||
|
||||
MT("commentSGML",
|
||||
"[comment <!--comment-->]");
|
||||
|
||||
MT("commentSGML2",
|
||||
"[comment <!--comment]",
|
||||
"[comment -->] [tag div] {}");
|
||||
|
||||
MT("indent_tagSelector",
|
||||
"[tag strong], [tag em] {",
|
||||
" [property background]: [atom rgba](",
|
||||
" [number 255], [number 255], [number 0], [number .2]",
|
||||
" );",
|
||||
"}");
|
||||
|
||||
MT("indent_atMedia",
|
||||
"[def @media] {",
|
||||
" [tag foo] {",
|
||||
" [property color]:",
|
||||
" [keyword yellow];",
|
||||
" }",
|
||||
"}");
|
||||
|
||||
MT("indent_comma",
|
||||
"[tag foo] {",
|
||||
" [property font-family]: [variable verdana],",
|
||||
" [atom sans-serif];",
|
||||
"}");
|
||||
|
||||
MT("indent_parentheses",
|
||||
"[tag foo]:[variable-3 before] {",
|
||||
" [property background]: [atom url](",
|
||||
"[string blahblah]",
|
||||
"[string etc]",
|
||||
"[string ]) [keyword !important];",
|
||||
"}");
|
||||
|
||||
MT("font_face",
|
||||
"[def @font-face] {",
|
||||
" [property font-family]: [string 'myfont'];",
|
||||
" [error nonsense]: [string 'abc'];",
|
||||
" [property src]: [atom url]([string http://blah]),",
|
||||
" [atom url]([string http://foo]);",
|
||||
"}");
|
||||
})();
|
||||
|
||||
205
applications/admin/static/codemirror/mode/d/d.js
vendored
205
applications/admin/static/codemirror/mode/d/d.js
vendored
@@ -1,205 +0,0 @@
|
||||
CodeMirror.defineMode("d", function(config, parserConfig) {
|
||||
var indentUnit = config.indentUnit,
|
||||
statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
|
||||
keywords = parserConfig.keywords || {},
|
||||
builtin = parserConfig.builtin || {},
|
||||
blockKeywords = parserConfig.blockKeywords || {},
|
||||
atoms = parserConfig.atoms || {},
|
||||
hooks = parserConfig.hooks || {},
|
||||
multiLineStrings = parserConfig.multiLineStrings;
|
||||
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
|
||||
|
||||
var curPunc;
|
||||
|
||||
function tokenBase(stream, state) {
|
||||
var ch = stream.next();
|
||||
if (hooks[ch]) {
|
||||
var result = hooks[ch](stream, state);
|
||||
if (result !== false) return result;
|
||||
}
|
||||
if (ch == '"' || ch == "'" || ch == "`") {
|
||||
state.tokenize = tokenString(ch);
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
|
||||
curPunc = ch;
|
||||
return null;
|
||||
}
|
||||
if (/\d/.test(ch)) {
|
||||
stream.eatWhile(/[\w\.]/);
|
||||
return "number";
|
||||
}
|
||||
if (ch == "/") {
|
||||
if (stream.eat("+")) {
|
||||
state.tokenize = tokenComment;
|
||||
return tokenNestedComment(stream, state);
|
||||
}
|
||||
if (stream.eat("*")) {
|
||||
state.tokenize = tokenComment;
|
||||
return tokenComment(stream, state);
|
||||
}
|
||||
if (stream.eat("/")) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
}
|
||||
if (isOperatorChar.test(ch)) {
|
||||
stream.eatWhile(isOperatorChar);
|
||||
return "operator";
|
||||
}
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
var cur = stream.current();
|
||||
if (keywords.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "keyword";
|
||||
}
|
||||
if (builtin.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "builtin";
|
||||
}
|
||||
if (atoms.propertyIsEnumerable(cur)) return "atom";
|
||||
return "variable";
|
||||
}
|
||||
|
||||
function tokenString(quote) {
|
||||
return function(stream, state) {
|
||||
var escaped = false, next, end = false;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == quote && !escaped) {end = true; break;}
|
||||
escaped = !escaped && next == "\\";
|
||||
}
|
||||
if (end || !(escaped || multiLineStrings))
|
||||
state.tokenize = null;
|
||||
return "string";
|
||||
};
|
||||
}
|
||||
|
||||
function tokenComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
while (ch = stream.next()) {
|
||||
if (ch == "/" && maybeEnd) {
|
||||
state.tokenize = null;
|
||||
break;
|
||||
}
|
||||
maybeEnd = (ch == "*");
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function tokenNestedComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
while (ch = stream.next()) {
|
||||
if (ch == "/" && maybeEnd) {
|
||||
state.tokenize = null;
|
||||
break;
|
||||
}
|
||||
maybeEnd = (ch == "+");
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function Context(indented, column, type, align, prev) {
|
||||
this.indented = indented;
|
||||
this.column = column;
|
||||
this.type = type;
|
||||
this.align = align;
|
||||
this.prev = prev;
|
||||
}
|
||||
function pushContext(state, col, type) {
|
||||
var indent = state.indented;
|
||||
if (state.context && state.context.type == "statement")
|
||||
indent = state.context.indented;
|
||||
return state.context = new Context(indent, col, type, null, state.context);
|
||||
}
|
||||
function popContext(state) {
|
||||
var t = state.context.type;
|
||||
if (t == ")" || t == "]" || t == "}")
|
||||
state.indented = state.context.indented;
|
||||
return state.context = state.context.prev;
|
||||
}
|
||||
|
||||
// Interface
|
||||
|
||||
return {
|
||||
startState: function(basecolumn) {
|
||||
return {
|
||||
tokenize: null,
|
||||
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
|
||||
indented: 0,
|
||||
startOfLine: true
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
var ctx = state.context;
|
||||
if (stream.sol()) {
|
||||
if (ctx.align == null) ctx.align = false;
|
||||
state.indented = stream.indentation();
|
||||
state.startOfLine = true;
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
curPunc = null;
|
||||
var style = (state.tokenize || tokenBase)(stream, state);
|
||||
if (style == "comment" || style == "meta") return style;
|
||||
if (ctx.align == null) ctx.align = true;
|
||||
|
||||
if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
|
||||
else if (curPunc == "{") pushContext(state, stream.column(), "}");
|
||||
else if (curPunc == "[") pushContext(state, stream.column(), "]");
|
||||
else if (curPunc == "(") pushContext(state, stream.column(), ")");
|
||||
else if (curPunc == "}") {
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
if (ctx.type == "}") ctx = popContext(state);
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
}
|
||||
else if (curPunc == ctx.type) popContext(state);
|
||||
else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
|
||||
pushContext(state, stream.column(), "statement");
|
||||
state.startOfLine = false;
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function(state, textAfter) {
|
||||
if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
|
||||
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
|
||||
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
|
||||
var closing = firstChar == ctx.type;
|
||||
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
|
||||
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
|
||||
else return ctx.indented + (closing ? 0 : indentUnit);
|
||||
},
|
||||
|
||||
electricChars: "{}"
|
||||
};
|
||||
});
|
||||
|
||||
(function() {
|
||||
function words(str) {
|
||||
var obj = {}, words = str.split(" ");
|
||||
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
|
||||
return obj;
|
||||
}
|
||||
|
||||
var blockKeywords = "body catch class do else enum for foreach foreach_reverse if in interface mixin " +
|
||||
"out scope struct switch try union unittest version while with";
|
||||
|
||||
CodeMirror.defineMIME("text/x-d", {
|
||||
name: "d",
|
||||
keywords: words("abstract alias align asm assert auto break case cast cdouble cent cfloat const continue " +
|
||||
"debug default delegate delete deprecated export extern final finally function goto immutable " +
|
||||
"import inout invariant is lazy macro module new nothrow override package pragma private " +
|
||||
"protected public pure ref return shared short static super synchronized template this " +
|
||||
"throw typedef typeid typeof volatile __FILE__ __LINE__ __gshared __traits __vector __parameters " +
|
||||
blockKeywords),
|
||||
blockKeywords: words(blockKeywords),
|
||||
builtin: words("bool byte char creal dchar double float idouble ifloat int ireal long real short ubyte " +
|
||||
"ucent uint ulong ushort wchar wstring void size_t sizediff_t"),
|
||||
atoms: words("exit failure success true false null"),
|
||||
hooks: {
|
||||
"@": function(stream, _state) {
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
return "meta";
|
||||
}
|
||||
}
|
||||
});
|
||||
}());
|
||||
@@ -1,273 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: D mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/edit/matchbrackets.js"></script>
|
||||
<script src="d.js"></script>
|
||||
<style>.CodeMirror {border: 2px inset #dee;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">D</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>D mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
/* D demo code // copied from phobos/sd/metastrings.d */
|
||||
// Written in the D programming language.
|
||||
|
||||
/**
|
||||
Templates with which to do compile-time manipulation of strings.
|
||||
|
||||
Macros:
|
||||
WIKI = Phobos/StdMetastrings
|
||||
|
||||
Copyright: Copyright Digital Mars 2007 - 2009.
|
||||
License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
|
||||
Authors: $(WEB digitalmars.com, Walter Bright),
|
||||
Don Clugston
|
||||
Source: $(PHOBOSSRC std/_metastrings.d)
|
||||
*/
|
||||
/*
|
||||
Copyright Digital Mars 2007 - 2009.
|
||||
Distributed under the Boost Software License, Version 1.0.
|
||||
(See accompanying file LICENSE_1_0.txt or copy at
|
||||
http://www.boost.org/LICENSE_1_0.txt)
|
||||
*/
|
||||
module std.metastrings;
|
||||
|
||||
/**
|
||||
Formats constants into a string at compile time. Analogous to $(XREF
|
||||
string,format).
|
||||
|
||||
Parameters:
|
||||
|
||||
A = tuple of constants, which can be strings, characters, or integral
|
||||
values.
|
||||
|
||||
Formats:
|
||||
* The formats supported are %s for strings, and %%
|
||||
* for the % character.
|
||||
Example:
|
||||
---
|
||||
import std.metastrings;
|
||||
import std.stdio;
|
||||
|
||||
void main()
|
||||
{
|
||||
string s = Format!("Arg %s = %s", "foo", 27);
|
||||
writefln(s); // "Arg foo = 27"
|
||||
}
|
||||
* ---
|
||||
*/
|
||||
|
||||
template Format(A...)
|
||||
{
|
||||
static if (A.length == 0)
|
||||
enum Format = "";
|
||||
else static if (is(typeof(A[0]) : const(char)[]))
|
||||
enum Format = FormatString!(A[0], A[1..$]);
|
||||
else
|
||||
enum Format = toStringNow!(A[0]) ~ Format!(A[1..$]);
|
||||
}
|
||||
|
||||
template FormatString(const(char)[] F, A...)
|
||||
{
|
||||
static if (F.length == 0)
|
||||
enum FormatString = Format!(A);
|
||||
else static if (F.length == 1)
|
||||
enum FormatString = F[0] ~ Format!(A);
|
||||
else static if (F[0..2] == "%s")
|
||||
enum FormatString
|
||||
= toStringNow!(A[0]) ~ FormatString!(F[2..$],A[1..$]);
|
||||
else static if (F[0..2] == "%%")
|
||||
enum FormatString = "%" ~ FormatString!(F[2..$],A);
|
||||
else
|
||||
{
|
||||
static assert(F[0] != '%', "unrecognized format %" ~ F[1]);
|
||||
enum FormatString = F[0] ~ FormatString!(F[1..$],A);
|
||||
}
|
||||
}
|
||||
|
||||
unittest
|
||||
{
|
||||
auto s = Format!("hel%slo", "world", -138, 'c', true);
|
||||
assert(s == "helworldlo-138ctrue", "[" ~ s ~ "]");
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert constant argument to a string.
|
||||
*/
|
||||
|
||||
template toStringNow(ulong v)
|
||||
{
|
||||
static if (v < 10)
|
||||
enum toStringNow = "" ~ cast(char)(v + '0');
|
||||
else
|
||||
enum toStringNow = toStringNow!(v / 10) ~ toStringNow!(v % 10);
|
||||
}
|
||||
|
||||
unittest
|
||||
{
|
||||
static assert(toStringNow!(1uL << 62) == "4611686018427387904");
|
||||
}
|
||||
|
||||
/// ditto
|
||||
template toStringNow(long v)
|
||||
{
|
||||
static if (v < 0)
|
||||
enum toStringNow = "-" ~ toStringNow!(cast(ulong) -v);
|
||||
else
|
||||
enum toStringNow = toStringNow!(cast(ulong) v);
|
||||
}
|
||||
|
||||
unittest
|
||||
{
|
||||
static assert(toStringNow!(0x100000000) == "4294967296");
|
||||
static assert(toStringNow!(-138L) == "-138");
|
||||
}
|
||||
|
||||
/// ditto
|
||||
template toStringNow(uint U)
|
||||
{
|
||||
enum toStringNow = toStringNow!(cast(ulong)U);
|
||||
}
|
||||
|
||||
/// ditto
|
||||
template toStringNow(int I)
|
||||
{
|
||||
enum toStringNow = toStringNow!(cast(long)I);
|
||||
}
|
||||
|
||||
/// ditto
|
||||
template toStringNow(bool B)
|
||||
{
|
||||
enum toStringNow = B ? "true" : "false";
|
||||
}
|
||||
|
||||
/// ditto
|
||||
template toStringNow(string S)
|
||||
{
|
||||
enum toStringNow = S;
|
||||
}
|
||||
|
||||
/// ditto
|
||||
template toStringNow(char C)
|
||||
{
|
||||
enum toStringNow = "" ~ C;
|
||||
}
|
||||
|
||||
|
||||
/********
|
||||
* Parse unsigned integer literal from the start of string s.
|
||||
* returns:
|
||||
* .value = the integer literal as a string,
|
||||
* .rest = the string following the integer literal
|
||||
* Otherwise:
|
||||
* .value = null,
|
||||
* .rest = s
|
||||
*/
|
||||
|
||||
template parseUinteger(const(char)[] s)
|
||||
{
|
||||
static if (s.length == 0)
|
||||
{
|
||||
enum value = "";
|
||||
enum rest = "";
|
||||
}
|
||||
else static if (s[0] >= '0' && s[0] <= '9')
|
||||
{
|
||||
enum value = s[0] ~ parseUinteger!(s[1..$]).value;
|
||||
enum rest = parseUinteger!(s[1..$]).rest;
|
||||
}
|
||||
else
|
||||
{
|
||||
enum value = "";
|
||||
enum rest = s;
|
||||
}
|
||||
}
|
||||
|
||||
/********
|
||||
Parse integer literal optionally preceded by $(D '-') from the start
|
||||
of string $(D s).
|
||||
|
||||
Returns:
|
||||
.value = the integer literal as a string,
|
||||
.rest = the string following the integer literal
|
||||
|
||||
Otherwise:
|
||||
.value = null,
|
||||
.rest = s
|
||||
*/
|
||||
|
||||
template parseInteger(const(char)[] s)
|
||||
{
|
||||
static if (s.length == 0)
|
||||
{
|
||||
enum value = "";
|
||||
enum rest = "";
|
||||
}
|
||||
else static if (s[0] >= '0' && s[0] <= '9')
|
||||
{
|
||||
enum value = s[0] ~ parseUinteger!(s[1..$]).value;
|
||||
enum rest = parseUinteger!(s[1..$]).rest;
|
||||
}
|
||||
else static if (s.length >= 2 &&
|
||||
s[0] == '-' && s[1] >= '0' && s[1] <= '9')
|
||||
{
|
||||
enum value = s[0..2] ~ parseUinteger!(s[2..$]).value;
|
||||
enum rest = parseUinteger!(s[2..$]).rest;
|
||||
}
|
||||
else
|
||||
{
|
||||
enum value = "";
|
||||
enum rest = s;
|
||||
}
|
||||
}
|
||||
|
||||
unittest
|
||||
{
|
||||
assert(parseUinteger!("1234abc").value == "1234");
|
||||
assert(parseUinteger!("1234abc").rest == "abc");
|
||||
assert(parseInteger!("-1234abc").value == "-1234");
|
||||
assert(parseInteger!("-1234abc").rest == "abc");
|
||||
}
|
||||
|
||||
/**
|
||||
Deprecated aliases held for backward compatibility.
|
||||
*/
|
||||
deprecated alias toStringNow ToString;
|
||||
/// Ditto
|
||||
deprecated alias parseUinteger ParseUinteger;
|
||||
/// Ditto
|
||||
deprecated alias parseUinteger ParseInteger;
|
||||
|
||||
</textarea></form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
indentUnit: 4,
|
||||
mode: "text/x-d"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p>Simple mode that handle D-Syntax (<a href="http://www.dlang.org">DLang Homepage</a>).</p>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-d</code>
|
||||
.</p>
|
||||
</article>
|
||||
@@ -1,32 +0,0 @@
|
||||
CodeMirror.defineMode("diff", function() {
|
||||
|
||||
var TOKEN_NAMES = {
|
||||
'+': 'positive',
|
||||
'-': 'negative',
|
||||
'@': 'meta'
|
||||
};
|
||||
|
||||
return {
|
||||
token: function(stream) {
|
||||
var tw_pos = stream.string.search(/[\t ]+?$/);
|
||||
|
||||
if (!stream.sol() || tw_pos === 0) {
|
||||
stream.skipToEnd();
|
||||
return ("error " + (
|
||||
TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, '');
|
||||
}
|
||||
|
||||
var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd();
|
||||
|
||||
if (tw_pos === -1) {
|
||||
stream.skipToEnd();
|
||||
} else {
|
||||
stream.pos = tw_pos;
|
||||
}
|
||||
|
||||
return token_name;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-diff", "diff");
|
||||
@@ -1,117 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Diff mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="diff.js"></script>
|
||||
<style>
|
||||
.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}
|
||||
span.cm-meta {color: #a0b !important;}
|
||||
span.cm-error { background-color: black; opacity: 0.4;}
|
||||
span.cm-error.cm-string { background-color: red; }
|
||||
span.cm-error.cm-tag { background-color: #2b2; }
|
||||
</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Diff</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Diff mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
diff --git a/index.html b/index.html
|
||||
index c1d9156..7764744 100644
|
||||
--- a/index.html
|
||||
+++ b/index.html
|
||||
@@ -95,7 +95,8 @@ StringStream.prototype = {
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
- autoMatchBrackets: true
|
||||
+ autoMatchBrackets: true,
|
||||
+ onGutterClick: function(x){console.log(x);}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
diff --git a/lib/codemirror.js b/lib/codemirror.js
|
||||
index 04646a9..9a39cc7 100644
|
||||
--- a/lib/codemirror.js
|
||||
+++ b/lib/codemirror.js
|
||||
@@ -399,10 +399,16 @@ var CodeMirror = (function() {
|
||||
}
|
||||
|
||||
function onMouseDown(e) {
|
||||
- var start = posFromMouse(e), last = start;
|
||||
+ var start = posFromMouse(e), last = start, target = e.target();
|
||||
if (!start) return;
|
||||
setCursor(start.line, start.ch, false);
|
||||
if (e.button() != 1) return;
|
||||
+ if (target.parentNode == gutter) {
|
||||
+ if (options.onGutterClick)
|
||||
+ options.onGutterClick(indexOf(gutter.childNodes, target) + showingFrom);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
if (!focused) onFocus();
|
||||
|
||||
e.stop();
|
||||
@@ -808,7 +814,7 @@ var CodeMirror = (function() {
|
||||
for (var i = showingFrom; i < showingTo; ++i) {
|
||||
var marker = lines[i].gutterMarker;
|
||||
if (marker) html.push('<div class="' + marker.style + '">' + htmlEscape(marker.text) + '</div>');
|
||||
- else html.push("<div>" + (options.lineNumbers ? i + 1 : "\u00a0") + "</div>");
|
||||
+ else html.push("<div>" + (options.lineNumbers ? i + options.firstLineNumber : "\u00a0") + "</div>");
|
||||
}
|
||||
gutter.style.display = "none"; // TODO test whether this actually helps
|
||||
gutter.innerHTML = html.join("");
|
||||
@@ -1371,10 +1377,8 @@ var CodeMirror = (function() {
|
||||
if (option == "parser") setParser(value);
|
||||
else if (option === "lineNumbers") setLineNumbers(value);
|
||||
else if (option === "gutter") setGutter(value);
|
||||
- else if (option === "readOnly") options.readOnly = value;
|
||||
- else if (option === "indentUnit") {options.indentUnit = indentUnit = value; setParser(options.parser);}
|
||||
- else if (/^(?:enterMode|tabMode|indentWithTabs|readOnly|autoMatchBrackets|undoDepth)$/.test(option)) options[option] = value;
|
||||
- else throw new Error("Can't set option " + option);
|
||||
+ else if (option === "indentUnit") {options.indentUnit = value; setParser(options.parser);}
|
||||
+ else options[option] = value;
|
||||
},
|
||||
cursorCoords: cursorCoords,
|
||||
undo: operation(undo),
|
||||
@@ -1402,7 +1406,8 @@ var CodeMirror = (function() {
|
||||
replaceRange: operation(replaceRange),
|
||||
|
||||
operation: function(f){return operation(f)();},
|
||||
- refresh: function(){updateDisplay([{from: 0, to: lines.length}]);}
|
||||
+ refresh: function(){updateDisplay([{from: 0, to: lines.length}]);},
|
||||
+ getInputField: function(){return input;}
|
||||
};
|
||||
return instance;
|
||||
}
|
||||
@@ -1420,6 +1425,7 @@ var CodeMirror = (function() {
|
||||
readOnly: false,
|
||||
onChange: null,
|
||||
onCursorActivity: null,
|
||||
+ onGutterClick: null,
|
||||
autoMatchBrackets: false,
|
||||
workTime: 200,
|
||||
workDelay: 300,
|
||||
</textarea></form>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-diff</code>.</p>
|
||||
|
||||
</article>
|
||||
192
applications/admin/static/codemirror/mode/ecl/ecl.js
vendored
192
applications/admin/static/codemirror/mode/ecl/ecl.js
vendored
@@ -1,192 +0,0 @@
|
||||
CodeMirror.defineMode("ecl", function(config) {
|
||||
|
||||
function words(str) {
|
||||
var obj = {}, words = str.split(" ");
|
||||
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
|
||||
return obj;
|
||||
}
|
||||
|
||||
function metaHook(stream, state) {
|
||||
if (!state.startOfLine) return false;
|
||||
stream.skipToEnd();
|
||||
return "meta";
|
||||
}
|
||||
|
||||
var indentUnit = config.indentUnit;
|
||||
var keyword = words("abs acos allnodes ascii asin asstring atan atan2 ave case choose choosen choosesets clustersize combine correlation cos cosh count covariance cron dataset dedup define denormalize distribute distributed distribution ebcdic enth error evaluate event eventextra eventname exists exp failcode failmessage fetch fromunicode getisvalid global graph group hash hash32 hash64 hashcrc hashmd5 having if index intformat isvalid iterate join keyunicode length library limit ln local log loop map matched matchlength matchposition matchtext matchunicode max merge mergejoin min nolocal nonempty normalize parse pipe power preload process project pull random range rank ranked realformat recordof regexfind regexreplace regroup rejected rollup round roundup row rowdiff sample set sin sinh sizeof soapcall sort sorted sqrt stepped stored sum table tan tanh thisnode topn tounicode transfer trim truncate typeof ungroup unicodeorder variance which workunit xmldecode xmlencode xmltext xmlunicode");
|
||||
var variable = words("apply assert build buildindex evaluate fail keydiff keypatch loadxml nothor notify output parallel sequential soapcall wait");
|
||||
var variable_2 = words("__compressed__ all and any as atmost before beginc++ best between case const counter csv descend encrypt end endc++ endmacro except exclusive expire export extend false few first flat from full function group header heading hole ifblock import in interface joined keep keyed last left limit load local locale lookup macro many maxcount maxlength min skew module named nocase noroot noscan nosort not of only opt or outer overwrite packed partition penalty physicallength pipe quote record relationship repeat return right scan self separator service shared skew skip sql store terminator thor threshold token transform trim true type unicodeorder unsorted validate virtual whole wild within xml xpath");
|
||||
var variable_3 = words("ascii big_endian boolean data decimal ebcdic integer pattern qstring real record rule set of string token udecimal unicode unsigned varstring varunicode");
|
||||
var builtin = words("checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when");
|
||||
var blockKeywords = words("catch class do else finally for if switch try while");
|
||||
var atoms = words("true false null");
|
||||
var hooks = {"#": metaHook};
|
||||
var multiLineStrings;
|
||||
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
|
||||
|
||||
var curPunc;
|
||||
|
||||
function tokenBase(stream, state) {
|
||||
var ch = stream.next();
|
||||
if (hooks[ch]) {
|
||||
var result = hooks[ch](stream, state);
|
||||
if (result !== false) return result;
|
||||
}
|
||||
if (ch == '"' || ch == "'") {
|
||||
state.tokenize = tokenString(ch);
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
|
||||
curPunc = ch;
|
||||
return null;
|
||||
}
|
||||
if (/\d/.test(ch)) {
|
||||
stream.eatWhile(/[\w\.]/);
|
||||
return "number";
|
||||
}
|
||||
if (ch == "/") {
|
||||
if (stream.eat("*")) {
|
||||
state.tokenize = tokenComment;
|
||||
return tokenComment(stream, state);
|
||||
}
|
||||
if (stream.eat("/")) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
}
|
||||
if (isOperatorChar.test(ch)) {
|
||||
stream.eatWhile(isOperatorChar);
|
||||
return "operator";
|
||||
}
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
var cur = stream.current().toLowerCase();
|
||||
if (keyword.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "keyword";
|
||||
} else if (variable.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "variable";
|
||||
} else if (variable_2.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "variable-2";
|
||||
} else if (variable_3.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "variable-3";
|
||||
} else if (builtin.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "builtin";
|
||||
} else { //Data types are of from KEYWORD##
|
||||
var i = cur.length - 1;
|
||||
while(i >= 0 && (!isNaN(cur[i]) || cur[i] == '_'))
|
||||
--i;
|
||||
|
||||
if (i > 0) {
|
||||
var cur2 = cur.substr(0, i + 1);
|
||||
if (variable_3.propertyIsEnumerable(cur2)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur2)) curPunc = "newstatement";
|
||||
return "variable-3";
|
||||
}
|
||||
}
|
||||
}
|
||||
if (atoms.propertyIsEnumerable(cur)) return "atom";
|
||||
return null;
|
||||
}
|
||||
|
||||
function tokenString(quote) {
|
||||
return function(stream, state) {
|
||||
var escaped = false, next, end = false;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == quote && !escaped) {end = true; break;}
|
||||
escaped = !escaped && next == "\\";
|
||||
}
|
||||
if (end || !(escaped || multiLineStrings))
|
||||
state.tokenize = tokenBase;
|
||||
return "string";
|
||||
};
|
||||
}
|
||||
|
||||
function tokenComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
while (ch = stream.next()) {
|
||||
if (ch == "/" && maybeEnd) {
|
||||
state.tokenize = tokenBase;
|
||||
break;
|
||||
}
|
||||
maybeEnd = (ch == "*");
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function Context(indented, column, type, align, prev) {
|
||||
this.indented = indented;
|
||||
this.column = column;
|
||||
this.type = type;
|
||||
this.align = align;
|
||||
this.prev = prev;
|
||||
}
|
||||
function pushContext(state, col, type) {
|
||||
return state.context = new Context(state.indented, col, type, null, state.context);
|
||||
}
|
||||
function popContext(state) {
|
||||
var t = state.context.type;
|
||||
if (t == ")" || t == "]" || t == "}")
|
||||
state.indented = state.context.indented;
|
||||
return state.context = state.context.prev;
|
||||
}
|
||||
|
||||
// Interface
|
||||
|
||||
return {
|
||||
startState: function(basecolumn) {
|
||||
return {
|
||||
tokenize: null,
|
||||
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
|
||||
indented: 0,
|
||||
startOfLine: true
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
var ctx = state.context;
|
||||
if (stream.sol()) {
|
||||
if (ctx.align == null) ctx.align = false;
|
||||
state.indented = stream.indentation();
|
||||
state.startOfLine = true;
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
curPunc = null;
|
||||
var style = (state.tokenize || tokenBase)(stream, state);
|
||||
if (style == "comment" || style == "meta") return style;
|
||||
if (ctx.align == null) ctx.align = true;
|
||||
|
||||
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
|
||||
else if (curPunc == "{") pushContext(state, stream.column(), "}");
|
||||
else if (curPunc == "[") pushContext(state, stream.column(), "]");
|
||||
else if (curPunc == "(") pushContext(state, stream.column(), ")");
|
||||
else if (curPunc == "}") {
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
if (ctx.type == "}") ctx = popContext(state);
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
}
|
||||
else if (curPunc == ctx.type) popContext(state);
|
||||
else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
|
||||
pushContext(state, stream.column(), "statement");
|
||||
state.startOfLine = false;
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function(state, textAfter) {
|
||||
if (state.tokenize != tokenBase && state.tokenize != null) return 0;
|
||||
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
|
||||
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
|
||||
var closing = firstChar == ctx.type;
|
||||
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
|
||||
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
|
||||
else return ctx.indented + (closing ? 0 : indentUnit);
|
||||
},
|
||||
|
||||
electricChars: "{}"
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-ecl", "ecl");
|
||||
@@ -1,52 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: ECL mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="ecl.js"></script>
|
||||
<style>.CodeMirror {border: 1px solid black;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">ECL</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>ECL mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
/*
|
||||
sample useless code to demonstrate ecl syntax highlighting
|
||||
this is a multiline comment!
|
||||
*/
|
||||
|
||||
// this is a singleline comment!
|
||||
|
||||
import ut;
|
||||
r :=
|
||||
record
|
||||
string22 s1 := '123';
|
||||
integer4 i1 := 123;
|
||||
end;
|
||||
#option('tmp', true);
|
||||
d := dataset('tmp::qb', r, thor);
|
||||
output(d);
|
||||
</textarea></form>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
|
||||
</script>
|
||||
|
||||
<p>Based on CodeMirror's clike mode. For more information see <a href="http://hpccsystems.com">HPCC Systems</a> web site.</p>
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-ecl</code>.</p>
|
||||
|
||||
</article>
|
||||
@@ -1,484 +0,0 @@
|
||||
// block; "begin", "case", "fun", "if", "receive", "try": closed by "end"
|
||||
// block internal; "after", "catch", "of"
|
||||
// guard; "when", closed by "->"
|
||||
// "->" opens a clause, closed by ";" or "."
|
||||
// "<<" opens a binary, closed by ">>"
|
||||
// "," appears in arglists, lists, tuples and terminates lines of code
|
||||
// "." resets indentation to 0
|
||||
// obsolete; "cond", "let", "query"
|
||||
|
||||
CodeMirror.defineMIME("text/x-erlang", "erlang");
|
||||
|
||||
CodeMirror.defineMode("erlang", function(cmCfg) {
|
||||
|
||||
function rval(state,_stream,type) {
|
||||
// distinguish between "." as terminator and record field operator
|
||||
state.in_record = (type == "record");
|
||||
|
||||
// erlang -> CodeMirror tag
|
||||
switch (type) {
|
||||
case "atom": return "atom";
|
||||
case "attribute": return "attribute";
|
||||
case "boolean": return "special";
|
||||
case "builtin": return "builtin";
|
||||
case "comment": return "comment";
|
||||
case "fun": return "meta";
|
||||
case "function": return "tag";
|
||||
case "guard": return "property";
|
||||
case "keyword": return "keyword";
|
||||
case "macro": return "variable-2";
|
||||
case "number": return "number";
|
||||
case "operator": return "operator";
|
||||
case "record": return "bracket";
|
||||
case "string": return "string";
|
||||
case "type": return "def";
|
||||
case "variable": return "variable";
|
||||
case "error": return "error";
|
||||
case "separator": return null;
|
||||
case "open_paren": return null;
|
||||
case "close_paren": return null;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
var typeWords = [
|
||||
"-type", "-spec", "-export_type", "-opaque"];
|
||||
|
||||
var keywordWords = [
|
||||
"after","begin","catch","case","cond","end","fun","if",
|
||||
"let","of","query","receive","try","when"];
|
||||
|
||||
var separatorRE = /[\->\.,:;]/;
|
||||
var separatorWords = [
|
||||
"->",";",":",".",","];
|
||||
|
||||
var operatorWords = [
|
||||
"and","andalso","band","bnot","bor","bsl","bsr","bxor",
|
||||
"div","not","or","orelse","rem","xor"];
|
||||
|
||||
var symbolRE = /[\+\-\*\/<>=\|:!]/;
|
||||
var symbolWords = [
|
||||
"+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-","!"];
|
||||
|
||||
var openParenRE = /[<\(\[\{]/;
|
||||
var openParenWords = [
|
||||
"<<","(","[","{"];
|
||||
|
||||
var closeParenRE = /[>\)\]\}]/;
|
||||
var closeParenWords = [
|
||||
"}","]",")",">>"];
|
||||
|
||||
var guardWords = [
|
||||
"is_atom","is_binary","is_bitstring","is_boolean","is_float",
|
||||
"is_function","is_integer","is_list","is_number","is_pid",
|
||||
"is_port","is_record","is_reference","is_tuple",
|
||||
"atom","binary","bitstring","boolean","function","integer","list",
|
||||
"number","pid","port","record","reference","tuple"];
|
||||
|
||||
var bifWords = [
|
||||
"abs","adler32","adler32_combine","alive","apply","atom_to_binary",
|
||||
"atom_to_list","binary_to_atom","binary_to_existing_atom",
|
||||
"binary_to_list","binary_to_term","bit_size","bitstring_to_list",
|
||||
"byte_size","check_process_code","contact_binary","crc32",
|
||||
"crc32_combine","date","decode_packet","delete_module",
|
||||
"disconnect_node","element","erase","exit","float","float_to_list",
|
||||
"garbage_collect","get","get_keys","group_leader","halt","hd",
|
||||
"integer_to_list","internal_bif","iolist_size","iolist_to_binary",
|
||||
"is_alive","is_atom","is_binary","is_bitstring","is_boolean",
|
||||
"is_float","is_function","is_integer","is_list","is_number","is_pid",
|
||||
"is_port","is_process_alive","is_record","is_reference","is_tuple",
|
||||
"length","link","list_to_atom","list_to_binary","list_to_bitstring",
|
||||
"list_to_existing_atom","list_to_float","list_to_integer",
|
||||
"list_to_pid","list_to_tuple","load_module","make_ref","module_loaded",
|
||||
"monitor_node","node","node_link","node_unlink","nodes","notalive",
|
||||
"now","open_port","pid_to_list","port_close","port_command",
|
||||
"port_connect","port_control","pre_loaded","process_flag",
|
||||
"process_info","processes","purge_module","put","register",
|
||||
"registered","round","self","setelement","size","spawn","spawn_link",
|
||||
"spawn_monitor","spawn_opt","split_binary","statistics",
|
||||
"term_to_binary","time","throw","tl","trunc","tuple_size",
|
||||
"tuple_to_list","unlink","unregister","whereis"];
|
||||
|
||||
// [Ø-Þ] [À-Ö]
|
||||
// [ß-ö] [ø-ÿ]
|
||||
var anumRE = /[\w@Ø-ÞÀ-Öß-öø-ÿ]/;
|
||||
var escapesRE =
|
||||
/[0-7]{1,3}|[bdefnrstv\\"']|\^[a-zA-Z]|x[0-9a-zA-Z]{2}|x{[0-9a-zA-Z]+}/;
|
||||
|
||||
function tokenize(stream, state) {
|
||||
|
||||
// in multi-line string
|
||||
if (state.in_string) {
|
||||
state.in_string = (!doubleQuote(stream));
|
||||
return rval(state,stream,"string");
|
||||
}
|
||||
|
||||
// in multi-line atom
|
||||
if (state.in_atom) {
|
||||
state.in_atom = (!singleQuote(stream));
|
||||
return rval(state,stream,"atom");
|
||||
}
|
||||
|
||||
// whitespace
|
||||
if (stream.eatSpace()) {
|
||||
return rval(state,stream,"whitespace");
|
||||
}
|
||||
|
||||
// attributes and type specs
|
||||
if ((peekToken(state).token == "") &&
|
||||
stream.match(/-\s*[a-zß-öø-ÿ][\wØ-ÞÀ-Öß-öø-ÿ]*/)) {
|
||||
if (isMember(stream.current(),typeWords)) {
|
||||
return rval(state,stream,"type");
|
||||
}else{
|
||||
return rval(state,stream,"attribute");
|
||||
}
|
||||
}
|
||||
|
||||
var ch = stream.next();
|
||||
|
||||
// comment
|
||||
if (ch == '%') {
|
||||
stream.skipToEnd();
|
||||
return rval(state,stream,"comment");
|
||||
}
|
||||
|
||||
// macro
|
||||
if (ch == '?') {
|
||||
stream.eatWhile(anumRE);
|
||||
return rval(state,stream,"macro");
|
||||
}
|
||||
|
||||
// record
|
||||
if (ch == "#") {
|
||||
stream.eatWhile(anumRE);
|
||||
return rval(state,stream,"record");
|
||||
}
|
||||
|
||||
// dollar escape
|
||||
if ( ch == "$" ) {
|
||||
if (stream.next() == "\\" && !stream.match(escapesRE)) {
|
||||
return rval(state,stream,"error");
|
||||
}
|
||||
return rval(state,stream,"number");
|
||||
}
|
||||
|
||||
// quoted atom
|
||||
if (ch == '\'') {
|
||||
if (!(state.in_atom = (!singleQuote(stream)))) {
|
||||
if (stream.match(/\s*\/\s*[0-9]/,false)) {
|
||||
stream.match(/\s*\/\s*[0-9]/,true);
|
||||
popToken(state);
|
||||
return rval(state,stream,"fun"); // 'f'/0 style fun
|
||||
}
|
||||
if (stream.match(/\s*\(/,false) || stream.match(/\s*:/,false)) {
|
||||
return rval(state,stream,"function");
|
||||
}
|
||||
}
|
||||
return rval(state,stream,"atom");
|
||||
}
|
||||
|
||||
// string
|
||||
if (ch == '"') {
|
||||
state.in_string = (!doubleQuote(stream));
|
||||
return rval(state,stream,"string");
|
||||
}
|
||||
|
||||
// variable
|
||||
if (/[A-Z_Ø-ÞÀ-Ö]/.test(ch)) {
|
||||
stream.eatWhile(anumRE);
|
||||
return rval(state,stream,"variable");
|
||||
}
|
||||
|
||||
// atom/keyword/BIF/function
|
||||
if (/[a-z_ß-öø-ÿ]/.test(ch)) {
|
||||
stream.eatWhile(anumRE);
|
||||
|
||||
if (stream.match(/\s*\/\s*[0-9]/,false)) {
|
||||
stream.match(/\s*\/\s*[0-9]/,true);
|
||||
popToken(state);
|
||||
return rval(state,stream,"fun"); // f/0 style fun
|
||||
}
|
||||
|
||||
var w = stream.current();
|
||||
|
||||
if (isMember(w,keywordWords)) {
|
||||
pushToken(state,stream);
|
||||
return rval(state,stream,"keyword");
|
||||
}else if (stream.match(/\s*\(/,false)) {
|
||||
// 'put' and 'erlang:put' are bifs, 'foo:put' is not
|
||||
if (isMember(w,bifWords) &&
|
||||
(!isPrev(stream,":") || isPrev(stream,"erlang:"))) {
|
||||
return rval(state,stream,"builtin");
|
||||
}else if (isMember(w,guardWords)) {
|
||||
return rval(state,stream,"guard");
|
||||
}else{
|
||||
return rval(state,stream,"function");
|
||||
}
|
||||
}else if (isMember(w,operatorWords)) {
|
||||
return rval(state,stream,"operator");
|
||||
}else if (stream.match(/\s*:/,false)) {
|
||||
if (w == "erlang") {
|
||||
return rval(state,stream,"builtin");
|
||||
} else {
|
||||
return rval(state,stream,"function");
|
||||
}
|
||||
}else if (isMember(w,["true","false"])) {
|
||||
return rval(state,stream,"boolean");
|
||||
}else{
|
||||
return rval(state,stream,"atom");
|
||||
}
|
||||
}
|
||||
|
||||
// number
|
||||
var digitRE = /[0-9]/;
|
||||
var radixRE = /[0-9a-zA-Z]/; // 36#zZ style int
|
||||
if (digitRE.test(ch)) {
|
||||
stream.eatWhile(digitRE);
|
||||
if (stream.eat('#')) {
|
||||
stream.eatWhile(radixRE); // 36#aZ style integer
|
||||
} else {
|
||||
if (stream.eat('.')) { // float
|
||||
stream.eatWhile(digitRE);
|
||||
}
|
||||
if (stream.eat(/[eE]/)) {
|
||||
stream.eat(/[-+]/); // float with exponent
|
||||
stream.eatWhile(digitRE);
|
||||
}
|
||||
}
|
||||
return rval(state,stream,"number"); // normal integer
|
||||
}
|
||||
|
||||
// open parens
|
||||
if (nongreedy(stream,openParenRE,openParenWords)) {
|
||||
pushToken(state,stream);
|
||||
return rval(state,stream,"open_paren");
|
||||
}
|
||||
|
||||
// close parens
|
||||
if (nongreedy(stream,closeParenRE,closeParenWords)) {
|
||||
pushToken(state,stream);
|
||||
return rval(state,stream,"close_paren");
|
||||
}
|
||||
|
||||
// separators
|
||||
if (greedy(stream,separatorRE,separatorWords)) {
|
||||
// distinguish between "." as terminator and record field operator
|
||||
if (!state.in_record) {
|
||||
pushToken(state,stream);
|
||||
}
|
||||
return rval(state,stream,"separator");
|
||||
}
|
||||
|
||||
// operators
|
||||
if (greedy(stream,symbolRE,symbolWords)) {
|
||||
return rval(state,stream,"operator");
|
||||
}
|
||||
|
||||
return rval(state,stream,null);
|
||||
}
|
||||
|
||||
function isPrev(stream,string) {
|
||||
var start = stream.start;
|
||||
var len = string.length;
|
||||
if (len <= start) {
|
||||
var word = stream.string.slice(start-len,start);
|
||||
return word == string;
|
||||
}else{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function nongreedy(stream,re,words) {
|
||||
if (stream.current().length == 1 && re.test(stream.current())) {
|
||||
stream.backUp(1);
|
||||
while (re.test(stream.peek())) {
|
||||
stream.next();
|
||||
if (isMember(stream.current(),words)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
stream.backUp(stream.current().length-1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function greedy(stream,re,words) {
|
||||
if (stream.current().length == 1 && re.test(stream.current())) {
|
||||
while (re.test(stream.peek())) {
|
||||
stream.next();
|
||||
}
|
||||
while (0 < stream.current().length) {
|
||||
if (isMember(stream.current(),words)) {
|
||||
return true;
|
||||
}else{
|
||||
stream.backUp(1);
|
||||
}
|
||||
}
|
||||
stream.next();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function doubleQuote(stream) {
|
||||
return quote(stream, '"', '\\');
|
||||
}
|
||||
|
||||
function singleQuote(stream) {
|
||||
return quote(stream,'\'','\\');
|
||||
}
|
||||
|
||||
function quote(stream,quoteChar,escapeChar) {
|
||||
while (!stream.eol()) {
|
||||
var ch = stream.next();
|
||||
if (ch == quoteChar) {
|
||||
return true;
|
||||
}else if (ch == escapeChar) {
|
||||
stream.next();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isMember(element,list) {
|
||||
return (-1 < list.indexOf(element));
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
function myIndent(state,textAfter) {
|
||||
var indent = cmCfg.indentUnit;
|
||||
var token = (peekToken(state)).token;
|
||||
var wordAfter = takewhile(textAfter,/[^a-z]/);
|
||||
|
||||
if (state.in_string || state.in_atom) {
|
||||
return CodeMirror.Pass;
|
||||
}else if (token == "") {
|
||||
return 0;
|
||||
}else if (isMember(token,openParenWords)) {
|
||||
return (peekToken(state)).column+token.length;
|
||||
}else if (token == "when") {
|
||||
return (peekToken(state)).column+token.length+1;
|
||||
}else if (token == "fun" && wordAfter == "") {
|
||||
return (peekToken(state)).column+token.length;
|
||||
}else if (token == "->") {
|
||||
if (isMember(wordAfter,["end","after","catch"])) {
|
||||
return peekToken(state,2).column;
|
||||
}else if (peekToken(state,2).token == "fun") {
|
||||
return peekToken(state,2).column+indent;
|
||||
}else if (peekToken(state,2).token == "") {
|
||||
return indent;
|
||||
}else{
|
||||
return (peekToken(state)).indent+indent;
|
||||
}
|
||||
}else if (isMember(wordAfter,["after","catch","of"])) {
|
||||
return (peekToken(state)).indent;
|
||||
}else{
|
||||
return (peekToken(state)).column+indent;
|
||||
}
|
||||
}
|
||||
|
||||
function takewhile(str,re) {
|
||||
var m = str.match(re);
|
||||
return m ? str.slice(0,m.index) : str;
|
||||
}
|
||||
|
||||
function Token(stream) {
|
||||
this.token = stream ? stream.current() : "";
|
||||
this.column = stream ? stream.column() : 0;
|
||||
this.indent = stream ? stream.indentation() : 0;
|
||||
}
|
||||
|
||||
function popToken(state) {
|
||||
return state.tokenStack.pop();
|
||||
}
|
||||
|
||||
function peekToken(state,depth) {
|
||||
var len = state.tokenStack.length;
|
||||
var dep = (depth ? depth : 1);
|
||||
if (len < dep) {
|
||||
return new Token;
|
||||
}else{
|
||||
return state.tokenStack[len-dep];
|
||||
}
|
||||
}
|
||||
|
||||
function pushToken(state,stream) {
|
||||
var token = stream.current();
|
||||
var prev_token = peekToken(state).token;
|
||||
|
||||
if (token == ".") {
|
||||
state.tokenStack = [];
|
||||
return false;
|
||||
}else if(isMember(token,[",", ":", "of", "cond", "let", "query"])) {
|
||||
return false;
|
||||
}else if (drop_last(prev_token,token)) {
|
||||
return false;
|
||||
}else if (drop_both(prev_token,token)) {
|
||||
popToken(state);
|
||||
return false;
|
||||
}else if (drop_first(prev_token,token)) {
|
||||
popToken(state);
|
||||
return pushToken(state,stream);
|
||||
}else if (isMember(token,["after","catch"])) {
|
||||
return false;
|
||||
}else{
|
||||
state.tokenStack.push(new Token(stream));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function drop_last(open, close) {
|
||||
switch(open+" "+close) {
|
||||
case "when ;": return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
function drop_first(open, close) {
|
||||
switch (open+" "+close) {
|
||||
case "when ->": return true;
|
||||
case "-> end": return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
function drop_both(open, close) {
|
||||
switch (open+" "+close) {
|
||||
case "( )": return true;
|
||||
case "[ ]": return true;
|
||||
case "{ }": return true;
|
||||
case "<< >>": return true;
|
||||
case "begin end": return true;
|
||||
case "case end": return true;
|
||||
case "fun end": return true;
|
||||
case "if end": return true;
|
||||
case "receive end": return true;
|
||||
case "try end": return true;
|
||||
case "-> catch": return true;
|
||||
case "-> after": return true;
|
||||
case "-> ;": return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
startState:
|
||||
function() {
|
||||
return {tokenStack: [],
|
||||
in_record: false,
|
||||
in_string: false,
|
||||
in_atom: false};
|
||||
},
|
||||
|
||||
token:
|
||||
function(stream, state) {
|
||||
return tokenize(stream, state);
|
||||
},
|
||||
|
||||
indent:
|
||||
function(state, textAfter) {
|
||||
return myIndent(state,textAfter);
|
||||
},
|
||||
|
||||
lineComment: "%"
|
||||
};
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Erlang mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<link rel="stylesheet" href="../../theme/erlang-dark.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/edit/matchbrackets.js"></script>
|
||||
<script src="erlang.js"></script>
|
||||
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Erlang</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Erlang mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
%% -*- mode: erlang; erlang-indent-level: 2 -*-
|
||||
%%% Created : 7 May 2012 by mats cronqvist <masse@klarna.com>
|
||||
|
||||
%% @doc
|
||||
%% Demonstrates how to print a record.
|
||||
%% @end
|
||||
|
||||
-module('ex').
|
||||
-author('mats cronqvist').
|
||||
-export([demo/0,
|
||||
rec_info/1]).
|
||||
|
||||
-record(demo,{a="One",b="Two",c="Three",d="Four"}).
|
||||
|
||||
rec_info(demo) -> record_info(fields,demo).
|
||||
|
||||
demo() -> expand_recs(?MODULE,#demo{a="A",b="BB"}).
|
||||
|
||||
expand_recs(M,List) when is_list(List) ->
|
||||
[expand_recs(M,L)||L<-List];
|
||||
expand_recs(M,Tup) when is_tuple(Tup) ->
|
||||
case tuple_size(Tup) of
|
||||
L when L < 1 -> Tup;
|
||||
L ->
|
||||
try Fields = M:rec_info(element(1,Tup)),
|
||||
L = length(Fields)+1,
|
||||
lists:zip(Fields,expand_recs(M,tl(tuple_to_list(Tup))))
|
||||
catch _:_ ->
|
||||
list_to_tuple(expand_recs(M,tuple_to_list(Tup)))
|
||||
end
|
||||
end;
|
||||
expand_recs(_,Term) ->
|
||||
Term.
|
||||
</textarea></form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
extraKeys: {"Tab": "indentAuto"},
|
||||
theme: "erlang-dark"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-erlang</code>.</p>
|
||||
</article>
|
||||
330
applications/admin/static/codemirror/mode/gas/gas.js
vendored
330
applications/admin/static/codemirror/mode/gas/gas.js
vendored
@@ -1,330 +0,0 @@
|
||||
CodeMirror.defineMode("gas", function(_config, parserConfig) {
|
||||
'use strict';
|
||||
|
||||
// If an architecture is specified, its initialization function may
|
||||
// populate this array with custom parsing functions which will be
|
||||
// tried in the event that the standard functions do not find a match.
|
||||
var custom = [];
|
||||
|
||||
// The symbol used to start a line comment changes based on the target
|
||||
// architecture.
|
||||
// If no architecture is pased in "parserConfig" then only multiline
|
||||
// comments will have syntax support.
|
||||
var lineCommentStartSymbol = "";
|
||||
|
||||
// These directives are architecture independent.
|
||||
// Machine specific directives should go in their respective
|
||||
// architecture initialization function.
|
||||
// Reference:
|
||||
// http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops
|
||||
var directives = {
|
||||
".abort" : "builtin",
|
||||
".align" : "builtin",
|
||||
".altmacro" : "builtin",
|
||||
".ascii" : "builtin",
|
||||
".asciz" : "builtin",
|
||||
".balign" : "builtin",
|
||||
".balignw" : "builtin",
|
||||
".balignl" : "builtin",
|
||||
".bundle_align_mode" : "builtin",
|
||||
".bundle_lock" : "builtin",
|
||||
".bundle_unlock" : "builtin",
|
||||
".byte" : "builtin",
|
||||
".cfi_startproc" : "builtin",
|
||||
".comm" : "builtin",
|
||||
".data" : "builtin",
|
||||
".def" : "builtin",
|
||||
".desc" : "builtin",
|
||||
".dim" : "builtin",
|
||||
".double" : "builtin",
|
||||
".eject" : "builtin",
|
||||
".else" : "builtin",
|
||||
".elseif" : "builtin",
|
||||
".end" : "builtin",
|
||||
".endef" : "builtin",
|
||||
".endfunc" : "builtin",
|
||||
".endif" : "builtin",
|
||||
".equ" : "builtin",
|
||||
".equiv" : "builtin",
|
||||
".eqv" : "builtin",
|
||||
".err" : "builtin",
|
||||
".error" : "builtin",
|
||||
".exitm" : "builtin",
|
||||
".extern" : "builtin",
|
||||
".fail" : "builtin",
|
||||
".file" : "builtin",
|
||||
".fill" : "builtin",
|
||||
".float" : "builtin",
|
||||
".func" : "builtin",
|
||||
".global" : "builtin",
|
||||
".gnu_attribute" : "builtin",
|
||||
".hidden" : "builtin",
|
||||
".hword" : "builtin",
|
||||
".ident" : "builtin",
|
||||
".if" : "builtin",
|
||||
".incbin" : "builtin",
|
||||
".include" : "builtin",
|
||||
".int" : "builtin",
|
||||
".internal" : "builtin",
|
||||
".irp" : "builtin",
|
||||
".irpc" : "builtin",
|
||||
".lcomm" : "builtin",
|
||||
".lflags" : "builtin",
|
||||
".line" : "builtin",
|
||||
".linkonce" : "builtin",
|
||||
".list" : "builtin",
|
||||
".ln" : "builtin",
|
||||
".loc" : "builtin",
|
||||
".loc_mark_labels" : "builtin",
|
||||
".local" : "builtin",
|
||||
".long" : "builtin",
|
||||
".macro" : "builtin",
|
||||
".mri" : "builtin",
|
||||
".noaltmacro" : "builtin",
|
||||
".nolist" : "builtin",
|
||||
".octa" : "builtin",
|
||||
".offset" : "builtin",
|
||||
".org" : "builtin",
|
||||
".p2align" : "builtin",
|
||||
".popsection" : "builtin",
|
||||
".previous" : "builtin",
|
||||
".print" : "builtin",
|
||||
".protected" : "builtin",
|
||||
".psize" : "builtin",
|
||||
".purgem" : "builtin",
|
||||
".pushsection" : "builtin",
|
||||
".quad" : "builtin",
|
||||
".reloc" : "builtin",
|
||||
".rept" : "builtin",
|
||||
".sbttl" : "builtin",
|
||||
".scl" : "builtin",
|
||||
".section" : "builtin",
|
||||
".set" : "builtin",
|
||||
".short" : "builtin",
|
||||
".single" : "builtin",
|
||||
".size" : "builtin",
|
||||
".skip" : "builtin",
|
||||
".sleb128" : "builtin",
|
||||
".space" : "builtin",
|
||||
".stab" : "builtin",
|
||||
".string" : "builtin",
|
||||
".struct" : "builtin",
|
||||
".subsection" : "builtin",
|
||||
".symver" : "builtin",
|
||||
".tag" : "builtin",
|
||||
".text" : "builtin",
|
||||
".title" : "builtin",
|
||||
".type" : "builtin",
|
||||
".uleb128" : "builtin",
|
||||
".val" : "builtin",
|
||||
".version" : "builtin",
|
||||
".vtable_entry" : "builtin",
|
||||
".vtable_inherit" : "builtin",
|
||||
".warning" : "builtin",
|
||||
".weak" : "builtin",
|
||||
".weakref" : "builtin",
|
||||
".word" : "builtin"
|
||||
};
|
||||
|
||||
var registers = {};
|
||||
|
||||
function x86(_parserConfig) {
|
||||
lineCommentStartSymbol = "#";
|
||||
|
||||
registers.ax = "variable";
|
||||
registers.eax = "variable-2";
|
||||
registers.rax = "variable-3";
|
||||
|
||||
registers.bx = "variable";
|
||||
registers.ebx = "variable-2";
|
||||
registers.rbx = "variable-3";
|
||||
|
||||
registers.cx = "variable";
|
||||
registers.ecx = "variable-2";
|
||||
registers.rcx = "variable-3";
|
||||
|
||||
registers.dx = "variable";
|
||||
registers.edx = "variable-2";
|
||||
registers.rdx = "variable-3";
|
||||
|
||||
registers.si = "variable";
|
||||
registers.esi = "variable-2";
|
||||
registers.rsi = "variable-3";
|
||||
|
||||
registers.di = "variable";
|
||||
registers.edi = "variable-2";
|
||||
registers.rdi = "variable-3";
|
||||
|
||||
registers.sp = "variable";
|
||||
registers.esp = "variable-2";
|
||||
registers.rsp = "variable-3";
|
||||
|
||||
registers.bp = "variable";
|
||||
registers.ebp = "variable-2";
|
||||
registers.rbp = "variable-3";
|
||||
|
||||
registers.ip = "variable";
|
||||
registers.eip = "variable-2";
|
||||
registers.rip = "variable-3";
|
||||
|
||||
registers.cs = "keyword";
|
||||
registers.ds = "keyword";
|
||||
registers.ss = "keyword";
|
||||
registers.es = "keyword";
|
||||
registers.fs = "keyword";
|
||||
registers.gs = "keyword";
|
||||
}
|
||||
|
||||
function armv6(_parserConfig) {
|
||||
// Reference:
|
||||
// http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf
|
||||
// http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf
|
||||
lineCommentStartSymbol = "@";
|
||||
directives.syntax = "builtin";
|
||||
|
||||
registers.r0 = "variable";
|
||||
registers.r1 = "variable";
|
||||
registers.r2 = "variable";
|
||||
registers.r3 = "variable";
|
||||
registers.r4 = "variable";
|
||||
registers.r5 = "variable";
|
||||
registers.r6 = "variable";
|
||||
registers.r7 = "variable";
|
||||
registers.r8 = "variable";
|
||||
registers.r9 = "variable";
|
||||
registers.r10 = "variable";
|
||||
registers.r11 = "variable";
|
||||
registers.r12 = "variable";
|
||||
|
||||
registers.sp = "variable-2";
|
||||
registers.lr = "variable-2";
|
||||
registers.pc = "variable-2";
|
||||
registers.r13 = registers.sp;
|
||||
registers.r14 = registers.lr;
|
||||
registers.r15 = registers.pc;
|
||||
|
||||
custom.push(function(ch, stream) {
|
||||
if (ch === '#') {
|
||||
stream.eatWhile(/\w/);
|
||||
return "number";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var arch = parserConfig.architecture.toLowerCase();
|
||||
if (arch === "x86") {
|
||||
x86(parserConfig);
|
||||
} else if (arch === "arm" || arch === "armv6") {
|
||||
armv6(parserConfig);
|
||||
}
|
||||
|
||||
function nextUntilUnescaped(stream, end) {
|
||||
var escaped = false, next;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next === end && !escaped) {
|
||||
return false;
|
||||
}
|
||||
escaped = !escaped && next === "\\";
|
||||
}
|
||||
return escaped;
|
||||
}
|
||||
|
||||
function clikeComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
while ((ch = stream.next()) != null) {
|
||||
if (ch === "/" && maybeEnd) {
|
||||
state.tokenize = null;
|
||||
break;
|
||||
}
|
||||
maybeEnd = (ch === "*");
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
|
||||
return {
|
||||
startState: function() {
|
||||
return {
|
||||
tokenize: null
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
if (state.tokenize) {
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
|
||||
if (stream.eatSpace()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var style, cur, ch = stream.next();
|
||||
|
||||
if (ch === "/") {
|
||||
if (stream.eat("*")) {
|
||||
state.tokenize = clikeComment;
|
||||
return clikeComment(stream, state);
|
||||
}
|
||||
}
|
||||
|
||||
if (ch === lineCommentStartSymbol) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
|
||||
if (ch === '"') {
|
||||
nextUntilUnescaped(stream, '"');
|
||||
return "string";
|
||||
}
|
||||
|
||||
if (ch === '.') {
|
||||
stream.eatWhile(/\w/);
|
||||
cur = stream.current().toLowerCase();
|
||||
style = directives[cur];
|
||||
return style || null;
|
||||
}
|
||||
|
||||
if (ch === '=') {
|
||||
stream.eatWhile(/\w/);
|
||||
return "tag";
|
||||
}
|
||||
|
||||
if (ch === '{') {
|
||||
return "braket";
|
||||
}
|
||||
|
||||
if (ch === '}') {
|
||||
return "braket";
|
||||
}
|
||||
|
||||
if (/\d/.test(ch)) {
|
||||
if (ch === "0" && stream.eat("x")) {
|
||||
stream.eatWhile(/[0-9a-fA-F]/);
|
||||
return "number";
|
||||
}
|
||||
stream.eatWhile(/\d/);
|
||||
return "number";
|
||||
}
|
||||
|
||||
if (/\w/.test(ch)) {
|
||||
stream.eatWhile(/\w/);
|
||||
if (stream.eat(":")) {
|
||||
return 'tag';
|
||||
}
|
||||
cur = stream.current().toLowerCase();
|
||||
style = registers[cur];
|
||||
return style || null;
|
||||
}
|
||||
|
||||
for (var i = 0; i < custom.length; i++) {
|
||||
style = custom[i](ch, stream, state);
|
||||
if (style) {
|
||||
return style;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
lineComment: lineCommentStartSymbol,
|
||||
blockCommentStart: "/*",
|
||||
blockCommentEnd: "*/"
|
||||
};
|
||||
});
|
||||
@@ -1,68 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Gas mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="gas.js"></script>
|
||||
<style>.CodeMirror {border: 2px inset #dee;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Gas</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Gas mode</h2>
|
||||
<form>
|
||||
<textarea id="code" name="code">
|
||||
.syntax unified
|
||||
.global main
|
||||
|
||||
/*
|
||||
* A
|
||||
* multi-line
|
||||
* comment.
|
||||
*/
|
||||
|
||||
@ A single line comment.
|
||||
|
||||
main:
|
||||
push {sp, lr}
|
||||
ldr r0, =message
|
||||
bl puts
|
||||
mov r0, #0
|
||||
pop {sp, pc}
|
||||
|
||||
message:
|
||||
.asciz "Hello world!<br />"
|
||||
</textarea>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
mode: {name: "gas", architecture: "ARMv6"},
|
||||
});
|
||||
</script>
|
||||
|
||||
<p>Handles AT&T assembler syntax (more specifically this handles
|
||||
the GNU Assembler (gas) syntax.)
|
||||
It takes a single optional configuration parameter:
|
||||
<code>architecture</code>, which can be one of <code>"ARM"</code>,
|
||||
<code>"ARMv6"</code> or <code>"x86"</code>.
|
||||
Including the parameter adds syntax for the registers and special
|
||||
directives for the supplied architecture.
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-gas</code></p>
|
||||
</article>
|
||||
@@ -1,96 +0,0 @@
|
||||
CodeMirror.defineMode("gfm", function(config) {
|
||||
var codeDepth = 0;
|
||||
function blankLine(state) {
|
||||
state.code = false;
|
||||
return null;
|
||||
}
|
||||
var gfmOverlay = {
|
||||
startState: function() {
|
||||
return {
|
||||
code: false,
|
||||
codeBlock: false,
|
||||
ateSpace: false
|
||||
};
|
||||
},
|
||||
copyState: function(s) {
|
||||
return {
|
||||
code: s.code,
|
||||
codeBlock: s.codeBlock,
|
||||
ateSpace: s.ateSpace
|
||||
};
|
||||
},
|
||||
token: function(stream, state) {
|
||||
// Hack to prevent formatting override inside code blocks (block and inline)
|
||||
if (state.codeBlock) {
|
||||
if (stream.match(/^```/)) {
|
||||
state.codeBlock = false;
|
||||
return null;
|
||||
}
|
||||
stream.skipToEnd();
|
||||
return null;
|
||||
}
|
||||
if (stream.sol()) {
|
||||
state.code = false;
|
||||
}
|
||||
if (stream.sol() && stream.match(/^```/)) {
|
||||
stream.skipToEnd();
|
||||
state.codeBlock = true;
|
||||
return null;
|
||||
}
|
||||
// If this block is changed, it may need to be updated in Markdown mode
|
||||
if (stream.peek() === '`') {
|
||||
stream.next();
|
||||
var before = stream.pos;
|
||||
stream.eatWhile('`');
|
||||
var difference = 1 + stream.pos - before;
|
||||
if (!state.code) {
|
||||
codeDepth = difference;
|
||||
state.code = true;
|
||||
} else {
|
||||
if (difference === codeDepth) { // Must be exact
|
||||
state.code = false;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
} else if (state.code) {
|
||||
stream.next();
|
||||
return null;
|
||||
}
|
||||
// Check if space. If so, links can be formatted later on
|
||||
if (stream.eatSpace()) {
|
||||
state.ateSpace = true;
|
||||
return null;
|
||||
}
|
||||
if (stream.sol() || state.ateSpace) {
|
||||
state.ateSpace = false;
|
||||
if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?:[a-f0-9]{7,40}\b)/)) {
|
||||
// User/Project@SHA
|
||||
// User@SHA
|
||||
// SHA
|
||||
return "link";
|
||||
} else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
|
||||
// User/Project#Num
|
||||
// User#Num
|
||||
// #Num
|
||||
return "link";
|
||||
}
|
||||
}
|
||||
if (stream.match(/^((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i)) {
|
||||
// URLs
|
||||
// Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
|
||||
// And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
|
||||
return "link";
|
||||
}
|
||||
stream.next();
|
||||
return null;
|
||||
},
|
||||
blankLine: blankLine
|
||||
};
|
||||
CodeMirror.defineMIME("gfmBase", {
|
||||
name: "markdown",
|
||||
underscoresBreakWords: false,
|
||||
taskLists: true,
|
||||
fencedCodeBlocks: true
|
||||
});
|
||||
return CodeMirror.overlayMode(CodeMirror.getMode(config, "gfmBase"), gfmOverlay);
|
||||
}, "markdown");
|
||||
@@ -1,82 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: GFM mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/mode/overlay.js"></script>
|
||||
<script src="../xml/xml.js"></script>
|
||||
<script src="../markdown/markdown.js"></script>
|
||||
<script src="gfm.js"></script>
|
||||
<script src="../javascript/javascript.js"></script>
|
||||
<script src="../css/css.js"></script>
|
||||
<script src="../htmlmixed/htmlmixed.js"></script>
|
||||
<script src="../clike/clike.js"></script>
|
||||
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">GFM</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>GFM mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
GitHub Flavored Markdown
|
||||
========================
|
||||
|
||||
Everything from markdown plus GFM features:
|
||||
|
||||
## URL autolinking
|
||||
|
||||
Underscores_are_allowed_between_words.
|
||||
|
||||
## Fenced code blocks (and syntax highlighting)
|
||||
|
||||
```javascript
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
console.log(items[i], i); // log them
|
||||
}
|
||||
```
|
||||
|
||||
## Task Lists
|
||||
|
||||
- [ ] Incomplete task list item
|
||||
- [x] **Completed** task list item
|
||||
|
||||
## A bit of GitHub spice
|
||||
|
||||
* SHA: be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
|
||||
* User@SHA ref: mojombo@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
|
||||
* User/Project@SHA: mojombo/god@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
|
||||
* \#Num: #1
|
||||
* User/#Num: mojombo#1
|
||||
* User/Project#Num: mojombo/god#1
|
||||
|
||||
See http://github.github.com/github-flavored-markdown/.
|
||||
|
||||
</textarea></form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
mode: 'gfm',
|
||||
lineNumbers: true,
|
||||
theme: "default"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p>Optionally depends on other modes for properly highlighted code blocks.</p>
|
||||
|
||||
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#gfm_*">normal</a>, <a href="../../test/index.html#verbose,gfm_*">verbose</a>.</p>
|
||||
|
||||
</article>
|
||||
@@ -1,112 +0,0 @@
|
||||
(function() {
|
||||
var mode = CodeMirror.getMode({tabSize: 4}, "gfm");
|
||||
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
|
||||
|
||||
MT("emInWordAsterisk",
|
||||
"foo[em *bar*]hello");
|
||||
|
||||
MT("emInWordUnderscore",
|
||||
"foo_bar_hello");
|
||||
|
||||
MT("emStrongUnderscore",
|
||||
"[strong __][em&strong _foo__][em _] bar");
|
||||
|
||||
MT("fencedCodeBlocks",
|
||||
"[comment ```]",
|
||||
"[comment foo]",
|
||||
"",
|
||||
"[comment ```]",
|
||||
"bar");
|
||||
|
||||
MT("fencedCodeBlockModeSwitching",
|
||||
"[comment ```javascript]",
|
||||
"[variable foo]",
|
||||
"",
|
||||
"[comment ```]",
|
||||
"bar");
|
||||
|
||||
MT("taskListAsterisk",
|
||||
"[variable-2 * []] foo]", // Invalid; must have space or x between []
|
||||
"[variable-2 * [ ]]bar]", // Invalid; must have space after ]
|
||||
"[variable-2 * [x]]hello]", // Invalid; must have space after ]
|
||||
"[variable-2 * ][meta [ ]]][variable-2 [world]]]", // Valid; tests reference style links
|
||||
" [variable-3 * ][property [x]]][variable-3 foo]"); // Valid; can be nested
|
||||
|
||||
MT("taskListPlus",
|
||||
"[variable-2 + []] foo]", // Invalid; must have space or x between []
|
||||
"[variable-2 + [ ]]bar]", // Invalid; must have space after ]
|
||||
"[variable-2 + [x]]hello]", // Invalid; must have space after ]
|
||||
"[variable-2 + ][meta [ ]]][variable-2 [world]]]", // Valid; tests reference style links
|
||||
" [variable-3 + ][property [x]]][variable-3 foo]"); // Valid; can be nested
|
||||
|
||||
MT("taskListDash",
|
||||
"[variable-2 - []] foo]", // Invalid; must have space or x between []
|
||||
"[variable-2 - [ ]]bar]", // Invalid; must have space after ]
|
||||
"[variable-2 - [x]]hello]", // Invalid; must have space after ]
|
||||
"[variable-2 - ][meta [ ]]][variable-2 [world]]]", // Valid; tests reference style links
|
||||
" [variable-3 - ][property [x]]][variable-3 foo]"); // Valid; can be nested
|
||||
|
||||
MT("taskListNumber",
|
||||
"[variable-2 1. []] foo]", // Invalid; must have space or x between []
|
||||
"[variable-2 2. [ ]]bar]", // Invalid; must have space after ]
|
||||
"[variable-2 3. [x]]hello]", // Invalid; must have space after ]
|
||||
"[variable-2 4. ][meta [ ]]][variable-2 [world]]]", // Valid; tests reference style links
|
||||
" [variable-3 1. ][property [x]]][variable-3 foo]"); // Valid; can be nested
|
||||
|
||||
MT("SHA",
|
||||
"foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar");
|
||||
|
||||
MT("shortSHA",
|
||||
"foo [link be6a8cc] bar");
|
||||
|
||||
MT("tooShortSHA",
|
||||
"foo be6a8c bar");
|
||||
|
||||
MT("longSHA",
|
||||
"foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar");
|
||||
|
||||
MT("badSHA",
|
||||
"foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar");
|
||||
|
||||
MT("userSHA",
|
||||
"foo [link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] hello");
|
||||
|
||||
MT("userProjectSHA",
|
||||
"foo [link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] world");
|
||||
|
||||
MT("num",
|
||||
"foo [link #1] bar");
|
||||
|
||||
MT("badNum",
|
||||
"foo #1bar hello");
|
||||
|
||||
MT("userNum",
|
||||
"foo [link bar#1] hello");
|
||||
|
||||
MT("userProjectNum",
|
||||
"foo [link bar/hello#1] world");
|
||||
|
||||
MT("vanillaLink",
|
||||
"foo [link http://www.example.com/] bar");
|
||||
|
||||
MT("vanillaLinkPunctuation",
|
||||
"foo [link http://www.example.com/]. bar");
|
||||
|
||||
MT("vanillaLinkExtension",
|
||||
"foo [link http://www.example.com/index.html] bar");
|
||||
|
||||
MT("notALink",
|
||||
"[comment ```css]",
|
||||
"[tag foo] {[property color][operator :][keyword black];}",
|
||||
"[comment ```][link http://www.example.com/]");
|
||||
|
||||
MT("notALink",
|
||||
"[comment ``foo `bar` http://www.example.com/``] hello");
|
||||
|
||||
MT("notALink",
|
||||
"[comment `foo]",
|
||||
"[link http://www.example.com/]",
|
||||
"[comment `foo]",
|
||||
"",
|
||||
"[link http://www.example.com/]");
|
||||
})();
|
||||
168
applications/admin/static/codemirror/mode/go/go.js
vendored
168
applications/admin/static/codemirror/mode/go/go.js
vendored
@@ -1,168 +0,0 @@
|
||||
CodeMirror.defineMode("go", function(config) {
|
||||
var indentUnit = config.indentUnit;
|
||||
|
||||
var keywords = {
|
||||
"break":true, "case":true, "chan":true, "const":true, "continue":true,
|
||||
"default":true, "defer":true, "else":true, "fallthrough":true, "for":true,
|
||||
"func":true, "go":true, "goto":true, "if":true, "import":true,
|
||||
"interface":true, "map":true, "package":true, "range":true, "return":true,
|
||||
"select":true, "struct":true, "switch":true, "type":true, "var":true,
|
||||
"bool":true, "byte":true, "complex64":true, "complex128":true,
|
||||
"float32":true, "float64":true, "int8":true, "int16":true, "int32":true,
|
||||
"int64":true, "string":true, "uint8":true, "uint16":true, "uint32":true,
|
||||
"uint64":true, "int":true, "uint":true, "uintptr":true
|
||||
};
|
||||
|
||||
var atoms = {
|
||||
"true":true, "false":true, "iota":true, "nil":true, "append":true,
|
||||
"cap":true, "close":true, "complex":true, "copy":true, "imag":true,
|
||||
"len":true, "make":true, "new":true, "panic":true, "print":true,
|
||||
"println":true, "real":true, "recover":true
|
||||
};
|
||||
|
||||
var isOperatorChar = /[+\-*&^%:=<>!|\/]/;
|
||||
|
||||
var curPunc;
|
||||
|
||||
function tokenBase(stream, state) {
|
||||
var ch = stream.next();
|
||||
if (ch == '"' || ch == "'" || ch == "`") {
|
||||
state.tokenize = tokenString(ch);
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
if (/[\d\.]/.test(ch)) {
|
||||
if (ch == ".") {
|
||||
stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/);
|
||||
} else if (ch == "0") {
|
||||
stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);
|
||||
} else {
|
||||
stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/);
|
||||
}
|
||||
return "number";
|
||||
}
|
||||
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
|
||||
curPunc = ch;
|
||||
return null;
|
||||
}
|
||||
if (ch == "/") {
|
||||
if (stream.eat("*")) {
|
||||
state.tokenize = tokenComment;
|
||||
return tokenComment(stream, state);
|
||||
}
|
||||
if (stream.eat("/")) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
}
|
||||
if (isOperatorChar.test(ch)) {
|
||||
stream.eatWhile(isOperatorChar);
|
||||
return "operator";
|
||||
}
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
var cur = stream.current();
|
||||
if (keywords.propertyIsEnumerable(cur)) {
|
||||
if (cur == "case" || cur == "default") curPunc = "case";
|
||||
return "keyword";
|
||||
}
|
||||
if (atoms.propertyIsEnumerable(cur)) return "atom";
|
||||
return "variable";
|
||||
}
|
||||
|
||||
function tokenString(quote) {
|
||||
return function(stream, state) {
|
||||
var escaped = false, next, end = false;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == quote && !escaped) {end = true; break;}
|
||||
escaped = !escaped && next == "\\";
|
||||
}
|
||||
if (end || !(escaped || quote == "`"))
|
||||
state.tokenize = tokenBase;
|
||||
return "string";
|
||||
};
|
||||
}
|
||||
|
||||
function tokenComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
while (ch = stream.next()) {
|
||||
if (ch == "/" && maybeEnd) {
|
||||
state.tokenize = tokenBase;
|
||||
break;
|
||||
}
|
||||
maybeEnd = (ch == "*");
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function Context(indented, column, type, align, prev) {
|
||||
this.indented = indented;
|
||||
this.column = column;
|
||||
this.type = type;
|
||||
this.align = align;
|
||||
this.prev = prev;
|
||||
}
|
||||
function pushContext(state, col, type) {
|
||||
return state.context = new Context(state.indented, col, type, null, state.context);
|
||||
}
|
||||
function popContext(state) {
|
||||
var t = state.context.type;
|
||||
if (t == ")" || t == "]" || t == "}")
|
||||
state.indented = state.context.indented;
|
||||
return state.context = state.context.prev;
|
||||
}
|
||||
|
||||
// Interface
|
||||
|
||||
return {
|
||||
startState: function(basecolumn) {
|
||||
return {
|
||||
tokenize: null,
|
||||
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
|
||||
indented: 0,
|
||||
startOfLine: true
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
var ctx = state.context;
|
||||
if (stream.sol()) {
|
||||
if (ctx.align == null) ctx.align = false;
|
||||
state.indented = stream.indentation();
|
||||
state.startOfLine = true;
|
||||
if (ctx.type == "case") ctx.type = "}";
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
curPunc = null;
|
||||
var style = (state.tokenize || tokenBase)(stream, state);
|
||||
if (style == "comment") return style;
|
||||
if (ctx.align == null) ctx.align = true;
|
||||
|
||||
if (curPunc == "{") pushContext(state, stream.column(), "}");
|
||||
else if (curPunc == "[") pushContext(state, stream.column(), "]");
|
||||
else if (curPunc == "(") pushContext(state, stream.column(), ")");
|
||||
else if (curPunc == "case") ctx.type = "case";
|
||||
else if (curPunc == "}" && ctx.type == "}") ctx = popContext(state);
|
||||
else if (curPunc == ctx.type) popContext(state);
|
||||
state.startOfLine = false;
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function(state, textAfter) {
|
||||
if (state.tokenize != tokenBase && state.tokenize != null) return 0;
|
||||
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
|
||||
if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) {
|
||||
state.context.type = "}";
|
||||
return ctx.indented;
|
||||
}
|
||||
var closing = firstChar == ctx.type;
|
||||
if (ctx.align) return ctx.column + (closing ? 0 : 1);
|
||||
else return ctx.indented + (closing ? 0 : indentUnit);
|
||||
},
|
||||
|
||||
electricChars: "{}:",
|
||||
blockCommentStart: "/*",
|
||||
blockCommentEnd: "*/",
|
||||
lineComment: "//"
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-go", "go");
|
||||
@@ -1,85 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Go mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<link rel="stylesheet" href="../../theme/elegant.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/edit/matchbrackets.js"></script>
|
||||
<script src="go.js"></script>
|
||||
<style>.CodeMirror {border:1px solid #999; background:#ffc}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Go</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Go mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
// Prime Sieve in Go.
|
||||
// Taken from the Go specification.
|
||||
// Copyright © The Go Authors.
|
||||
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Send the sequence 2, 3, 4, ... to channel 'ch'.
|
||||
func generate(ch chan<- int) {
|
||||
for i := 2; ; i++ {
|
||||
ch <- i // Send 'i' to channel 'ch'
|
||||
}
|
||||
}
|
||||
|
||||
// Copy the values from channel 'src' to channel 'dst',
|
||||
// removing those divisible by 'prime'.
|
||||
func filter(src <-chan int, dst chan<- int, prime int) {
|
||||
for i := range src { // Loop over values received from 'src'.
|
||||
if i%prime != 0 {
|
||||
dst <- i // Send 'i' to channel 'dst'.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The prime sieve: Daisy-chain filter processes together.
|
||||
func sieve() {
|
||||
ch := make(chan int) // Create a new channel.
|
||||
go generate(ch) // Start generate() as a subprocess.
|
||||
for {
|
||||
prime := <-ch
|
||||
fmt.Print(prime, "\n")
|
||||
ch1 := make(chan int)
|
||||
go filter(ch, ch1, prime)
|
||||
ch = ch1
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
sieve()
|
||||
}
|
||||
</textarea></form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
theme: "elegant",
|
||||
matchBrackets: true,
|
||||
indentUnit: 8,
|
||||
tabSize: 8,
|
||||
indentWithTabs: true,
|
||||
mode: "text/x-go"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME type:</strong> <code>text/x-go</code></p>
|
||||
</article>
|
||||
@@ -1,211 +0,0 @@
|
||||
CodeMirror.defineMode("groovy", function(config) {
|
||||
function words(str) {
|
||||
var obj = {}, words = str.split(" ");
|
||||
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
|
||||
return obj;
|
||||
}
|
||||
var keywords = words(
|
||||
"abstract as assert boolean break byte case catch char class const continue def default " +
|
||||
"do double else enum extends final finally float for goto if implements import in " +
|
||||
"instanceof int interface long native new package private protected public return " +
|
||||
"short static strictfp super switch synchronized threadsafe throw throws transient " +
|
||||
"try void volatile while");
|
||||
var blockKeywords = words("catch class do else finally for if switch try while enum interface def");
|
||||
var atoms = words("null true false this");
|
||||
|
||||
var curPunc;
|
||||
function tokenBase(stream, state) {
|
||||
var ch = stream.next();
|
||||
if (ch == '"' || ch == "'") {
|
||||
return startString(ch, stream, state);
|
||||
}
|
||||
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
|
||||
curPunc = ch;
|
||||
return null;
|
||||
}
|
||||
if (/\d/.test(ch)) {
|
||||
stream.eatWhile(/[\w\.]/);
|
||||
if (stream.eat(/eE/)) { stream.eat(/\+\-/); stream.eatWhile(/\d/); }
|
||||
return "number";
|
||||
}
|
||||
if (ch == "/") {
|
||||
if (stream.eat("*")) {
|
||||
state.tokenize.push(tokenComment);
|
||||
return tokenComment(stream, state);
|
||||
}
|
||||
if (stream.eat("/")) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
if (expectExpression(state.lastToken)) {
|
||||
return startString(ch, stream, state);
|
||||
}
|
||||
}
|
||||
if (ch == "-" && stream.eat(">")) {
|
||||
curPunc = "->";
|
||||
return null;
|
||||
}
|
||||
if (/[+\-*&%=<>!?|\/~]/.test(ch)) {
|
||||
stream.eatWhile(/[+\-*&%=<>|~]/);
|
||||
return "operator";
|
||||
}
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
if (ch == "@") { stream.eatWhile(/[\w\$_\.]/); return "meta"; }
|
||||
if (state.lastToken == ".") return "property";
|
||||
if (stream.eat(":")) { curPunc = "proplabel"; return "property"; }
|
||||
var cur = stream.current();
|
||||
if (atoms.propertyIsEnumerable(cur)) { return "atom"; }
|
||||
if (keywords.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "keyword";
|
||||
}
|
||||
return "variable";
|
||||
}
|
||||
tokenBase.isBase = true;
|
||||
|
||||
function startString(quote, stream, state) {
|
||||
var tripleQuoted = false;
|
||||
if (quote != "/" && stream.eat(quote)) {
|
||||
if (stream.eat(quote)) tripleQuoted = true;
|
||||
else return "string";
|
||||
}
|
||||
function t(stream, state) {
|
||||
var escaped = false, next, end = !tripleQuoted;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == quote && !escaped) {
|
||||
if (!tripleQuoted) { break; }
|
||||
if (stream.match(quote + quote)) { end = true; break; }
|
||||
}
|
||||
if (quote == '"' && next == "$" && !escaped && stream.eat("{")) {
|
||||
state.tokenize.push(tokenBaseUntilBrace());
|
||||
return "string";
|
||||
}
|
||||
escaped = !escaped && next == "\\";
|
||||
}
|
||||
if (end) state.tokenize.pop();
|
||||
return "string";
|
||||
}
|
||||
state.tokenize.push(t);
|
||||
return t(stream, state);
|
||||
}
|
||||
|
||||
function tokenBaseUntilBrace() {
|
||||
var depth = 1;
|
||||
function t(stream, state) {
|
||||
if (stream.peek() == "}") {
|
||||
depth--;
|
||||
if (depth == 0) {
|
||||
state.tokenize.pop();
|
||||
return state.tokenize[state.tokenize.length-1](stream, state);
|
||||
}
|
||||
} else if (stream.peek() == "{") {
|
||||
depth++;
|
||||
}
|
||||
return tokenBase(stream, state);
|
||||
}
|
||||
t.isBase = true;
|
||||
return t;
|
||||
}
|
||||
|
||||
function tokenComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
while (ch = stream.next()) {
|
||||
if (ch == "/" && maybeEnd) {
|
||||
state.tokenize.pop();
|
||||
break;
|
||||
}
|
||||
maybeEnd = (ch == "*");
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function expectExpression(last) {
|
||||
return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) ||
|
||||
last == "newstatement" || last == "keyword" || last == "proplabel";
|
||||
}
|
||||
|
||||
function Context(indented, column, type, align, prev) {
|
||||
this.indented = indented;
|
||||
this.column = column;
|
||||
this.type = type;
|
||||
this.align = align;
|
||||
this.prev = prev;
|
||||
}
|
||||
function pushContext(state, col, type) {
|
||||
return state.context = new Context(state.indented, col, type, null, state.context);
|
||||
}
|
||||
function popContext(state) {
|
||||
var t = state.context.type;
|
||||
if (t == ")" || t == "]" || t == "}")
|
||||
state.indented = state.context.indented;
|
||||
return state.context = state.context.prev;
|
||||
}
|
||||
|
||||
// Interface
|
||||
|
||||
return {
|
||||
startState: function(basecolumn) {
|
||||
return {
|
||||
tokenize: [tokenBase],
|
||||
context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false),
|
||||
indented: 0,
|
||||
startOfLine: true,
|
||||
lastToken: null
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
var ctx = state.context;
|
||||
if (stream.sol()) {
|
||||
if (ctx.align == null) ctx.align = false;
|
||||
state.indented = stream.indentation();
|
||||
state.startOfLine = true;
|
||||
// Automatic semicolon insertion
|
||||
if (ctx.type == "statement" && !expectExpression(state.lastToken)) {
|
||||
popContext(state); ctx = state.context;
|
||||
}
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
curPunc = null;
|
||||
var style = state.tokenize[state.tokenize.length-1](stream, state);
|
||||
if (style == "comment") return style;
|
||||
if (ctx.align == null) ctx.align = true;
|
||||
|
||||
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
|
||||
// Handle indentation for {x -> \n ... }
|
||||
else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") {
|
||||
popContext(state);
|
||||
state.context.align = false;
|
||||
}
|
||||
else if (curPunc == "{") pushContext(state, stream.column(), "}");
|
||||
else if (curPunc == "[") pushContext(state, stream.column(), "]");
|
||||
else if (curPunc == "(") pushContext(state, stream.column(), ")");
|
||||
else if (curPunc == "}") {
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
if (ctx.type == "}") ctx = popContext(state);
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
}
|
||||
else if (curPunc == ctx.type) popContext(state);
|
||||
else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
|
||||
pushContext(state, stream.column(), "statement");
|
||||
state.startOfLine = false;
|
||||
state.lastToken = curPunc || style;
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function(state, textAfter) {
|
||||
if (!state.tokenize[state.tokenize.length-1].isBase) return 0;
|
||||
var firstChar = textAfter && textAfter.charAt(0), ctx = state.context;
|
||||
if (ctx.type == "statement" && !expectExpression(state.lastToken)) ctx = ctx.prev;
|
||||
var closing = firstChar == ctx.type;
|
||||
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit);
|
||||
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
|
||||
else return ctx.indented + (closing ? 0 : config.indentUnit);
|
||||
},
|
||||
|
||||
electricChars: "{}",
|
||||
fold: "brace"
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-groovy", "groovy");
|
||||
@@ -1,84 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Groovy mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/edit/matchbrackets.js"></script>
|
||||
<script src="groovy.js"></script>
|
||||
<style>.CodeMirror {border-top: 1px solid #500; border-bottom: 1px solid #500;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Groovy</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Groovy mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
//Pattern for groovy script
|
||||
def p = ~/.*\.groovy/
|
||||
new File( 'd:\\scripts' ).eachFileMatch(p) {f ->
|
||||
// imports list
|
||||
def imports = []
|
||||
f.eachLine {
|
||||
// condition to detect an import instruction
|
||||
ln -> if ( ln =~ '^import .*' ) {
|
||||
imports << "${ln - 'import '}"
|
||||
}
|
||||
}
|
||||
// print thmen
|
||||
if ( ! imports.empty ) {
|
||||
println f
|
||||
imports.each{ println " $it" }
|
||||
}
|
||||
}
|
||||
|
||||
/* Coin changer demo code from http://groovy.codehaus.org */
|
||||
|
||||
enum UsCoin {
|
||||
quarter(25), dime(10), nickel(5), penny(1)
|
||||
UsCoin(v) { value = v }
|
||||
final value
|
||||
}
|
||||
|
||||
enum OzzieCoin {
|
||||
fifty(50), twenty(20), ten(10), five(5)
|
||||
OzzieCoin(v) { value = v }
|
||||
final value
|
||||
}
|
||||
|
||||
def plural(word, count) {
|
||||
if (count == 1) return word
|
||||
word[-1] == 'y' ? word[0..-2] + "ies" : word + "s"
|
||||
}
|
||||
|
||||
def change(currency, amount) {
|
||||
currency.values().inject([]){ list, coin ->
|
||||
int count = amount / coin.value
|
||||
amount = amount % coin.value
|
||||
list += "$count ${plural(coin.toString(), count)}"
|
||||
}
|
||||
}
|
||||
</textarea></form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
mode: "text/x-groovy"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-groovy</code></p>
|
||||
</article>
|
||||
@@ -1,153 +0,0 @@
|
||||
(function() {
|
||||
"use strict";
|
||||
|
||||
// full haml mode. This handled embeded ruby and html fragments too
|
||||
CodeMirror.defineMode("haml", function(config) {
|
||||
var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"});
|
||||
var rubyMode = CodeMirror.getMode(config, "ruby");
|
||||
|
||||
function rubyInQuote(endQuote) {
|
||||
return function(stream, state) {
|
||||
var ch = stream.peek();
|
||||
if (ch == endQuote && state.rubyState.tokenize.length == 1) {
|
||||
// step out of ruby context as it seems to complete processing all the braces
|
||||
stream.next();
|
||||
state.tokenize = html;
|
||||
return "closeAttributeTag";
|
||||
} else {
|
||||
return ruby(stream, state);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function ruby(stream, state) {
|
||||
if (stream.match("-#")) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
return rubyMode.token(stream, state.rubyState);
|
||||
}
|
||||
|
||||
function html(stream, state) {
|
||||
var ch = stream.peek();
|
||||
|
||||
// handle haml declarations. All declarations that cant be handled here
|
||||
// will be passed to html mode
|
||||
if (state.previousToken.style == "comment" ) {
|
||||
if (state.indented > state.previousToken.indented) {
|
||||
stream.skipToEnd();
|
||||
return "commentLine";
|
||||
}
|
||||
}
|
||||
|
||||
if (state.startOfLine) {
|
||||
if (ch == "!" && stream.match("!!")) {
|
||||
stream.skipToEnd();
|
||||
return "tag";
|
||||
} else if (stream.match(/^%[\w:#\.]+=/)) {
|
||||
state.tokenize = ruby;
|
||||
return "hamlTag";
|
||||
} else if (stream.match(/^%[\w:]+/)) {
|
||||
return "hamlTag";
|
||||
} else if (ch == "/" ) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
}
|
||||
|
||||
if (state.startOfLine || state.previousToken.style == "hamlTag") {
|
||||
if ( ch == "#" || ch == ".") {
|
||||
stream.match(/[\w-#\.]*/);
|
||||
return "hamlAttribute";
|
||||
}
|
||||
}
|
||||
|
||||
// donot handle --> as valid ruby, make it HTML close comment instead
|
||||
if (state.startOfLine && !stream.match("-->", false) && (ch == "=" || ch == "-" )) {
|
||||
state.tokenize = ruby;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (state.previousToken.style == "hamlTag" ||
|
||||
state.previousToken.style == "closeAttributeTag" ||
|
||||
state.previousToken.style == "hamlAttribute") {
|
||||
if (ch == "(") {
|
||||
state.tokenize = rubyInQuote(")");
|
||||
return null;
|
||||
} else if (ch == "{") {
|
||||
state.tokenize = rubyInQuote("}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return htmlMode.token(stream, state.htmlState);
|
||||
}
|
||||
|
||||
return {
|
||||
// default to html mode
|
||||
startState: function() {
|
||||
var htmlState = htmlMode.startState();
|
||||
var rubyState = rubyMode.startState();
|
||||
return {
|
||||
htmlState: htmlState,
|
||||
rubyState: rubyState,
|
||||
indented: 0,
|
||||
previousToken: { style: null, indented: 0},
|
||||
tokenize: html
|
||||
};
|
||||
},
|
||||
|
||||
copyState: function(state) {
|
||||
return {
|
||||
htmlState : CodeMirror.copyState(htmlMode, state.htmlState),
|
||||
rubyState: CodeMirror.copyState(rubyMode, state.rubyState),
|
||||
indented: state.indented,
|
||||
previousToken: state.previousToken,
|
||||
tokenize: state.tokenize
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
if (stream.sol()) {
|
||||
state.indented = stream.indentation();
|
||||
state.startOfLine = true;
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
var style = state.tokenize(stream, state);
|
||||
state.startOfLine = false;
|
||||
// dont record comment line as we only want to measure comment line with
|
||||
// the opening comment block
|
||||
if (style && style != "commentLine") {
|
||||
state.previousToken = { style: style, indented: state.indented };
|
||||
}
|
||||
// if current state is ruby and the previous token is not `,` reset the
|
||||
// tokenize to html
|
||||
if (stream.eol() && state.tokenize == ruby) {
|
||||
stream.backUp(1);
|
||||
var ch = stream.peek();
|
||||
stream.next();
|
||||
if (ch && ch != ",") {
|
||||
state.tokenize = html;
|
||||
}
|
||||
}
|
||||
// reprocess some of the specific style tag when finish setting previousToken
|
||||
if (style == "hamlTag") {
|
||||
style = "tag";
|
||||
} else if (style == "commentLine") {
|
||||
style = "comment";
|
||||
} else if (style == "hamlAttribute") {
|
||||
style = "attribute";
|
||||
} else if (style == "closeAttributeTag") {
|
||||
style = null;
|
||||
}
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function(state) {
|
||||
return state.indented;
|
||||
}
|
||||
};
|
||||
}, "htmlmixed", "ruby");
|
||||
|
||||
CodeMirror.defineMIME("text/x-haml", "haml");
|
||||
})();
|
||||
@@ -1,79 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: HAML mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../xml/xml.js"></script>
|
||||
<script src="../htmlmixed/htmlmixed.js"></script>
|
||||
<script src="../javascript/javascript.js"></script>
|
||||
<script src="../ruby/ruby.js"></script>
|
||||
<script src="haml.js"></script>
|
||||
<style>.CodeMirror {background: #f8f8f8;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">HAML</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>HAML mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
!!!
|
||||
#content
|
||||
.left.column(title="title"){:href => "/hello", :test => "#{hello}_#{world}"}
|
||||
<!-- This is a comment -->
|
||||
%h2 Welcome to our site!
|
||||
%p= puts "HAML MODE"
|
||||
.right.column
|
||||
= render :partial => "sidebar"
|
||||
|
||||
.container
|
||||
.row
|
||||
.span8
|
||||
%h1.title= @page_title
|
||||
%p.title= @page_title
|
||||
%p
|
||||
/
|
||||
The same as HTML comment
|
||||
Hello multiline comment
|
||||
|
||||
-# haml comment
|
||||
This wont be displayed
|
||||
nor will this
|
||||
Date/Time:
|
||||
- now = DateTime.now
|
||||
%strong= now
|
||||
- if now > DateTime.parse("December 31, 2006")
|
||||
= "Happy new " + "year!"
|
||||
|
||||
%title
|
||||
= @title
|
||||
\= @title
|
||||
<h1>Title</h1>
|
||||
<h1 title="HELLO">
|
||||
Title
|
||||
</h1>
|
||||
</textarea></form>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
mode: "text/x-haml"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-haml</code>.</p>
|
||||
|
||||
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#haml_*">normal</a>, <a href="../../test/index.html#verbose,haml_*">verbose</a>.</p>
|
||||
|
||||
</article>
|
||||
@@ -1,94 +0,0 @@
|
||||
(function() {
|
||||
var mode = CodeMirror.getMode({tabSize: 4}, "haml");
|
||||
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
|
||||
|
||||
// Requires at least one media query
|
||||
MT("elementName",
|
||||
"[tag %h1] Hey There");
|
||||
|
||||
MT("oneElementPerLine",
|
||||
"[tag %h1] Hey There %h2");
|
||||
|
||||
MT("idSelector",
|
||||
"[tag %h1][attribute #test] Hey There");
|
||||
|
||||
MT("classSelector",
|
||||
"[tag %h1][attribute .hello] Hey There");
|
||||
|
||||
MT("docType",
|
||||
"[tag !!! XML]");
|
||||
|
||||
MT("comment",
|
||||
"[comment / Hello WORLD]");
|
||||
|
||||
MT("notComment",
|
||||
"[tag %h1] This is not a / comment ");
|
||||
|
||||
MT("attributes",
|
||||
"[tag %a]([variable title][operator =][string \"test\"]){[atom :title] [operator =>] [string \"test\"]}");
|
||||
|
||||
MT("htmlCode",
|
||||
"[tag <h1>]Title[tag </h1>]");
|
||||
|
||||
MT("rubyBlock",
|
||||
"[operator =][variable-2 @item]");
|
||||
|
||||
MT("selectorRubyBlock",
|
||||
"[tag %a.selector=] [variable-2 @item]");
|
||||
|
||||
MT("nestedRubyBlock",
|
||||
"[tag %a]",
|
||||
" [operator =][variable puts] [string \"test\"]");
|
||||
|
||||
MT("multilinePlaintext",
|
||||
"[tag %p]",
|
||||
" Hello,",
|
||||
" World");
|
||||
|
||||
MT("multilineRuby",
|
||||
"[tag %p]",
|
||||
" [comment -# this is a comment]",
|
||||
" [comment and this is a comment too]",
|
||||
" Date/Time",
|
||||
" [operator -] [variable now] [operator =] [tag DateTime][operator .][variable now]",
|
||||
" [tag %strong=] [variable now]",
|
||||
" [operator -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][variable parse]([string \"December 31, 2006\"])",
|
||||
" [operator =][string \"Happy\"]",
|
||||
" [operator =][string \"Belated\"]",
|
||||
" [operator =][string \"Birthday\"]");
|
||||
|
||||
MT("multilineComment",
|
||||
"[comment /]",
|
||||
" [comment Multiline]",
|
||||
" [comment Comment]");
|
||||
|
||||
MT("hamlComment",
|
||||
"[comment -# this is a comment]");
|
||||
|
||||
MT("multilineHamlComment",
|
||||
"[comment -# this is a comment]",
|
||||
" [comment and this is a comment too]");
|
||||
|
||||
MT("multilineHTMLComment",
|
||||
"[comment <!--]",
|
||||
" [comment what a comment]",
|
||||
" [comment -->]");
|
||||
|
||||
MT("hamlAfterRubyTag",
|
||||
"[attribute .block]",
|
||||
" [tag %strong=] [variable now]",
|
||||
" [attribute .test]",
|
||||
" [operator =][variable now]",
|
||||
" [attribute .right]");
|
||||
|
||||
MT("stretchedRuby",
|
||||
"[operator =] [variable puts] [string \"Hello\"],",
|
||||
" [string \"World\"]");
|
||||
|
||||
MT("interpolationInHashAttribute",
|
||||
//"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
|
||||
"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
|
||||
|
||||
MT("interpolationInHTMLAttribute",
|
||||
"[tag %div]([variable title][operator =][string \"#{][variable test][string }_#{][variable ting]()[string }\"]) Test");
|
||||
})();
|
||||
@@ -1,250 +0,0 @@
|
||||
CodeMirror.defineMode("haskell", function(_config, modeConfig) {
|
||||
|
||||
function switchState(source, setState, f) {
|
||||
setState(f);
|
||||
return f(source, setState);
|
||||
}
|
||||
|
||||
// These should all be Unicode extended, as per the Haskell 2010 report
|
||||
var smallRE = /[a-z_]/;
|
||||
var largeRE = /[A-Z]/;
|
||||
var digitRE = /[0-9]/;
|
||||
var hexitRE = /[0-9A-Fa-f]/;
|
||||
var octitRE = /[0-7]/;
|
||||
var idRE = /[a-z_A-Z0-9']/;
|
||||
var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:]/;
|
||||
var specialRE = /[(),;[\]`{}]/;
|
||||
var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer
|
||||
|
||||
function normal(source, setState) {
|
||||
if (source.eatWhile(whiteCharRE)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var ch = source.next();
|
||||
if (specialRE.test(ch)) {
|
||||
if (ch == '{' && source.eat('-')) {
|
||||
var t = "comment";
|
||||
if (source.eat('#')) {
|
||||
t = "meta";
|
||||
}
|
||||
return switchState(source, setState, ncomment(t, 1));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ch == '\'') {
|
||||
if (source.eat('\\')) {
|
||||
source.next(); // should handle other escapes here
|
||||
}
|
||||
else {
|
||||
source.next();
|
||||
}
|
||||
if (source.eat('\'')) {
|
||||
return "string";
|
||||
}
|
||||
return "error";
|
||||
}
|
||||
|
||||
if (ch == '"') {
|
||||
return switchState(source, setState, stringLiteral);
|
||||
}
|
||||
|
||||
if (largeRE.test(ch)) {
|
||||
source.eatWhile(idRE);
|
||||
if (source.eat('.')) {
|
||||
return "qualifier";
|
||||
}
|
||||
return "variable-2";
|
||||
}
|
||||
|
||||
if (smallRE.test(ch)) {
|
||||
source.eatWhile(idRE);
|
||||
return "variable";
|
||||
}
|
||||
|
||||
if (digitRE.test(ch)) {
|
||||
if (ch == '0') {
|
||||
if (source.eat(/[xX]/)) {
|
||||
source.eatWhile(hexitRE); // should require at least 1
|
||||
return "integer";
|
||||
}
|
||||
if (source.eat(/[oO]/)) {
|
||||
source.eatWhile(octitRE); // should require at least 1
|
||||
return "number";
|
||||
}
|
||||
}
|
||||
source.eatWhile(digitRE);
|
||||
var t = "number";
|
||||
if (source.eat('.')) {
|
||||
t = "number";
|
||||
source.eatWhile(digitRE); // should require at least 1
|
||||
}
|
||||
if (source.eat(/[eE]/)) {
|
||||
t = "number";
|
||||
source.eat(/[-+]/);
|
||||
source.eatWhile(digitRE); // should require at least 1
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
if (symbolRE.test(ch)) {
|
||||
if (ch == '-' && source.eat(/-/)) {
|
||||
source.eatWhile(/-/);
|
||||
if (!source.eat(symbolRE)) {
|
||||
source.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
}
|
||||
var t = "variable";
|
||||
if (ch == ':') {
|
||||
t = "variable-2";
|
||||
}
|
||||
source.eatWhile(symbolRE);
|
||||
return t;
|
||||
}
|
||||
|
||||
return "error";
|
||||
}
|
||||
|
||||
function ncomment(type, nest) {
|
||||
if (nest == 0) {
|
||||
return normal;
|
||||
}
|
||||
return function(source, setState) {
|
||||
var currNest = nest;
|
||||
while (!source.eol()) {
|
||||
var ch = source.next();
|
||||
if (ch == '{' && source.eat('-')) {
|
||||
++currNest;
|
||||
}
|
||||
else if (ch == '-' && source.eat('}')) {
|
||||
--currNest;
|
||||
if (currNest == 0) {
|
||||
setState(normal);
|
||||
return type;
|
||||
}
|
||||
}
|
||||
}
|
||||
setState(ncomment(type, currNest));
|
||||
return type;
|
||||
};
|
||||
}
|
||||
|
||||
function stringLiteral(source, setState) {
|
||||
while (!source.eol()) {
|
||||
var ch = source.next();
|
||||
if (ch == '"') {
|
||||
setState(normal);
|
||||
return "string";
|
||||
}
|
||||
if (ch == '\\') {
|
||||
if (source.eol() || source.eat(whiteCharRE)) {
|
||||
setState(stringGap);
|
||||
return "string";
|
||||
}
|
||||
if (source.eat('&')) {
|
||||
}
|
||||
else {
|
||||
source.next(); // should handle other escapes here
|
||||
}
|
||||
}
|
||||
}
|
||||
setState(normal);
|
||||
return "error";
|
||||
}
|
||||
|
||||
function stringGap(source, setState) {
|
||||
if (source.eat('\\')) {
|
||||
return switchState(source, setState, stringLiteral);
|
||||
}
|
||||
source.next();
|
||||
setState(normal);
|
||||
return "error";
|
||||
}
|
||||
|
||||
|
||||
var wellKnownWords = (function() {
|
||||
var wkw = {};
|
||||
function setType(t) {
|
||||
return function () {
|
||||
for (var i = 0; i < arguments.length; i++)
|
||||
wkw[arguments[i]] = t;
|
||||
};
|
||||
}
|
||||
|
||||
setType("keyword")(
|
||||
"case", "class", "data", "default", "deriving", "do", "else", "foreign",
|
||||
"if", "import", "in", "infix", "infixl", "infixr", "instance", "let",
|
||||
"module", "newtype", "of", "then", "type", "where", "_");
|
||||
|
||||
setType("keyword")(
|
||||
"\.\.", ":", "::", "=", "\\", "\"", "<-", "->", "@", "~", "=>");
|
||||
|
||||
setType("builtin")(
|
||||
"!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<=", "=<<",
|
||||
"==", ">", ">=", ">>", ">>=", "^", "^^", "||", "*", "**");
|
||||
|
||||
setType("builtin")(
|
||||
"Bool", "Bounded", "Char", "Double", "EQ", "Either", "Enum", "Eq",
|
||||
"False", "FilePath", "Float", "Floating", "Fractional", "Functor", "GT",
|
||||
"IO", "IOError", "Int", "Integer", "Integral", "Just", "LT", "Left",
|
||||
"Maybe", "Monad", "Nothing", "Num", "Ord", "Ordering", "Rational", "Read",
|
||||
"ReadS", "Real", "RealFloat", "RealFrac", "Right", "Show", "ShowS",
|
||||
"String", "True");
|
||||
|
||||
setType("builtin")(
|
||||
"abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf",
|
||||
"asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling",
|
||||
"compare", "concat", "concatMap", "const", "cos", "cosh", "curry",
|
||||
"cycle", "decodeFloat", "div", "divMod", "drop", "dropWhile", "either",
|
||||
"elem", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
|
||||
"enumFromTo", "error", "even", "exp", "exponent", "fail", "filter",
|
||||
"flip", "floatDigits", "floatRadix", "floatRange", "floor", "fmap",
|
||||
"foldl", "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger",
|
||||
"fromIntegral", "fromRational", "fst", "gcd", "getChar", "getContents",
|
||||
"getLine", "head", "id", "init", "interact", "ioError", "isDenormalized",
|
||||
"isIEEE", "isInfinite", "isNaN", "isNegativeZero", "iterate", "last",
|
||||
"lcm", "length", "lex", "lines", "log", "logBase", "lookup", "map",
|
||||
"mapM", "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound",
|
||||
"minimum", "mod", "negate", "not", "notElem", "null", "odd", "or",
|
||||
"otherwise", "pi", "pred", "print", "product", "properFraction",
|
||||
"putChar", "putStr", "putStrLn", "quot", "quotRem", "read", "readFile",
|
||||
"readIO", "readList", "readLn", "readParen", "reads", "readsPrec",
|
||||
"realToFrac", "recip", "rem", "repeat", "replicate", "return", "reverse",
|
||||
"round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq",
|
||||
"sequence", "sequence_", "show", "showChar", "showList", "showParen",
|
||||
"showString", "shows", "showsPrec", "significand", "signum", "sin",
|
||||
"sinh", "snd", "span", "splitAt", "sqrt", "subtract", "succ", "sum",
|
||||
"tail", "take", "takeWhile", "tan", "tanh", "toEnum", "toInteger",
|
||||
"toRational", "truncate", "uncurry", "undefined", "unlines", "until",
|
||||
"unwords", "unzip", "unzip3", "userError", "words", "writeFile", "zip",
|
||||
"zip3", "zipWith", "zipWith3");
|
||||
|
||||
var override = modeConfig.overrideKeywords;
|
||||
if (override) for (var word in override) if (override.hasOwnProperty(word))
|
||||
wkw[word] = override[word];
|
||||
|
||||
return wkw;
|
||||
})();
|
||||
|
||||
|
||||
|
||||
return {
|
||||
startState: function () { return { f: normal }; },
|
||||
copyState: function (s) { return { f: s.f }; },
|
||||
|
||||
token: function(stream, state) {
|
||||
var t = state.f(stream, function(s) { state.f = s; });
|
||||
var w = stream.current();
|
||||
return (w in wellKnownWords) ? wellKnownWords[w] : t;
|
||||
},
|
||||
|
||||
blockCommentStart: "{-",
|
||||
blockCommentEnd: "-}",
|
||||
lineComment: "--"
|
||||
};
|
||||
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-haskell", "haskell");
|
||||
@@ -1,73 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Haskell mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<link rel="stylesheet" href="../../theme/elegant.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../../addon/edit/matchbrackets.js"></script>
|
||||
<script src="haskell.js"></script>
|
||||
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Haskell</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Haskell mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
module UniquePerms (
|
||||
uniquePerms
|
||||
)
|
||||
where
|
||||
|
||||
-- | Find all unique permutations of a list where there might be duplicates.
|
||||
uniquePerms :: (Eq a) => [a] -> [[a]]
|
||||
uniquePerms = permBag . makeBag
|
||||
|
||||
-- | An unordered collection where duplicate values are allowed,
|
||||
-- but represented with a single value and a count.
|
||||
type Bag a = [(a, Int)]
|
||||
|
||||
makeBag :: (Eq a) => [a] -> Bag a
|
||||
makeBag [] = []
|
||||
makeBag (a:as) = mix a $ makeBag as
|
||||
where
|
||||
mix a [] = [(a,1)]
|
||||
mix a (bn@(b,n):bs) | a == b = (b,n+1):bs
|
||||
| otherwise = bn : mix a bs
|
||||
|
||||
permBag :: Bag a -> [[a]]
|
||||
permBag [] = [[]]
|
||||
permBag bs = concatMap (\(f,cs) -> map (f:) $ permBag cs) . oneOfEach $ bs
|
||||
where
|
||||
oneOfEach [] = []
|
||||
oneOfEach (an@(a,n):bs) =
|
||||
let bs' = if n == 1 then bs else (a,n-1):bs
|
||||
in (a,bs') : mapSnd (an:) (oneOfEach bs)
|
||||
|
||||
apSnd f (a,b) = (a, f b)
|
||||
mapSnd = map . apSnd
|
||||
</textarea></form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
theme: "elegant"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-haskell</code>.</p>
|
||||
</article>
|
||||
@@ -1,429 +0,0 @@
|
||||
CodeMirror.defineMode("haxe", function(config, parserConfig) {
|
||||
var indentUnit = config.indentUnit;
|
||||
|
||||
// Tokenizer
|
||||
|
||||
var keywords = function(){
|
||||
function kw(type) {return {type: type, style: "keyword"};}
|
||||
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
|
||||
var operator = kw("operator"), atom = {type: "atom", style: "atom"}, attribute = {type:"attribute", style: "attribute"};
|
||||
var type = kw("typedef");
|
||||
return {
|
||||
"if": A, "while": A, "else": B, "do": B, "try": B,
|
||||
"return": C, "break": C, "continue": C, "new": C, "throw": C,
|
||||
"var": kw("var"), "inline":attribute, "static": attribute, "using":kw("import"),
|
||||
"public": attribute, "private": attribute, "cast": kw("cast"), "import": kw("import"), "macro": kw("macro"),
|
||||
"function": kw("function"), "catch": kw("catch"), "untyped": kw("untyped"), "callback": kw("cb"),
|
||||
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
|
||||
"in": operator, "never": kw("property_access"), "trace":kw("trace"),
|
||||
"class": type, "enum":type, "interface":type, "typedef":type, "extends":type, "implements":type, "dynamic":type,
|
||||
"true": atom, "false": atom, "null": atom
|
||||
};
|
||||
}();
|
||||
|
||||
var isOperatorChar = /[+\-*&%=<>!?|]/;
|
||||
|
||||
function chain(stream, state, f) {
|
||||
state.tokenize = f;
|
||||
return f(stream, state);
|
||||
}
|
||||
|
||||
function nextUntilUnescaped(stream, end) {
|
||||
var escaped = false, next;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == end && !escaped)
|
||||
return false;
|
||||
escaped = !escaped && next == "\\";
|
||||
}
|
||||
return escaped;
|
||||
}
|
||||
|
||||
// Used as scratch variables to communicate multiple values without
|
||||
// consing up tons of objects.
|
||||
var type, content;
|
||||
function ret(tp, style, cont) {
|
||||
type = tp; content = cont;
|
||||
return style;
|
||||
}
|
||||
|
||||
function haxeTokenBase(stream, state) {
|
||||
var ch = stream.next();
|
||||
if (ch == '"' || ch == "'")
|
||||
return chain(stream, state, haxeTokenString(ch));
|
||||
else if (/[\[\]{}\(\),;\:\.]/.test(ch))
|
||||
return ret(ch);
|
||||
else if (ch == "0" && stream.eat(/x/i)) {
|
||||
stream.eatWhile(/[\da-f]/i);
|
||||
return ret("number", "number");
|
||||
}
|
||||
else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) {
|
||||
stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
|
||||
return ret("number", "number");
|
||||
}
|
||||
else if (state.reAllowed && (ch == "~" && stream.eat(/\//))) {
|
||||
nextUntilUnescaped(stream, "/");
|
||||
stream.eatWhile(/[gimsu]/);
|
||||
return ret("regexp", "string-2");
|
||||
}
|
||||
else if (ch == "/") {
|
||||
if (stream.eat("*")) {
|
||||
return chain(stream, state, haxeTokenComment);
|
||||
}
|
||||
else if (stream.eat("/")) {
|
||||
stream.skipToEnd();
|
||||
return ret("comment", "comment");
|
||||
}
|
||||
else {
|
||||
stream.eatWhile(isOperatorChar);
|
||||
return ret("operator", null, stream.current());
|
||||
}
|
||||
}
|
||||
else if (ch == "#") {
|
||||
stream.skipToEnd();
|
||||
return ret("conditional", "meta");
|
||||
}
|
||||
else if (ch == "@") {
|
||||
stream.eat(/:/);
|
||||
stream.eatWhile(/[\w_]/);
|
||||
return ret ("metadata", "meta");
|
||||
}
|
||||
else if (isOperatorChar.test(ch)) {
|
||||
stream.eatWhile(isOperatorChar);
|
||||
return ret("operator", null, stream.current());
|
||||
}
|
||||
else {
|
||||
var word;
|
||||
if(/[A-Z]/.test(ch))
|
||||
{
|
||||
stream.eatWhile(/[\w_<>]/);
|
||||
word = stream.current();
|
||||
return ret("type", "variable-3", word);
|
||||
}
|
||||
else
|
||||
{
|
||||
stream.eatWhile(/[\w_]/);
|
||||
var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
|
||||
return (known && state.kwAllowed) ? ret(known.type, known.style, word) :
|
||||
ret("variable", "variable", word);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function haxeTokenString(quote) {
|
||||
return function(stream, state) {
|
||||
if (!nextUntilUnescaped(stream, quote))
|
||||
state.tokenize = haxeTokenBase;
|
||||
return ret("string", "string");
|
||||
};
|
||||
}
|
||||
|
||||
function haxeTokenComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
while (ch = stream.next()) {
|
||||
if (ch == "/" && maybeEnd) {
|
||||
state.tokenize = haxeTokenBase;
|
||||
break;
|
||||
}
|
||||
maybeEnd = (ch == "*");
|
||||
}
|
||||
return ret("comment", "comment");
|
||||
}
|
||||
|
||||
// Parser
|
||||
|
||||
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
|
||||
|
||||
function HaxeLexical(indented, column, type, align, prev, info) {
|
||||
this.indented = indented;
|
||||
this.column = column;
|
||||
this.type = type;
|
||||
this.prev = prev;
|
||||
this.info = info;
|
||||
if (align != null) this.align = align;
|
||||
}
|
||||
|
||||
function inScope(state, varname) {
|
||||
for (var v = state.localVars; v; v = v.next)
|
||||
if (v.name == varname) return true;
|
||||
}
|
||||
|
||||
function parseHaxe(state, style, type, content, stream) {
|
||||
var cc = state.cc;
|
||||
// Communicate our context to the combinators.
|
||||
// (Less wasteful than consing up a hundred closures on every call.)
|
||||
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
|
||||
|
||||
if (!state.lexical.hasOwnProperty("align"))
|
||||
state.lexical.align = true;
|
||||
|
||||
while(true) {
|
||||
var combinator = cc.length ? cc.pop() : statement;
|
||||
if (combinator(type, content)) {
|
||||
while(cc.length && cc[cc.length - 1].lex)
|
||||
cc.pop()();
|
||||
if (cx.marked) return cx.marked;
|
||||
if (type == "variable" && inScope(state, content)) return "variable-2";
|
||||
if (type == "variable" && imported(state, content)) return "variable-3";
|
||||
return style;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function imported(state, typename)
|
||||
{
|
||||
if (/[a-z]/.test(typename.charAt(0)))
|
||||
return false;
|
||||
var len = state.importedtypes.length;
|
||||
for (var i = 0; i<len; i++)
|
||||
if(state.importedtypes[i]==typename) return true;
|
||||
}
|
||||
|
||||
|
||||
function registerimport(importname) {
|
||||
var state = cx.state;
|
||||
for (var t = state.importedtypes; t; t = t.next)
|
||||
if(t.name == importname) return;
|
||||
state.importedtypes = { name: importname, next: state.importedtypes };
|
||||
}
|
||||
// Combinator utils
|
||||
|
||||
var cx = {state: null, column: null, marked: null, cc: null};
|
||||
function pass() {
|
||||
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
|
||||
}
|
||||
function cont() {
|
||||
pass.apply(null, arguments);
|
||||
return true;
|
||||
}
|
||||
function register(varname) {
|
||||
var state = cx.state;
|
||||
if (state.context) {
|
||||
cx.marked = "def";
|
||||
for (var v = state.localVars; v; v = v.next)
|
||||
if (v.name == varname) return;
|
||||
state.localVars = {name: varname, next: state.localVars};
|
||||
}
|
||||
}
|
||||
|
||||
// Combinators
|
||||
|
||||
var defaultVars = {name: "this", next: null};
|
||||
function pushcontext() {
|
||||
if (!cx.state.context) cx.state.localVars = defaultVars;
|
||||
cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
|
||||
}
|
||||
function popcontext() {
|
||||
cx.state.localVars = cx.state.context.vars;
|
||||
cx.state.context = cx.state.context.prev;
|
||||
}
|
||||
function pushlex(type, info) {
|
||||
var result = function() {
|
||||
var state = cx.state;
|
||||
state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info);
|
||||
};
|
||||
result.lex = true;
|
||||
return result;
|
||||
}
|
||||
function poplex() {
|
||||
var state = cx.state;
|
||||
if (state.lexical.prev) {
|
||||
if (state.lexical.type == ")")
|
||||
state.indented = state.lexical.indented;
|
||||
state.lexical = state.lexical.prev;
|
||||
}
|
||||
}
|
||||
poplex.lex = true;
|
||||
|
||||
function expect(wanted) {
|
||||
return function(type) {
|
||||
if (type == wanted) return cont();
|
||||
else if (wanted == ";") return pass();
|
||||
else return cont(arguments.callee);
|
||||
};
|
||||
}
|
||||
|
||||
function statement(type) {
|
||||
if (type == "@") return cont(metadef);
|
||||
if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
|
||||
if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
|
||||
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
|
||||
if (type == "{") return cont(pushlex("}"), pushcontext, block, poplex, popcontext);
|
||||
if (type == ";") return cont();
|
||||
if (type == "attribute") return cont(maybeattribute);
|
||||
if (type == "function") return cont(functiondef);
|
||||
if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
|
||||
poplex, statement, poplex);
|
||||
if (type == "variable") return cont(pushlex("stat"), maybelabel);
|
||||
if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
|
||||
block, poplex, poplex);
|
||||
if (type == "case") return cont(expression, expect(":"));
|
||||
if (type == "default") return cont(expect(":"));
|
||||
if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
|
||||
statement, poplex, popcontext);
|
||||
if (type == "import") return cont(importdef, expect(";"));
|
||||
if (type == "typedef") return cont(typedef);
|
||||
return pass(pushlex("stat"), expression, expect(";"), poplex);
|
||||
}
|
||||
function expression(type) {
|
||||
if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
|
||||
if (type == "function") return cont(functiondef);
|
||||
if (type == "keyword c") return cont(maybeexpression);
|
||||
if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator);
|
||||
if (type == "operator") return cont(expression);
|
||||
if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
|
||||
if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
|
||||
return cont();
|
||||
}
|
||||
function maybeexpression(type) {
|
||||
if (type.match(/[;\}\)\],]/)) return pass();
|
||||
return pass(expression);
|
||||
}
|
||||
|
||||
function maybeoperator(type, value) {
|
||||
if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
|
||||
if (type == "operator" || type == ":") return cont(expression);
|
||||
if (type == ";") return;
|
||||
if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
|
||||
if (type == ".") return cont(property, maybeoperator);
|
||||
if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
|
||||
}
|
||||
|
||||
function maybeattribute(type) {
|
||||
if (type == "attribute") return cont(maybeattribute);
|
||||
if (type == "function") return cont(functiondef);
|
||||
if (type == "var") return cont(vardef1);
|
||||
}
|
||||
|
||||
function metadef(type) {
|
||||
if(type == ":") return cont(metadef);
|
||||
if(type == "variable") return cont(metadef);
|
||||
if(type == "(") return cont(pushlex(")"), commasep(metaargs, ")"), poplex, statement);
|
||||
}
|
||||
function metaargs(type) {
|
||||
if(type == "variable") return cont();
|
||||
}
|
||||
|
||||
function importdef (type, value) {
|
||||
if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
|
||||
else if(type == "variable" || type == "property" || type == ".") return cont(importdef);
|
||||
}
|
||||
|
||||
function typedef (type, value)
|
||||
{
|
||||
if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
|
||||
}
|
||||
|
||||
function maybelabel(type) {
|
||||
if (type == ":") return cont(poplex, statement);
|
||||
return pass(maybeoperator, expect(";"), poplex);
|
||||
}
|
||||
function property(type) {
|
||||
if (type == "variable") {cx.marked = "property"; return cont();}
|
||||
}
|
||||
function objprop(type) {
|
||||
if (type == "variable") cx.marked = "property";
|
||||
if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
|
||||
}
|
||||
function commasep(what, end) {
|
||||
function proceed(type) {
|
||||
if (type == ",") return cont(what, proceed);
|
||||
if (type == end) return cont();
|
||||
return cont(expect(end));
|
||||
}
|
||||
return function(type) {
|
||||
if (type == end) return cont();
|
||||
else return pass(what, proceed);
|
||||
};
|
||||
}
|
||||
function block(type) {
|
||||
if (type == "}") return cont();
|
||||
return pass(statement, block);
|
||||
}
|
||||
function vardef1(type, value) {
|
||||
if (type == "variable"){register(value); return cont(typeuse, vardef2);}
|
||||
return cont();
|
||||
}
|
||||
function vardef2(type, value) {
|
||||
if (value == "=") return cont(expression, vardef2);
|
||||
if (type == ",") return cont(vardef1);
|
||||
}
|
||||
function forspec1(type, value) {
|
||||
if (type == "variable") {
|
||||
register(value);
|
||||
}
|
||||
return cont(pushlex(")"), pushcontext, forin, expression, poplex, statement, popcontext);
|
||||
}
|
||||
function forin(_type, value) {
|
||||
if (value == "in") return cont();
|
||||
}
|
||||
function functiondef(type, value) {
|
||||
if (type == "variable") {register(value); return cont(functiondef);}
|
||||
if (value == "new") return cont(functiondef);
|
||||
if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, typeuse, statement, popcontext);
|
||||
}
|
||||
function typeuse(type) {
|
||||
if(type == ":") return cont(typestring);
|
||||
}
|
||||
function typestring(type) {
|
||||
if(type == "type") return cont();
|
||||
if(type == "variable") return cont();
|
||||
if(type == "{") return cont(pushlex("}"), commasep(typeprop, "}"), poplex);
|
||||
}
|
||||
function typeprop(type) {
|
||||
if(type == "variable") return cont(typeuse);
|
||||
}
|
||||
function funarg(type, value) {
|
||||
if (type == "variable") {register(value); return cont(typeuse);}
|
||||
}
|
||||
|
||||
// Interface
|
||||
|
||||
return {
|
||||
startState: function(basecolumn) {
|
||||
var defaulttypes = ["Int", "Float", "String", "Void", "Std", "Bool", "Dynamic", "Array"];
|
||||
return {
|
||||
tokenize: haxeTokenBase,
|
||||
reAllowed: true,
|
||||
kwAllowed: true,
|
||||
cc: [],
|
||||
lexical: new HaxeLexical((basecolumn || 0) - indentUnit, 0, "block", false),
|
||||
localVars: parserConfig.localVars,
|
||||
importedtypes: defaulttypes,
|
||||
context: parserConfig.localVars && {vars: parserConfig.localVars},
|
||||
indented: 0
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
if (stream.sol()) {
|
||||
if (!state.lexical.hasOwnProperty("align"))
|
||||
state.lexical.align = false;
|
||||
state.indented = stream.indentation();
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
var style = state.tokenize(stream, state);
|
||||
if (type == "comment") return style;
|
||||
state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/));
|
||||
state.kwAllowed = type != '.';
|
||||
return parseHaxe(state, style, type, content, stream);
|
||||
},
|
||||
|
||||
indent: function(state, textAfter) {
|
||||
if (state.tokenize != haxeTokenBase) return 0;
|
||||
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
|
||||
if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
|
||||
var type = lexical.type, closing = firstChar == type;
|
||||
if (type == "vardef") return lexical.indented + 4;
|
||||
else if (type == "form" && firstChar == "{") return lexical.indented;
|
||||
else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
|
||||
else if (lexical.info == "switch" && !closing)
|
||||
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
|
||||
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
|
||||
else return lexical.indented + (closing ? 0 : indentUnit);
|
||||
},
|
||||
|
||||
electricChars: "{}"
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-haxe", "haxe");
|
||||
@@ -1,103 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Haxe mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="haxe.js"></script>
|
||||
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Haxe</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Haxe mode</h2>
|
||||
|
||||
|
||||
<div><textarea id="code" name="code">
|
||||
import one.two.Three;
|
||||
|
||||
@attr("test")
|
||||
class Foo<T> extends Three
|
||||
{
|
||||
public function new()
|
||||
{
|
||||
noFoo = 12;
|
||||
}
|
||||
|
||||
public static inline function doFoo(obj:{k:Int, l:Float}):Int
|
||||
{
|
||||
for(i in 0...10)
|
||||
{
|
||||
obj.k++;
|
||||
trace(i);
|
||||
var var1 = new Array();
|
||||
if(var1.length > 1)
|
||||
throw "Error";
|
||||
}
|
||||
// The following line should not be colored, the variable is scoped out
|
||||
var1;
|
||||
/* Multi line
|
||||
* Comment test
|
||||
*/
|
||||
return obj.k;
|
||||
}
|
||||
private function bar():Void
|
||||
{
|
||||
#if flash
|
||||
var t1:String = "1.21";
|
||||
#end
|
||||
try {
|
||||
doFoo({k:3, l:1.2});
|
||||
}
|
||||
catch (e : String) {
|
||||
trace(e);
|
||||
}
|
||||
var t2:Float = cast(3.2);
|
||||
var t3:haxe.Timer = new haxe.Timer();
|
||||
var t4 = {k:Std.int(t2), l:Std.parseFloat(t1)};
|
||||
var t5 = ~/123+.*$/i;
|
||||
doFoo(t4);
|
||||
untyped t1 = 4;
|
||||
bob = new Foo<Int>
|
||||
}
|
||||
public var okFoo(default, never):Float;
|
||||
var noFoo(getFoo, null):Int;
|
||||
function getFoo():Int {
|
||||
return noFoo;
|
||||
}
|
||||
|
||||
public var three:Int;
|
||||
}
|
||||
enum Color
|
||||
{
|
||||
red;
|
||||
green;
|
||||
blue;
|
||||
grey( v : Int );
|
||||
rgb (r:Int,g:Int,b:Int);
|
||||
}
|
||||
</textarea></div>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
indentUnit: 4,
|
||||
indentWithTabs: true
|
||||
});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-haxe</code>.</p>
|
||||
</article>
|
||||
@@ -58,8 +58,6 @@ CodeMirror.defineMode("htmlembedded", function(config, parserConfig) {
|
||||
};
|
||||
},
|
||||
|
||||
electricChars: "/{}:",
|
||||
|
||||
innerMode: function(state) {
|
||||
if (state.token == scriptingDispatch) return {state: state.scriptState, mode: scriptingMode};
|
||||
else return {state: state.htmlState, mode: htmlMixedMode};
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: Html Embedded Scripts mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../xml/xml.js"></script>
|
||||
<script src="../javascript/javascript.js"></script>
|
||||
<script src="../css/css.js"></script>
|
||||
<script src="../htmlmixed/htmlmixed.js"></script>
|
||||
<script src="htmlembedded.js"></script>
|
||||
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">Html Embedded Scripts</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>Html Embedded Scripts mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
<%
|
||||
function hello(who) {
|
||||
return "Hello " + who;
|
||||
}
|
||||
%>
|
||||
This is an example of EJS (embedded javascript)
|
||||
<p>The program says <%= hello("world") %>.</p>
|
||||
<script>
|
||||
alert("And here is some normal JS code"); // also colored
|
||||
</script>
|
||||
</textarea></form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
mode: "application/x-ejs",
|
||||
indentUnit: 4,
|
||||
indentWithTabs: true,
|
||||
enterMode: "keep",
|
||||
tabMode: "shift"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p>Mode for html embedded scripts like JSP and ASP.NET. Depends on HtmlMixed which in turn depends on
|
||||
JavaScript, CSS and XML.<br />Other dependancies include those of the scriping language chosen.</p>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>application/x-aspx</code> (ASP.NET),
|
||||
<code>application/x-ejs</code> (Embedded Javascript), <code>application/x-jsp</code> (JavaServer Pages)</p>
|
||||
</article>
|
||||
@@ -44,7 +44,7 @@ CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
|
||||
if (close > -1) stream.backUp(cur.length - close);
|
||||
else if (m = cur.match(/<\/?$/)) {
|
||||
stream.backUp(cur.length);
|
||||
if (!stream.match(pat, false)) stream.match(cur[0]);
|
||||
if (!stream.match(pat, false)) stream.match(cur);
|
||||
}
|
||||
return style;
|
||||
}
|
||||
@@ -93,8 +93,6 @@ CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
|
||||
return CodeMirror.Pass;
|
||||
},
|
||||
|
||||
electricChars: "/{}:",
|
||||
|
||||
innerMode: function(state) {
|
||||
return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
|
||||
}
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: HTML mixed mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="../xml/xml.js"></script>
|
||||
<script src="../javascript/javascript.js"></script>
|
||||
<script src="../css/css.js"></script>
|
||||
<script src="../vbscript/vbscript.js"></script>
|
||||
<script src="htmlmixed.js"></script>
|
||||
<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">HTML mixed</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>HTML mixed mode</h2>
|
||||
<form><textarea id="code" name="code">
|
||||
<html style="color: green">
|
||||
<!-- this is a comment -->
|
||||
<head>
|
||||
<title>Mixed HTML Example</title>
|
||||
<style type="text/css">
|
||||
h1 {font-family: comic sans; color: #f0f;}
|
||||
div {background: yellow !important;}
|
||||
body {
|
||||
max-width: 50em;
|
||||
margin: 1em 2em 1em 5em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Mixed HTML Example</h1>
|
||||
<script>
|
||||
function jsFunc(arg1, arg2) {
|
||||
if (arg1 && arg2) document.body.innerHTML = "achoo";
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
</textarea></form>
|
||||
<script>
|
||||
// Define an extended mixed-mode that understands vbscript and
|
||||
// leaves mustache/handlebars embedded templates in html mode
|
||||
var mixedMode = {
|
||||
name: "htmlmixed",
|
||||
scriptTypes: [{matches: /\/x-handlebars-template|\/x-mustache/i,
|
||||
mode: null},
|
||||
{matches: /(text|application)\/(x-)?vb(a|script)/i,
|
||||
mode: "vbscript"}]
|
||||
};
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: mixedMode, tabMode: "indent"});
|
||||
</script>
|
||||
|
||||
<p>The HTML mixed mode depends on the XML, JavaScript, and CSS modes.</p>
|
||||
|
||||
<p>It takes an optional mode configuration
|
||||
option, <code>scriptTypes</code>, which can be used to add custom
|
||||
behavior for specific <code><script type="..."></code> tags. If
|
||||
given, it should hold an array of <code>{matches, mode}</code>
|
||||
objects, where <code>matches</code> is a string or regexp that
|
||||
matches the script type, and <code>mode</code> is
|
||||
either <code>null</code>, for script types that should stay in
|
||||
HTML mode, or a <a href="../../doc/manual.html#option_mode">mode
|
||||
spec</a> corresponding to the mode that should be used for the
|
||||
script.</p>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/html</code>
|
||||
(redefined, only takes effect if you load this parser after the
|
||||
XML parser).</p>
|
||||
|
||||
</article>
|
||||
@@ -1,98 +0,0 @@
|
||||
CodeMirror.defineMode("http", function() {
|
||||
function failFirstLine(stream, state) {
|
||||
stream.skipToEnd();
|
||||
state.cur = header;
|
||||
return "error";
|
||||
}
|
||||
|
||||
function start(stream, state) {
|
||||
if (stream.match(/^HTTP\/\d\.\d/)) {
|
||||
state.cur = responseStatusCode;
|
||||
return "keyword";
|
||||
} else if (stream.match(/^[A-Z]+/) && /[ \t]/.test(stream.peek())) {
|
||||
state.cur = requestPath;
|
||||
return "keyword";
|
||||
} else {
|
||||
return failFirstLine(stream, state);
|
||||
}
|
||||
}
|
||||
|
||||
function responseStatusCode(stream, state) {
|
||||
var code = stream.match(/^\d+/);
|
||||
if (!code) return failFirstLine(stream, state);
|
||||
|
||||
state.cur = responseStatusText;
|
||||
var status = Number(code[0]);
|
||||
if (status >= 100 && status < 200) {
|
||||
return "positive informational";
|
||||
} else if (status >= 200 && status < 300) {
|
||||
return "positive success";
|
||||
} else if (status >= 300 && status < 400) {
|
||||
return "positive redirect";
|
||||
} else if (status >= 400 && status < 500) {
|
||||
return "negative client-error";
|
||||
} else if (status >= 500 && status < 600) {
|
||||
return "negative server-error";
|
||||
} else {
|
||||
return "error";
|
||||
}
|
||||
}
|
||||
|
||||
function responseStatusText(stream, state) {
|
||||
stream.skipToEnd();
|
||||
state.cur = header;
|
||||
return null;
|
||||
}
|
||||
|
||||
function requestPath(stream, state) {
|
||||
stream.eatWhile(/\S/);
|
||||
state.cur = requestProtocol;
|
||||
return "string-2";
|
||||
}
|
||||
|
||||
function requestProtocol(stream, state) {
|
||||
if (stream.match(/^HTTP\/\d\.\d$/)) {
|
||||
state.cur = header;
|
||||
return "keyword";
|
||||
} else {
|
||||
return failFirstLine(stream, state);
|
||||
}
|
||||
}
|
||||
|
||||
function header(stream) {
|
||||
if (stream.sol() && !stream.eat(/[ \t]/)) {
|
||||
if (stream.match(/^.*?:/)) {
|
||||
return "atom";
|
||||
} else {
|
||||
stream.skipToEnd();
|
||||
return "error";
|
||||
}
|
||||
} else {
|
||||
stream.skipToEnd();
|
||||
return "string";
|
||||
}
|
||||
}
|
||||
|
||||
function body(stream) {
|
||||
stream.skipToEnd();
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
token: function(stream, state) {
|
||||
var cur = state.cur;
|
||||
if (cur != header && cur != body && stream.eatSpace()) return null;
|
||||
return cur(stream, state);
|
||||
},
|
||||
|
||||
blankLine: function(state) {
|
||||
state.cur = body;
|
||||
},
|
||||
|
||||
startState: function() {
|
||||
return {cur: start};
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("message/http", "http");
|
||||
@@ -1,45 +0,0 @@
|
||||
<!doctype html>
|
||||
|
||||
<title>CodeMirror: HTTP mode</title>
|
||||
<meta charset="utf-8"/>
|
||||
<link rel=stylesheet href="../../doc/docs.css">
|
||||
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="http.js"></script>
|
||||
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
|
||||
<div id=nav>
|
||||
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
|
||||
|
||||
<ul>
|
||||
<li><a href="../../index.html">Home</a>
|
||||
<li><a href="../../doc/manual.html">Manual</a>
|
||||
<li><a href="https://github.com/marijnh/codemirror">Code</a>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="../index.html">Language modes</a>
|
||||
<li><a class=active href="#">HTTP</a>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<article>
|
||||
<h2>HTTP mode</h2>
|
||||
|
||||
|
||||
<div><textarea id="code" name="code">
|
||||
POST /somewhere HTTP/1.1
|
||||
Host: example.com
|
||||
If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
|
||||
Content-Type: application/x-www-form-urlencoded;
|
||||
charset=utf-8
|
||||
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Ubuntu/12.04 Chromium/20.0.1132.47 Chrome/20.0.1132.47 Safari/536.11
|
||||
|
||||
This is the request body!
|
||||
</textarea></div>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>message/http</code>.</p>
|
||||
</article>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user