forked from damiansimanuk/texslide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmark2slide.py
1374 lines (1121 loc) · 42.6 KB
/
mark2slide.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the TexSlide project
#
# Copyright © 2012 by Héctor Damián Simañuk
#
# TexSlide is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# TexSlide is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with TexSlide. If not, see <http://www.gnu.org/licenses/>.
import re
alltext='''
autor:
date:
# # # # # # # # #
Prmier slide
-------------------------------
Prmier subtítulo del mismo slide que en realida es el prmier subtítulo del mismo slide, el prmier subtítulo como díje antes
a continuación un código:
``` #! python
print("hola mundo")
```
``` #! css
section.middle {
line-height: 68px;
/*
text-align: center;
*/
display: table-cell;
vertical-align: middle;
height: 600px;
width: 900px;
padding:20px;
}
```
yea
Segundo slide #id3
------------------
Este no tiene subtítulo
A continuación un código trucho:
```
codigo
trucho
```
Ahora un **principio** sin fin de bloque de código
```
Y esta es una lista:
------------------------------------
Ups se me dividió el slide
- Esta es una lista solo termina con un salto de linea osea un
renglón vacío.
- Osea que esta debe __ser otra__ linea del mismo item. Porque si
escribo en __emcas
con__ la opción fill "auto-fill-mode" me hace el salto
automático de lineas
Debería funcionar lo anterior
Tercer Slide:
...................
Listas combinadas
Ahora una lista combinada ¡tachan!:
1. item 1
- Hola mundo
1. y el 1-1
2. y el 1-2
2. item 2
- y otro item
3. y ahora el 3
cuarto slide
=================
Las tablas locas:
| Esta es una | tabla | como |
| 1 columnas | y dos filas | yea |
| Nueva tabla muy simple | sería que sigue acá | necesita |
dos divisores a menos Esta \| yu
es una imágen de nada solo \\ sirve para \n probar.Esta es una
imágen de nada solo sirve para probar.
por ejemplo:
hola | mundo | bien
texto 4 ``para nada`` **yea** o no
Quinto Slide
-----------------
y ahora las imágenes
[logo.png ]"Este es el logo"
Yea mundo.
Esta es una imágen de nada solo sirve para probar.
Todo bien che
-----------------
[openbox.png ]
Notas al pie
---------------------
Y ahora notas **al pie^[id1] ad
será^[2] que** O NO ANDA **anda^[#]** bien^[#] o esta la segunda^[#]
[^id1]: Yea acá está la nota al pie
[^#]: O no es una nota al pie
Notas al pie
---------------------
Ahora una lista combinada ¡tachan!:
1. item 1
- Hola mundo
1. y el 1-1
2. y el 1-2
2. item 2
- y otro item
3. y ahora el 3
1. item 1
- Hola mundo
1. y el 1-1
2. y el 1-2
2. item 2
- y otro item
3. y ahora el 3
Y ahora notas al pie^[id1] ad
será^[2] que anda^[id1] bien^[#] o esta la segunda^[#]
[^id1]: Yea acá está la nota al pie O no es una nota al pie digo que si es porque me parece que es... dale dale
[^#]: Primer nota pie automática
[^#]: Segunda
YEA
[id2]: porque este es el pie
yea esta es la ultima linea
hola
'''
DEBUG=True
COLOR_DEBUG=True
MACROS = {'date' : '%Y%m%d', 'infile': '%f',
'mtime': '%Y%m%d', 'outfile': '%f'}
HEADER_TEMPLATE = {
'xhtml': """\
<?xml version="1.0"
encoding="%(ENCODING)s"
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%(HEADER1)s</title>
<meta name="generator" content="http://txt2tags.org" />
<link rel="stylesheet" type="text/css" href="%(STYLE)s" />
</head>
<body bgcolor="white" text="black">
<div align="center">
<h1>%(HEADER1)s</h1>
<h2>%(HEADER2)s</h2>
<h3>%(HEADERn3)s</h3>
</div>
""",
'tex': \
r"""\documentclass{article}
\usepackage{graphicx}
\usepackage{paralist} %% needed for compact lists
\usepackage[normalem]{ulem} %% needed by strike
\usepackage[urlcolor=blue,colorlinks=true]{hyperref}
\usepackage[%(ENCODING)s]{inputenc} %% char encoding
\usepackage{%(STYLE)s} %% user defined
n
\title{%(HEADER1)s}
\author{%(HEADER2)s}
\begin{document}
\date{%(HEADER3)s}
\maketitle
\clearpage
"""
}
ALLTAGS = {
'html': {
'paragraph' : '\n<P>%s</P>' ,
'list' : '\n<UL>%s</UL>' ,
'numlist' : '\n<OL>%s</OL>' ,
'item' : '\n<LI>%s</LI>' ,
'table' :'\n<TABLE>%s\n</TABLE>',
'tableRow' :'\n<TR>%s</TR>',
'tableCell' :'<TD>%s</TD>',
'img' : '\n<IMG %s SRC="%s" alt="%s" />',
'figure' : '\n<div class="%s">%s \n</div>',
'caption' : '\n<P><B>Fig:</B> %s</P>',
'fnote' :
'<sup class="footnote"><a href="#fn%(id)s">%(id)s</a></sup>',
'title1' : '<H1>%s</H1>' ,
'title2' : '<H2>%s</H2>' ,
'title3' : '<H3>%s</H3>' ,
'title4' : '<H4>%s</H4>' ,
'title5' : '<H5>%s</H5>' ,
'blockQuote' : '<BLOCKQUOTE>%s</BLOCKQUOTE>' ,
'fontMono' : '<CODE>%s</CODE>' ,
'blockVerb' : '<PRE>%s</PRE>' ,
'anchor' : '<A NAME="\a"></A>\n',
'fontBold' : '<B>\\1</B>',
'fontItalic' : '<I>\\1</I>',
'fontUnderline' : '<U>\\1</U>',
'fontStrike' : '<S>\\1</S>',
'fontMono' : '<CODE>\\1</CODE>',
'deflist' : '<DL>%s</DL>' ,
'deflistItem' : '<DT>%s</DT>' ,
'deflistItem2' : '<DD>' ,
'bar1' : '<HR NOSHADE SIZE=1>' ,
'bar2' : '<HR NOSHADE SIZE=5>' ,
'url' : '<A HREF="%s">%s</A>' ,
'urlMark' : '<A HREF="%s">%s</A>' ,
'email' : '<A HREF="mailto:%s">%s</A>' ,
'emailMark' : '<A HREF="mailto:%s">%s</A>' ,
'prueba':
['hola',1],
'tableOpen' : '<TABLE~A~~B~ CELLPADDING="4">',
'tableClose' : '</TABLE>' ,
'tableRowOpen' : '<TR>' ,
'tableRowClose' : '</TR>' ,
'tableCellOpen' : '<TD~A~~S~>' ,
'tableCellClose' : '</TD>' ,
'tableTitleCellOpen' : '<TH~S~>' ,
'tableTitleCellClose' : '</TH>' ,
'_tableBorder' : ' BORDER="1"' ,
'_tableAlignCenter' : ' ALIGN="center"',
'_tableCellAlignRight' : ' ALIGN="right"' ,
'_tableCellAlignCenter': ' ALIGN="center"',
'_tableCellColSpan' : ' COLSPAN="\a"' ,
'cssOpen' : '<STYLE TYPE="text/css">',
'cssClose' : '</STYLE>' ,
'comment' : '<!-- %s -->' ,
'EOD' : '</BODY></HTML>'
},
'tex': {
'title1' : '~A~\section*{\a}' ,
'title2' : '~A~\\subsection*{\a}' ,
'title3' : '~A~\\subsubsection*{\a}',
# title 4/5: DIRTY: para+BF+\\+\n
'title4' : '~A~\\paragraph{}\\textbf{\a}\\\\\n',
'title5' : '~A~\\paragraph{}\\textbf{\a}\\\\\n',
'numtitle1' : '\n~A~\section{\a}' ,
'numtitle2' : '~A~\\subsection{\a}' ,
'numtitle3' : '~A~\\subsubsection{\a}' ,
'anchor' : '\\hypertarget{\a}{}\n' ,
'blockVerbOpen' : '\\begin{verbatim}' ,
'blockVerbClose' : '\\end{verbatim}' ,
'blockQuoteOpen' : '\\begin{quotation}' ,
'blockQuoteClose' : '\\end{quotation}' ,
'fontMonoOpen' : '\\texttt{' ,
'fontMonoClose' : '}' ,
'fontBoldOpen' : '\\textbf{' ,
'fontBoldClose' : '}' ,
'fontItalicOpen' : '\\textit{' ,
'fontItalicClose' : '}' ,
'fontUnderlineOpen' : '\\underline{' ,
'fontUnderlineClose' : '}' ,
'fontStrikeOpen' : '\\sout{' ,
'fontStrikeClose' : '}' ,
'listOpen' : '\\begin{itemize}' ,
'listClose' : '\\end{itemize}' ,
'listOpenCompact' : '\\begin{compactitem}',
'listCloseCompact' : '\\end{compactitem}' ,
'listItemOpen' : '\\item ' ,
'numlistOpen' : '\\begin{enumerate}' ,
'numlistClose' : '\\end{enumerate}' ,
'numlistOpenCompact' : '\\begin{compactenum}',
'numlistCloseCompact' : '\\end{compactenum}' ,
'numlistItemOpen' : '\\item ' ,
'deflistOpen' : '\\begin{description}',
'deflistClose' : '\\end{description}' ,
'deflistOpenCompact' : '\\begin{compactdesc}',
'deflistCloseCompact' : '\\end{compactdesc}' ,
'deflistItem1Open' : '\\item[' ,
'deflistItem1Close' : ']' ,
'bar1' : '\\hrulefill{}' ,
'bar2' : '\\rule{\linewidth}{1mm}',
'url' : '\\htmladdnormallink{\a}{\a}',
'urlMark' : '\\htmladdnormallink{\a}{\a}',
'email' : '\\htmladdnormallink{\a}{mailto:\a}',
'emailMark' : '\\htmladdnormallink{\a}{mailto:\a}',
'img' : '\\includegraphics{\a}',
'tableOpen' : '\\begin{center}\\begin{tabular}{|~C~|}',
'tableClose' : '\\end{tabular}\\end{center}',
'tableRowOpen' : '\\hline ' ,
'tableRowClose' : ' \\\\' ,
'tableCellSep' : ' & ' ,
'_tableColAlignLeft' : 'l' ,
'_tableColAlignRight' : 'r' ,
'_tableColAlignCenter' : 'c' ,
'_tableCellAlignLeft' : 'l' ,
'_tableCellAlignRight' : 'r' ,
'_tableCellAlignCenter': 'c' ,
'_tableCellColSpan' : '\a' ,
'_tableCellMulticolOpen' : '\\multicolumn{\a}{|~C~|}{',
'_tableCellMulticolClose' : '}',
'tableColAlignSep' : '|' ,
'comment' : '% \a' ,
'TOC' : '\\tableofcontents',
'pageBreak' : '\\clearpage',
'EOD' : '\\end{document}'
}
}
def Debug(msg,id_=0):
if not DEBUG: return
if int(id_) not in range(10): id_ = 0
# 0:black 1:red 2:green 3:yellow 4:blue 5:pink 6:cyan 7:white ;1:light
#~ ids = ['INI','CFG','SRC','BLK','HLD','GUI','OUT','DET','NAD','Import']
#~ colors_bgdark = ['7;1','1;1','3;1','6;1','4;1','5;1','2;1','7;1']
colors_bglight = ['7' ,'1' ,'3' ,'6' ,'4' ,'5' ,'2' ,'2;1','7;1','1;1']
if COLOR_DEBUG:
color = colors_bglight[id_]
msg = '\033[3%sm%s\033[m'%(color,msg)
print("--- %s"%(msg))
def getRegexes():
"""
Retorna las expreciones regulares compiladas para las marcas de
texslide
"""
bank = {
'lineVoid':
re.compile(r'^\s*$'),
'title':
re.compile(r'^(\w.+)$'),
# la \w es para que no empieze con ` que corresponden a ```
# de códigos multilinea (hay que mejorar)
'titleRule':
re.compile(r'^\s*([.=-]{4,})\s*$'),
'titleSub':
re.compile(r'^\s*(.+)$'),
'blockVerbOpen':
re.compile(r'^```\s*((#!)\s*(\w*))*\s*$'),
'blockVerbClose':
re.compile(r'^```\s*$'),
'blockQuoteOpen':
re.compile(r'^"""\s*(.*)$'),
'blockQuoteClose':
re.compile(r'^"""\s*$'),
'blockQuote2Open':
re.compile(r"^'''\s*(.*)$"),
'blockQuote2Close':
re.compile(r"^'''\s*$"),
'listOpen':
re.compile(r'^( *|\t*)- (.*)$'),
'listClose':
re.compile(r'^ *$'),
'numlistOpen':
re.compile(r'^( *|\t*)(\d)[.] (.+)$'),
'numlistClose':
re.compile(r'^ *$'),
'tableOpen':
re.compile(r'\|.*[^\\]\|'),
'tableClose':
re.compile(r'^ *$'),
# 'table': # ¿esto vá (se usa))?
# re.compile(r'\|.*[^\\]\|'),
# imagenes
'imageOpen':
re.compile(\
r'\[([\w_,.+%$#@!?+~/-]+\.(png|jpe?g|gif|eps|bmp))( +.*)?\] ?(".*)?'),
'imageClose':
re.compile(r'.*'),
# footnotes [id] \\ [^id]: ejemplo de nota al pie
'ids':
re.compile(r'^\[(\^?(?:#?|\w+))\]:(.+)'),
'footnote':
re.compile(r'\^\[(\w+|#)\]',re.S|re.U),
'blockCommentClose':
re.compile(r'^%%%\s*$'),
'quote':
re.compile(r'^\t+'),
'1lineVerb':
re.compile(r'^``` (?=.)'),
'1lineRaw':
re.compile(r'^""" (?=.)'),
'1lineTagged':
re.compile(r"^''' (?=.)"),
'Comment':
re.compile(r'\s+//(.*)$'),
# mono, bold, italic, underline:
'fontMono':
re.compile( r'``([^\s](|.*?[^\s])`*)``',re.S|re.U),
'tagged':
re.compile( r"''([^\s](|.*?[^\s])'*)''",re.S|re.U),
'fontBold':
re.compile(r'\*\*([^\s](|.*?[^\s])\**)\*\*',re.S|re.U),
'fontItalic':
re.compile( r'//([^\s](|.*?[^\s])/*)//',re.S|re.U),
'fontUnderline':
re.compile( r'__([^\s].+\s*.*[^\s])__'),
'fontStrike':
re.compile( r'--([^\s](|.*?[^\s])-*)--'),
'raw':
re.compile( r'""([^\s](|.*?[^\s])"*)""'),
'list':
re.compile(r'^( *)(-) (?=[^ ])'),
'numlist':
re.compile(r'^( *)(\+) (?=[^ ])'),
'deflist':
re.compile(r'^( *)(:) (.*)$'),
'listclose':
re.compile(r'^( *)([-+:])\s*$'),
'bar':
re.compile(r'^(\s*)([_=-]{20,})\s*$'),
# 'table':
# re.compile(r'^ *\|\|? '),
'blankline':
re.compile(r'^\s*$'),
'comment':
re.compile(r'^%'),
'indent':
re.compile(r'^( {3,})(.*)$'),
# Auxiliary tag regexes
'_imgAlign' : re.compile(r'~A~', re.I),
'_tableAlign' : re.compile(r'~A~', re.I),
'_anchor' : re.compile(r'~A~', re.I),
'_tableBorder' : re.compile(r'~B~', re.I),
'_tableColAlign' : re.compile(r'~C~', re.I),
'_tableCellColSpan': re.compile(r'~S~', re.I),
'_tableCellAlign' : re.compile(r'~A~', re.I),
}
# Special char to place data on TAGs contents (\a == bell)
bank['x'] = re.compile('\a')
# %%macroname [ (formatting) ]
bank['macros'] = re.compile(r'%%%%(?P<name>%s)\b(\((?P<fmt>.*?)\))?' % (
'|'.join(MACROS.keys())), re.I)
# %%TOC special macro for TOC positioning
bank['toc'] = re.compile(r'^ *%%toc\s*$', re.I)
# Almost complicated title regexes ;)
titskel = r'^ *(?P<id>%s)(?P<txt>%s)\1(\[(?P<label>[\w-]*)\])?\s*$'
### Complicated regexes begin here ;)
#
# Textual descriptions on --help's style: [...] is optional, | is OR
### First, some auxiliary variables
#
# [image.EXT]
patt_img = r'\[([\w_,.+%$#@!?+~/-]+\.(png|jpe?g|gif|eps|bmp))\]'
# Link things
# http://www.gbiv.com/protocols/uri/rfc/rfc3986.html
# pchar: A-Za-z._~- / %FF / !$&'()*+,;= / :@
# Recomended order: scheme://user:pass@domain/path?query=foo#anchor
# Also works : scheme://user:pass@domain/path#anchor?query=foo
# TODO form: !'():
urlskel = {
'proto' : r'(https?|ftp|news|telnet|gopher|wais)://',
'guess' : r'(www[23]?|ftp)\.', # w/out proto, try to guess
'login' : r'A-Za-z0-9_.-', # for ftp://login@domain.com
'pass' : r'[^ @]*', # for ftp://login:pass@dom.com
'chars' : r'A-Za-z0-9%._/~:,=$@&+-', # %20(space), :80(port), D&D
'anchor': r'A-Za-z0-9%._-', # %nn(encoded)
'form' : r'A-Za-z0-9/%&=+:;.,$@*_-', # .,@*_-(as is)
'punct' : r'.,;:!?'
}
# username [ :password ] @
patt_url_login = r'([%s]+(:%s)?@)?'%(urlskel['login'],urlskel['pass'])
# [ http:// ] [ username:password@ ] domain.com [ / ]
# [ #anchor | ?form=data ]
retxt_url = r'\b(%s%s|%s)[%s]+\b/*(\?[%s]+)?(#[%s]*)?'%(
urlskel['proto'],patt_url_login, urlskel['guess'],
urlskel['chars'],urlskel['form'],urlskel['anchor'])
# filename | [ filename ] #anchor
retxt_url_local = r'[%s]+|[%s]*(#[%s]*)'%(
urlskel['chars'],urlskel['chars'],urlskel['anchor'])
# user@domain [ ?form=data ]
patt_email = r'\b[%s]+@([A-Za-z0-9_-]+\.)+[A-Za-z]{2,4}\b(\?[%s]+)?'%(
urlskel['login'],urlskel['form'])
# Saving for future use
bank['_urlskel'] = urlskel
### And now the real regexes
#
bank['email'] = re.compile(patt_email,re.I)
# email | url
bank['link'] = re.compile(r'%s|%s'%(retxt_url,patt_email), re.I)
# \[ label | imagetag url | email | filename \]
bank['linkmark'] = re.compile(
r'\[(?P<label>%s|[^]]+) (?P<link>%s|%s|%s)\]'%(
patt_img, retxt_url, patt_email, retxt_url_local),
re.L+re.I)
# Image
bank['img'] = re.compile(patt_img, re.L+re.I)
# Special things
bank['special'] = re.compile(r'^%!\s*')
return bank
### END OF regex nightmares
# def header2():
# """
# Procesa la cabecera para determinar ciertas
# configuraciones útiles
# """
# print("Hay cabecera")
CONFIG = {
'target' : 'html', # default
'title' : 'Slide hecho con TexSlide', # default
'author' : 'TexSlide', # default
'email' : 'github.texslide.org', # ¿direccion de github?
'Licencia' : 'GPL V3',
}
# # # Definicion de los bloques
BLOCKS = {
""" BLOCKS contiene los distintos bloques y los bloques internos
que se permiten en TexSlide
"""
'para' :['comment','raw','tagged'],
'verb' :[],
'table' :['comment'],
'raw' :[],
'tagged' :[],
'comment' :[],
'quote' :['quote','comment','raw','tagged'], # 'bar'
'list' :['list','numlist','deflist','para','verb','comment',\
'raw','tagged'],
'numlist' :['list','numlist'],
'deflist' :['list','numlist','deflist','para','verb','comment',\
'raw','tagged'],
'bar' :[],
'title' :[],
'numtitle' :[],
}
EXCLUSIVE = ['comment','verb','raw','tagged']
ORDEN_BLOCKS=['blockVerb','list','numlist','table','image']
# # # END definicion de bloques
CONFIG['target']='html'
class ConvertFunction():
def __init__(self):
global CONFIG,ALLTAGS,BLOCKS
self.b_list = BLOCKS["list"]
self.b_numlist = BLOCKS["numlist"]
self.b_list = BLOCKS["list"]
self.regex = getRegexes()
self.lang = None
self.target = CONFIG['target']
self.tags = ALLTAGS[self.target]
"""
Se analizan los distintos bloques y devuelve el valor para
saber a que linea saltar. Generalmente se devuelve > 1, por
ejemplo para `code` multilinea.
Se devuelve 0 en realidad no es un bloque como se suponía que
era '
"""
self.func={
'blockVerb' :self.codeVerb,
'list' :self.list,
'numlist' :self.numlist,
'table' :self.table,
'image' :self.image,
'funcion1' :self.funcion1,
}
def reset(self):
pass
def funcion1(self,lines):
Debug("funcion1: ",1)
Debug(lines,0)
return 0, ''
def image(self,lines):
Debug(":IMAGE: ",1)
Debug(lines,0)
find = self.regex['imageOpen'].search(lines[0])
arg=find.group(3)
cap=find.group(4)
src=find.group(1)
# alignh='center'
# if re.search(r'[ ,]r[ ,]',arg):
# alignh='right'
# elif re.search(r'[ ,]l[ ,]',arg):
# alignh='left'
alh= 'right' if re.search(r'[ ,]r( |,|$)',arg) else 'left' if\
re.search(r'[ ,]l( |,|$)',arg) else 'center'
alv= 'top' if re.search(r'[ ,]t( |,|$)',arg) else 'booton' if\
re.search(r'[ ,]b( |,|$)',arg) else 'center'
size=re.search(r'[ ,](\d+(px|%))( |,|$)',arg)
if size:
size=size.group(1)
else:
size=''
index=0
caption=''
if cap:
c=re.match(r'^"(.*)"',cap)
if c:
caption=c.group(1)
elif lines[1]:
c=re.match(r'(.*)"( |$)',lines[1])
if c:
caption=cap[1:] +'\n'+ c.group(1)
index=1
elif lines[1]:
c=re.match(r'^ ?"(.*)"( |$)',lines[1])
if c:
caption=c.group(1)
index=1
# para implementar lo siguiente es necesario trabajar un poco
# con los css y las variables anterires alh alv y en cuanto
# a el size hay que obtener ancho y alto.
clas='image'
arg=''
res=self.tags['img']%(arg,src,caption)
if caption:
caption=self.newPara([caption],False)
caption = self.tags['caption']%(caption)
res=self.tags['figure']%(clas,res + caption)
print(res)
return index, res
def table(self,lines):
Debug(":tableOpen: ",1)
Debug(lines,0)
line_a = lines[0]
rows = [line_a.strip().strip('\\').strip('|').split('|')]
# print(rows)
i=-1
for line in lines[1:]:
i+=1
find = self.regex['tableOpen'].search(line)
if not find:
lines = lines[:i]
Debug(":tabla: trunca .......................",0)
break
# Si line_a (fila anterior ) termina en \\ y extiende la
# fila con la siguiente linea o si no agrega una nueva
# fila
if line_a.strip().endswith('\\'):
rows[-1].extend(line.strip().strip('\\').strip('|').\
split('|'))
else:
rows.append(line.strip().strip('\\').strip('|').\
split('|'))
line_a = line
# ahora ya se tiene la tabla correcta en rows se pueden
# analizar los espacios para saber como estan centrados los
# textos pero no se hace eso todavía...
table =''
for ro in rows:
cells=''
for cel in ro:
# Debug(":table:cel:|%s|"%cel,3)
cell = self.newPara([cel],False)
cells += self.tags['tableCell']%(cell)
table += self.tags['tableRow']%(cells)
table = self.tags['table']%(table)
Debug(table,2)
# Debug(' | '.join(row),4)
# Debug(rows,3)
return i, table
def list(self,lines):
# Debug(":list: ingresa ",2)
## yas
find = self.regex['listOpen'].search(lines[0])
nivel = len(find.group(1))
curItem=[find.group(2)]
items=''
tempIndex=0
for line in lines[1:-1]:
find = self.regex['listOpen'].search(line)
if find:
nnivel = len(find.group(1))
if nnivel < nivel:
tempIndex -=1
break
#~ return tempIndex, items
elif nnivel == nivel:
items += self.tags['item']%\
(self.parser(curItem,self.b_numlist))
curItem=[find.group(2)]
#~ j+=1
else:
curItem.append(line)
else:
curItem.append(line)
tempIndex +=1
items += self.tags['item']%\
(self.parser(curItem,self.b_numlist))
items = self.tags['list']%(items)
# Debug(":lista: retorna",6)
# Debug(items,8)
return tempIndex, items
def numlist(self,lines):
# Debug(":numlist: ingresa ",2)
find = self.regex['numlistOpen'].search(lines[0])
nivel = len(find.group(1))
curItem=[find.group(3)]
# Debug(":numlist: %s -- %s"%(nivel,curItem),3)
items=''
tempIndex=0
for line in lines[1:-1]:
find = self.regex['numlistOpen'].search(line)
if find:
nnivel = len(find.group(1))
if nnivel < nivel:
tempIndex -=1
break
#~ return tempIndex, items
elif nnivel == nivel:
items += self.tags['item']%\
(self.parser(curItem,self.b_numlist))
curItem=[find.group(3)]
#~ j+=1
else:
curItem.append(line)
else:
curItem.append(line)
tempIndex +=1
items += self.tags['item']%\
(self.parser(curItem,self.b_numlist))
items = self.tags['numlist']%(items)
# Debug(":numlist: retorna",6)
# Debug(items,8)
return tempIndex, items
def codeVerb(self,lines):
Debug(":codeVerb: ingresa ",2)
index=len(lines)
if self.target == 'html':
return index-1, self.highlighting(lines)
else:
return index, ''
def highlighting(self,code):
"""
returns : A string of html code.
¿damian: debería andar para html y no html?
"""
#~ Debug(code[0],4)
reg=re.compile(r'^```\s*((#!)\s*(\w*))*\s*$')
res=reg.search(code[0])
code.pop(0)
if res:
lang=res.group(3)
Debug(':Code: lang: %s'%lang,9)
else:
lang=None
code='\n'.join(code).strip('\n').strip('`').strip('\n')
try:
from pygments import highlight
from pygments.lexers import get_lexer_by_name,TextLexer
from pygments.formatters import HtmlFormatter
pygments = True
except ImportError:
pygments = False
Debug('H: La librería pygments no está disponible:\
ImportError',9)
if pygments:
try:
lexer = get_lexer_by_name(lang)
except ValueError:
lexer = TextLexer()
formatter = HtmlFormatter()
codeh=highlight(code, lexer, formatter)
# Debug(codeh,5)
return codeh
else:
# damian: aca se deberia hacer general (¿para latex?)
txt = code.replace('&', '&')
txt = txt.replace('<', '<')
txt = txt.replace('>', '>')
txt = txt.replace('"', '"')
return txt
def parser(self,lines,block_orden):
lines.append('')
ultimalinea = len(lines)
lineref = 0
body_parser=[]
joinLines=[]
result=''
voidLine=True
while lineref < ultimalinea:
line = lines[lineref]
#Debug(':parser: linea:',1)
#Debug(line,0)
lineref += 1
analise=re.search(r'^~~\w~~(.*)',line,re.DOTALL|re.UNICODE)
if analise:
Debug(':parser: ------ linea analizada ------',2)
newblock=True
result=analise.group(1)
# acá en adelante se podría hacer todo con if si se complican los
# análisis de los bloques.
else:
newblock=False
for block in block_orden:
# block contiene en orden los bloques a busacar, así
# primero se busca un bloque de código despues uno de
# xxx y por último un xxx
if self.regex[block+'Open'].search(line):
Debug(":parser: abre %s"%block,5)
aux_body=[line]
for j in range(lineref,ultimalinea):
aux_line= lines[j]
aux_body.append(aux_line)
if self.regex[block+'Close'].search(aux_line):
index,result = self.func[block](aux_body)
if index >= 0:
lineref = lineref + index
newblock=True
Debug(":parser: cierra %s"%block,6)
break
elif newblock:
break
else:
pass
if newblock:
# Si hay un nuevo bloque primero agrega el parrafo
# pendiente luego incorpora el nuevo bloque
body_parser.append(self.newPara(joinLines))
body_parser.append(result)
joinLines=[]
elif re.search(r'^\s*$',line):
# Si no hay nuevo bloque pero hay salto de linea,
# osea una linea vacia => hay un nuevo parrafo
body_parser.append(self.newPara(joinLines))
joinLines=[]
else:
# Concatena las lineas
joinLines.append(line)
return('\n'.join(body_parser))
def newPara(self,joinLines,para=True):
"""
Recibe una lista (un parrafo) y analiza sus partes.
Para los enlaces y notas al pie es necesario detectar
los #id (eso lo hace convert)
## USO:
>>> ts=mark2slide.ConvertFunction()
>>> text="hola __mundo__ como //estas//"
>>> ts.newPara([text])
'\n<P>hola <U>mundo</U> como <I>estas</I></P>'
"""