• Publicidad

Expresión regular para texto anidado

¿Apenas comienzas con Perl? En este foro podrás encontrar y hacer preguntas básicas de Perl con respuestas aptas a tu nivel.

Re: Expresión regular para texto anidado

Notapor pablgonz » 2015-01-01 22:35 @983

Lo logré... la solución es un poco chambona... pero... bastante útil:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use v5.18;
  3. use re 'eval';
  4. use autodie;                    # muere si ocurre un error
  5. use File::Basename;             # separa el archivo de entrada
  6. use Config;
  7.  
  8. # Constantes
  9. my $tempDir = ".";              # temporary directory
  10. my $imageDir = "images";        # where to save the images
  11. my $ignore = "ignore";          # ignore verbatim environment
  12. my $exacount = 1;               # Counter for images
  13. my $other = "other";            # otro entorno
  14. #--------------------- Arreglo de la extensión -------------------------
  15. my @SuffixList = ('.tex', '', '.ltx');               # posible extensión
  16. my ($name, $path, $ext) = fileparse($ARGV[0], @SuffixList);
  17. $ext = '.tex' if not $ext;
  18.  
  19. #---------------- Creamos el directorio para las imágenes --------------
  20. -e $imageDir or mkdir($imageDir,0744) or die "No puedo crear $imageDir: $!\n";
  21.  
  22. # Constantes para regex
  23. my $BP = '\\\\begin{postscript}';
  24. my $EP = '\\\\end{postscript}';
  25. my $BPL = '\begin{postscript}';
  26. my $EPL = '\end{postscript}';
  27. my $sipgf = 'pgfpicture';
  28. my $nopgf = 'pgfinterruptpicture';
  29. my $graphics = "graphic=\{\[scale=1\]$imageDir/$name-fig";
  30.  
  31. ############################# PARTE 1 ##################################
  32. #---------------- Creamos un hash con los cambios ----------------------
  33. my %cambios = (
  34. # pspicture    
  35.     '\pspicture'                => '\TRICKS',
  36.     '\endpspicture'             => '\ENDTRICKS',
  37. # pspicture
  38.     '\begin{pspicture'          => '\begin{TRICKS',
  39.     '\end{pspicture'            => '\end{TRICKS',
  40. # postscript
  41.     '\begin{postscript}'        => '\begin{POSTRICKS}',
  42.     '\end{postscript}'          => '\end{POSTRICKS}',
  43. # $other    
  44.     "\\begin\{$other"           => '\begin{OTHER',
  45.     "\\end\{$other"             => '\end{OTHER',
  46. # document
  47.     '\begin{document}'          => '\begin{DOCTRICKS}',
  48.     '\end{document}'            => '\end{DOCTRICKS}',
  49. # tikzpicture
  50.     '\begin{tikzpicture}'       => '\begin{TIKZPICTURE}',
  51.     '\end{tikzpicture}'         => '\end{TIKZPICTURE}',
  52. # pgfinterruptpicture
  53.     '\begin{pgfinterruptpicture'=> '\begin{PGFINTERRUPTPICTURE',
  54.     '\end{pgfinterruptpicture'  => '\end{PGFINTERRUPTPICTURE',
  55. # pgfpicture
  56.     '\begin{pgfpicture}'        => '\begin{PGFPICTURE}',
  57.     '\end{pgfpicture}'          => '\end{PGFPICTURE}',
  58. # ganttchart
  59.     '\begin{ganttchart}'        => '\begin{GANTTCHART}',
  60.     '\end{ganttchart}'          => '\end{GANTTCHART}',
  61. # circuitikz
  62.     '\begin{circuitikz}'        => '\begin{CIRCUITIKZ}',
  63.     '\end{circuitikz}'          => '\end{CIRCUITIKZ}',
  64. # forest    
  65.     '\begin{forest}'            => '\begin{FOREST}',
  66.     '\end{forest}'              => '\end{FOREST}',
  67. # tikzcd
  68.     '\begin{tikzcd}'            => '\begin{TIKZCD}',
  69.     '\end{tikzcd}'              => '\end{TIKZCD}',
  70. # dependency
  71.     '\begin{dependency}'        => '\begin{DEPENDENCY}',
  72.     '\end{dependency}'          => '\end{DEPENDENCY}',
  73. );
  74.  
  75. #--------------------------- Coment Verbatim --------------------------#
  76.  
  77. open my $ENTRADA, '<', "$name$ext";
  78. my $archivo;
  79. {
  80.     local $/;
  81.     $archivo = <$ENTRADA>;
  82. }
  83. close $ENTRADA;
  84.  
  85. # Variables y constantes
  86. my $no_del = "\0";
  87. my $del    = $no_del;
  88.  
  89. # Reglas
  90. my $llaves      = qr/\{ .+? \}                                                                  /x;
  91. my $no_corchete = qr/(?:\[ .+? \])?                                                             /x;
  92. my $delimitador = qr/\{ (?<del>.+?) \}                                                          /x;
  93. my $verb        = qr/(spv|v|V)erb [*]?                                                          /ix;
  94. my $lst         = qr/lstinline (?!\*) $no_corchete                                              /ix;
  95. my $mint        = qr/mint      (?!\*) $no_corchete $llaves                                      /ix;
  96. my $marca       = qr/\\ (?:$verb | $lst | $mint ) (\S) .+? \g{-1}                               /x;
  97. my $comentario  = qr/^ \s* \%+ .+? $                                                            /mx;
  98. my $definedel   = qr/\\ (?:   DefineShortVerb | lstMakeShortInline  ) $no_corchete $delimitador /ix;
  99. my $indefinedel = qr/\\ (?: UndefineShortVerb | lstDeleteShortInline) $llaves                   /ix;
  100.  
  101. while ($archivo =~
  102.         /   $marca
  103.         |   $comentario
  104.         |   $definedel
  105.         |   $indefinedel
  106.         |   $del .+? $del                                                       # delimitado
  107.         /pgmx) {
  108.  
  109.         my($pos_inicial, $pos_final) = ($-[0], $+[0]);                          # posiciones
  110.         my $encontrado = ${^MATCH};                                             # lo encontrado
  111.  
  112.     if ($encontrado =~ /$definedel/){                                           # definimos delimitador
  113.                         $del = $+{del};
  114.                         $del = "\Q$+{del}" if substr($del,0,1) ne '\\';         # es necesario "escapar" el delimitador
  115.                 }
  116.     elsif($encontrado =~ /$indefinedel/) {                                      # indefinimos delimitador
  117.                  $del = $no_del;                                      
  118.         }
  119.     else {                                                                      # aquí se hacen los cambios
  120.         while (my($busco, $cambio) = each %cambios) {
  121.                        $encontrado =~ s/\Q$busco\E/$cambio/g;                   # es necesario escapar $busco
  122.                         }
  123.         substr $archivo, $pos_inicial, $pos_final-$pos_inicial, $encontrado;     # insertamos los nuevos cambios
  124.  
  125.         pos($archivo)= $pos_inicial + length $encontrado;                        # re posicionamos la siguiente búsqueda
  126.         }
  127. }
  128.  
  129. # Write
  130. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  131.    print   $SALIDA "$archivo";
  132. close $SALIDA;
  133.  
  134. #--------------------- Coment Verbatim environment --------------------#
  135.  
  136. my @lineas;
  137. {
  138.    open my $FILE,'<',"$tempDir/$name-tmp$ext";
  139.    @lineas = <$FILE>;
  140.    close $FILE;
  141. }
  142.  
  143. # Verbatim environments
  144. my $ENTORNO  = qr/(?: (v|V)erbatim\*?| PSTexample | LTXexample| $ignore\*? | PSTcode | tcblisting\*? | spverbatim | minted | lstlisting | alltt | comment\*? | xcomment)/xi;
  145.  
  146. # postscript environment
  147. my $POSTSCRIPT = qr/(?: postscript)/xi;
  148.  
  149. # tikzpicture environment
  150. my $TIKZENV    = qr/(?: tikzpicture)/xi;
  151. #    
  152. my $DEL;
  153. # tcbverb verbatim
  154. my $tcbverb = qr/\\(?:tcboxverb|myverb)/;
  155. my $arg_brac = qr/(?:\[.+?\])?/;
  156.  
  157. my $arg_curl = qr/\{(.+)\}/;          
  158.  
  159. # coment verbatim environment
  160. for (@lineas) {
  161.     if (/\\begin\{($ENTORNO)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  162.         while (my($busco, $cambio) = each %cambios) {
  163.             s/\Q$busco\E/$cambio/g;
  164.         }
  165.     }
  166. }
  167. # coment tcolorbox inline
  168. for (@lineas) {
  169.     if (m/$tcbverb$arg_brac$arg_curl/) {
  170.         while (my($busco, $cambio) = each %cambios) {
  171.             s/\Q$busco\E/$cambio/g;
  172.         }
  173.     } # close
  174.  }
  175. # remove postscript from hash
  176. delete @cambios{'\begin{postscript}','\end{postscript}'};
  177. # coment in postscript environment
  178. for (@lineas) {
  179.     if (/\\begin\{($POSTSCRIPT)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  180.         while (my($busco, $cambio) = each %cambios) {
  181.             s/\Q$busco\E/$cambio/g;
  182.         }
  183.     } # close postcript environment
  184. }
  185. # remove tikzpicture from hash
  186. delete @cambios{'\begin{tikzpicture}','\end{tikzpicture}'};
  187. # coment in tikzpicture environment
  188. for (@lineas) {
  189.     if (/\\begin\{($TIKZENV)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  190.         while (my($busco, $cambio) = each %cambios) {
  191.             s/\Q$busco\E/$cambio/g;
  192.         }
  193.     } # close TIKZ environment
  194. }
  195.  
  196. # Write file
  197. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  198. print   $SALIDA @lineas;
  199. close   $SALIDA;
  200.  
  201. ############################# PARTE 2 ##################################
  202. #------------- Convert ALL into Postscript environments ---------------#
  203. open my $ENTRADA, '<', "$tempDir/$name-tmp$ext";
  204. my $archivo;
  205. {
  206.     local $/;
  207.     $archivo = <$ENTRADA>;
  208. }
  209. close $ENTRADA;
  210.  
  211. ## Partición del documento
  212.  
  213. my($cabeza,$cuerpo,$final) = $archivo =~ m/\A (.+?) (^\\begin{document} .+)(^\\end{document}.*)\z/msx;
  214.  
  215. # \pspicture to \begin{pspicture}
  216. $cuerpo =~ s/\\pspicture(\*)?(.+?)\\endpspicture/\\begin{pspicture$1}$2\\end{pspicture$1}/gmsx;
  217.  
  218. # pspicture to Postscript
  219. $cuerpo =~ s/
  220.     (
  221.         (?:\\psset\{[^\}]+\}.*?)?
  222.         (?:\\begin\{pspicture(\*)?\})
  223.                 .*?
  224.         (?:\\end\{pspicture(\*)?\})
  225.     )
  226.     /$BPL\n$1\n$EPL/gmsx;
  227.  
  228. # pgfpicture to Postscript
  229. $cuerpo =~ s/
  230.     (
  231.         \\begin{$sipgf}
  232.             .*?
  233.             (
  234.                 \\begin{$nopgf}
  235.                 .+?
  236.                 \\end{$nopgf}
  237.                 .*?
  238.             )*?
  239.         \\end{$sipgf}
  240.     )
  241.     /$BPL\n$1\n$EPL/gmsx;
  242.  
  243. # tikz to Postscript
  244. $cuerpo =~ s/
  245.      (
  246.         (?:\\tikzset(\{(?:\{.*?\}|[^\{])*\}).*?)? # si está lo guardo
  247.               (?:\\begin\{tikzpicture\})       # aquí comienza la búsqueda
  248.                             .*?                # guardo el contenido en $1
  249.                     (?:\\end\{tikzpicture\})   # termina la búsqueda
  250.                 ) # cierra $1
  251.                 /$BPL\n$1\n$EPL/gmsx;
  252.  
  253. # rest to Postscript
  254. my $export  = qr/(forest|ganttchart|tikzcd|circuitikz|dependency|$other\*?)/x;
  255.  
  256. $cuerpo =~ s/(\\begin\{($export)\} (.*?)  \\end\{\g{-2}\})/$BPL\n$1\n$EPL/gmsx;
  257.  
  258. # Write
  259. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  260.    print   $SALIDA "$cabeza$cuerpo$final";
  261. close $SALIDA;
  262.  
  263.  
  264. ##---------------------------- PARTE 3 -------------------------------##
  265. #-------------------------- Reverse changes ---------------------------#
  266.  
  267. my %cambios = (
  268. # pst/tikz set    
  269.     '\PSSET'                    =>      '\psset',
  270.     '\TIKZSET'                  =>      '\tikzset',                    
  271. # pspicture    
  272.     '\TRICKS'                   =>      '\pspicture',
  273.     '\ENDTRICKS'                =>      '\endpspicture',            
  274. # pspicture
  275.     '\begin{TRICKS'             =>      '\begin{pspicture',
  276.     '\end{TRICKS'               =>      '\end{pspicture',
  277. # $other    
  278.     '\begin{OTHER'              =>      "\\begin\{$other",             
  279.     '\end{OTHER'                =>      "\\end\{$other",
  280. # document
  281.     '\begin{DOCTRICKS}'         =>      '\begin{document}',
  282.     '\end{DOCTRICKS}'           =>      '\end{document}',
  283. # tikzpicture
  284.     '\begin{TIKZPICTURE}'       =>      '\begin{tikzpicture}',
  285.     '\end{TIKZPICTURE}'         =>      '\end{tikzpicture}',
  286. # pgfinterruptpicture
  287.     '\begin{PGFINTERRUPTPICTURE'=>      '\begin{pgfinterruptpicture',
  288.     '\end{PGFINTERRUPTPICTURE'  =>      '\end{pgfinterruptpicture',
  289. # pgfpicture
  290.     '\begin{PGFPICTURE}'        =>      '\begin{pgfpicture}',
  291.     '\end{PGFPICTURE}'          =>      '\end{pgfpicture}',
  292. # ganttchart
  293.     '\begin{GANTTCHART}'        =>      '\begin{ganttchart}',
  294.     '\end{GANTTCHART}'          =>      '\end{ganttchart}',
  295. # circuitikz
  296.     '\begin{CIRCUITIKZ}'        =>      '\begin{circuitikz}',
  297.     '\end{CIRCUITIKZ}'          =>      '\end{circuitikz}',
  298. # forest    
  299.     '\begin{FOREST}'            =>      '\begin{forest}',
  300.     '\end{FOREST}'              =>      '\end{forest}',
  301. # tikzcd
  302.     '\begin{TIKZCD}'            =>      '\begin{tikzcd}',
  303.     '\end{TIKZCD}'              =>      '\end{tikzcd}',
  304. # dependency
  305.     '\begin{DEPENDENCY}'        =>      '\begin{dependency}',
  306.     '\end{DEPENDENCY}'          =>      '\end{dependency}',
  307. );
  308.  
  309. #-------------------------- Back Postscript ---------------------------#
  310. my @lineas;
  311. {
  312.    open my $FILE,'<',"$tempDir/$name-tmp$ext";
  313.    @lineas = <$FILE>;
  314.    close $FILE;
  315. }
  316. # reverse in postscript environment
  317. for (@lineas) {
  318.     if (/\\begin\{($POSTSCRIPT)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  319.         while (my($busco, $cambio) = each %cambios) {
  320.             s/\Q$busco\E/$cambio/g;
  321.         }
  322.     } # close postscript environment changes
  323. }
  324.    
  325. # Write
  326. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  327. print   $SALIDA @lineas;
  328. close   $SALIDA;
  329.  
  330. ##---------------------------- PARTE 4 -------------------------------##
  331. #--------------- Extract source code for PST/PGF/TIKZ -----------------#
  332. open my $ENTRADA, '<',"$tempDir/$name-tmp$ext";
  333. my $archivo;
  334. {
  335.     local $/;
  336.     $archivo = <$ENTRADA>;
  337. }
  338. close $ENTRADA;
  339.  
  340. # Dividir el archivo
  341. my($cabeza,$cuerpo,$final) = $archivo =~ m/\A (.+?) (^\\begin{document} .+)(^\\end{document}.*)\z/msx;
  342.  
  343. $cabeza .= <<"EXTRA";
  344. \\newenvironment{postscript}{}{}
  345. \\pagestyle{empty}
  346. EXTRA
  347.  
  348. # Poner el atributo añadido a PostScript
  349. while ($cuerpo =~ /\\begin\{postscript\}/gsm) {
  350.  
  351.     my $corchetes = $1;
  352.     my($pos_inicial, $pos_final) = ($-[1], $+[1]);      # posición donde están los corchetes
  353.  
  354.     if (not $corchetes) {
  355.         $pos_inicial = $pos_final = $+[0];              # si no hay corchetes, nos ponemos al final de \begin
  356.     }
  357.     if (not $corchetes  or  $corchetes =~ /\[\s*\]/) {  # si no hay corchetes, o están vacíos,
  358.         $corchetes = "[$graphics-$exacount}]";          # ponemos los nuestros
  359.     }
  360.     substr($cuerpo, $pos_inicial, $pos_final - $pos_inicial) = $corchetes;    
  361.     pos($cuerpo) = $pos_inicial + length $corchetes;    # reposicionamos la búsqueda de la exp. reg.
  362. }
  363. continue {
  364.     $exacount++;
  365. }
  366.  
  367. #---------------------- Extract source code in images -----------------#
  368. while ($cuerpo =~ /$BP\[.+?(?<img_src_name>$imageDir\/.+?-\d+)\}\](?<code>.+?)(?=^$EP)/gsm) {
  369.     open my $SALIDA, '>', "$+{'img_src_name'}$ext";
  370.     print $SALIDA <<"EOC";
  371. $cabeza\\begin{document}$+{'code'}\\end{document}
  372. EOC
  373. close $SALIDA;
  374. }
  375.  
  376. __END__
Coloreado en 0.018 segundos, usando GeSHi 1.0.8.4

Después de mucho pensar en el asunto de los anidados (son realmente un dolor de cabeza) me decidí por atacar el problema desde otro punto de vista:
  • Creo un hash con las palabras que deseo cambiar dentro de líneas que me dan problemas y recorro todo el archivo haciendo los cambios y lo guardo.
  • Como tengo varios entornos donde no deseo hacer cambios (postscript, y tikzpicture}), leo el archivo por líneas y usando for y quitando algunas claves del hash hago los cambios dentro de lo que no deseo modificar y guardo el archivo.
  • Vuelvo a abrir el archivo y con expresiones regulares modifico lo que me interesa, ya no tengo anidados, puesto que modifiqué las palabras que me interferían y lo vuelvo a guardar.
  • Creo un nuevo hash para volver las palabras a la normalidad solo dentro de \begin{postscript} ... \end{postscript} y lo guardo. Ahora está todo como lo deseo.
  • Vuelvo a abrir el archivo y extraigo lo que me interesa.
Agradezco enormemente a explorer y a los distintos usuarios que escriben en el foro, revisar soluciones de otros asuntos ayuda bastante.
Saludos.
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Publicidad

Re: Expresión regular para texto anidado

Notapor explorer » 2015-01-03 19:56 @872

Sigo sin entender el porqué de las líneas que graban a disco e inmediatamente lo vuelven a leer... no es necesario tanto lío.

Ejemplo:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. # Write
  2. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  3.    print   $SALIDA "$archivo";
  4. close $SALIDA;
  5.  
  6. #--------------------- Coment Verbatim environment --------------------#
  7.  
  8. my @lineas;
  9. {
  10.    open my $FILE,'<',"$tempDir/$name-tmp$ext";
  11.    @lineas = <$FILE>;
  12.    close $FILE;
  13. }
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
se puede reducir a
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my @lineas = split /\n/, $archivo;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Expresión regular para texto anidado

Notapor pablgonz » 2015-01-04 11:19 @513

Con el cambio que me propones ya no funciona, con el script así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use v5.18;
  3. use re 'eval';
  4. use autodie;                    # muere si ocurre un error
  5. use File::Basename;             # separa el archivo de entrada
  6. use Config;
  7.  
  8. # Constantes
  9. my $tempDir = ".";              # temporary directory
  10. my $imageDir = "images";        # where to save the images
  11. my $ignore = "ignore";          # ignore verbatim environment
  12. my $exacount = 1;               # Counter for images
  13. my $other = "other";            # otro entorno
  14. #--------------------- Arreglo de la extensión -------------------------
  15. my @SuffixList = ('.tex', '', '.ltx');               # posible extensión
  16. my ($name, $path, $ext) = fileparse($ARGV[0], @SuffixList);
  17. $ext = '.tex' if not $ext;
  18.  
  19. #---------------- Creamos el directorio para las imágenes --------------
  20. -e $imageDir or mkdir($imageDir,0744) or die "No puedo crear $imageDir: $!\n";
  21. # Constantes para regex
  22. my $BP = '\\\\begin{postscript}';
  23. my $EP = '\\\\end{postscript}';
  24. my $BPL = '\begin{postscript}';
  25. my $EPL = '\end{postscript}';
  26. my $sipgf = 'pgfpicture';
  27. my $nopgf = 'pgfinterruptpicture';
  28. my $graphics = "graphic=\{\[scale=1\]$imageDir/$name-fig";
  29.  
  30. #------------ Creamos un hash con los cambios para verbatim -----------#
  31. my %cambios = (
  32. # pst/tikz set    
  33.     '\psset'                    => '\PSSET',
  34.     '\tikzset'                  => '\TIKZSET',
  35. # pspicture    
  36.     '\pspicture'                => '\TRICKS',
  37.     '\endpspicture'             => '\ENDTRICKS',
  38. # pspicture
  39.     '\begin{pspicture'          => '\begin{TRICKS',
  40.     '\end{pspicture'            => '\end{TRICKS',
  41. # postscript
  42.     '\begin{postscript}'        => '\begin{POSTRICKS}',
  43.     '\end{postscript}'          => '\end{POSTRICKS}',
  44. # $other    
  45.     "\\begin\{$other"           => '\begin{OTHER',
  46.     "\\end\{$other"             => '\end{OTHER',
  47. # document
  48.     '\begin{document}'          => '\begin{DOCTRICKS}',
  49.     '\end{document}'            => '\end{DOCTRICKS}',
  50. # tikzpicture
  51.     '\begin{tikzpicture}'       => '\begin{TIKZPICTURE}',
  52.     '\end{tikzpicture}'         => '\end{TIKZPICTURE}',
  53. # pgfinterruptpicture
  54.     '\begin{pgfinterruptpicture'=> '\begin{PGFINTERRUPTPICTURE',
  55.     '\end{pgfinterruptpicture'  => '\end{PGFINTERRUPTPICTURE',
  56. # pgfpicture
  57.     '\begin{pgfpicture}'        => '\begin{PGFPICTURE}',
  58.     '\end{pgfpicture}'          => '\end{PGFPICTURE}',
  59. # ganttchart
  60.     '\begin{ganttchart}'        => '\begin{GANTTCHART}',
  61.     '\end{ganttchart}'          => '\end{GANTTCHART}',
  62. # circuitikz
  63.     '\begin{circuitikz}'        => '\begin{CIRCUITIKZ}',
  64.     '\end{circuitikz}'          => '\end{CIRCUITIKZ}',
  65. # forest    
  66.     '\begin{forest}'            => '\begin{FOREST}',
  67.     '\end{forest}'              => '\end{FOREST}',
  68. # tikzcd
  69.     '\begin{tikzcd}'            => '\begin{TIKZCD}',
  70.     '\end{tikzcd}'              => '\end{TIKZCD}',
  71. # dependency
  72.     '\begin{dependency}'        => '\begin{DEPENDENCY}',
  73.     '\end{dependency}'          => '\end{DEPENDENCY}',
  74. );
  75.  
  76. #------------------------ Coment inline Verbatim ----------------------#
  77. open my $ENTRADA, '<', "$name$ext";
  78. my $archivo;
  79. {
  80.     local $/;
  81.     $archivo = <$ENTRADA>;
  82. }
  83. close $ENTRADA;
  84.  
  85. # Variables y constantes
  86. my $no_del = "\0";
  87. my $del    = $no_del;
  88.  
  89. # Reglas
  90. my $llaves      = qr/\{ .+? \}                                                                  /x;
  91. my $no_corchete = qr/(?:\[ .+? \])?                                                             /x;
  92. my $delimitador = qr/\{ (?<del>.+?) \}                                                          /x;
  93. my $verb        = qr/(spv|v|V)erb [*]?                                                          /ix;
  94. my $lst         = qr/lstinline (?!\*) $no_corchete                                              /ix;
  95. my $mint        = qr/mint      (?!\*) $no_corchete $llaves                                      /ix;
  96. my $marca       = qr/\\ (?:$verb | $lst | $mint ) (\S) .+? \g{-1}                               /x;
  97. my $comentario  = qr/^ \s* \%+ .+? $                                                            /mx;
  98. my $definedel   = qr/\\ (?:   DefineShortVerb | lstMakeShortInline  ) $no_corchete $delimitador /ix;
  99. my $indefinedel = qr/\\ (?: UndefineShortVerb | lstDeleteShortInline) $llaves                   /ix;
  100.  
  101. while ($archivo =~
  102.         /   $marca
  103.         |   $comentario
  104.         |   $definedel
  105.         |   $indefinedel
  106.         |   $del .+? $del                                                       # delimitado
  107.         /pgmx) {
  108.  
  109.         my($pos_inicial, $pos_final) = ($-[0], $+[0]);                          # posiciones
  110.         my $encontrado = ${^MATCH};                                             # lo encontrado
  111.  
  112.     if ($encontrado =~ /$definedel/){                                           # definimos delimitador
  113.                         $del = $+{del};
  114.                         $del = "\Q$+{del}" if substr($del,0,1) ne '\\';         # es necesario "escapar" el delimitador
  115.                 }
  116.     elsif($encontrado =~ /$indefinedel/) {                                      # indefinimos delimitador
  117.                  $del = $no_del;                                      
  118.         }
  119.     else {                                                                      # aquí se hacen los cambios
  120.         while (my($busco, $cambio) = each %cambios) {
  121.                        $encontrado =~ s/\Q$busco\E/$cambio/g;                   # es necesario escapar $busco
  122.                         }
  123.         substr $archivo, $pos_inicial, $pos_final-$pos_inicial, $encontrado;     # insertamos los nuevos cambios
  124.  
  125.         pos($archivo)= $pos_inicial + length $encontrado;                        # re posicionamos la siguiente búsqueda
  126.         }
  127. }
  128.  
  129. # Write
  130. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  131.    print   $SALIDA "$archivo";
  132. close $SALIDA;
  133.  
  134. #--------------------- Coment Verbatim environment --------------------#
  135.  
  136. my @lineas;
  137. {
  138.    open my $FILE,'<',"$tempDir/$name-tmp$ext";
  139.    @lineas = <$FILE>;
  140.    close $FILE;
  141. }
  142.  
  143. # Verbatim environments
  144. my $ENTORNO  = qr/(?: (v|V)erbatim\*?| PSTexample | LTXexample| $ignore\*? | PSTcode | tcblisting\*? | spverbatim | minted | lstlisting | alltt | comment\*? | xcomment)/xi;
  145.  
  146. # postscript environment
  147. my $POSTSCRIPT = qr/(?: postscript)/xi;
  148.  
  149. # tikzpicture environment
  150. my $TIKZENV    = qr/(?: tikzpicture)/xi;
  151. #    
  152. my $DEL;
  153. # tcbverb verbatim
  154. my $tcbverb = qr/\\(?:tcboxverb|myverb)/;
  155. my $arg_brac = qr/(?:\[.+?\])?/;
  156. my $arg_curl = qr/\{(.+)\}/;          
  157.  
  158. # coment verbatim environment
  159. for (@lineas) {
  160.     if (/\\begin\{($ENTORNO)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  161.         while (my($busco, $cambio) = each %cambios) {
  162.             s/\Q$busco\E/$cambio/g;
  163.         }
  164.     }
  165. }
  166. # coment tcolorbox inline
  167. for (@lineas) {
  168.     if (m/$tcbverb$arg_brac$arg_curl/) {
  169.         while (my($busco, $cambio) = each %cambios) {
  170.             s/\Q$busco\E/$cambio/g;
  171.         }
  172.     } # close
  173.  }
  174. # remove postscript from hash
  175. delete @cambios{'\begin{postscript}','\end{postscript}'};
  176. # coment in postscript environment
  177. for (@lineas) {
  178.     if (/\\begin\{($POSTSCRIPT)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  179.         while (my($busco, $cambio) = each %cambios) {
  180.             s/\Q$busco\E/$cambio/g;
  181.         }
  182.     } # close postcript environment
  183. }
  184. # remove tikzpicture from hash
  185. delete @cambios{'\begin{tikzpicture}','\end{tikzpicture}'};
  186. # coment in tikzpicture environment
  187. for (@lineas) {
  188.     if (/\\begin\{($TIKZENV)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  189.         while (my($busco, $cambio) = each %cambios) {
  190.             s/\Q$busco\E/$cambio/g;
  191.         }
  192.     } # close TIKZ environment
  193. }
  194.  
  195. # Write file
  196. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  197. print   $SALIDA @lineas;
  198. close   $SALIDA;
  199.  
  200. ##--------------------------- PARTE 2 --------------------------------##
  201. #------------- Convert ALL into Postscript environments ---------------#
  202. open my $ENTRADA, '<', "$tempDir/$name-tmp$ext";
  203. my $archivo;
  204. {
  205.     local $/;
  206.     $archivo = <$ENTRADA>;
  207. }
  208. close $ENTRADA;
  209.  
  210. ## Partición del documento
  211.  
  212. my($cabeza,$cuerpo,$final) = $archivo =~ m/\A (.+?) (^\\begin{document} .+)(^\\end{document}.*)\z/msx;
  213.  
  214. # \pspicture to \begin{pspicture}
  215. $cuerpo =~ s/\\pspicture(\*)?(.+?)\\endpspicture/\\begin{pspicture$1}$2\\end{pspicture$1}/gmsx;
  216.  
  217. # pspicture to Postscript
  218. $cuerpo =~ s/
  219.     (
  220.         (?:\\psset\{[^\}]+\}.*?)?
  221.         (?:\\begin\{pspicture(\*)?\})
  222.                 .*?
  223.         (?:\\end\{pspicture(\*)?\})
  224.     )
  225.     /$BPL\n$1\n$EPL/gmsx;
  226.  
  227. # pgfpicture to Postscript
  228. $cuerpo =~ s/
  229.     (
  230.         \\begin{$sipgf}
  231.             .*?
  232.             (
  233.                 \\begin{$nopgf}
  234.                 .+?
  235.                 \\end{$nopgf}
  236.                 .*?
  237.             )*?
  238.         \\end{$sipgf}
  239.     )
  240.     /$BPL\n$1\n$EPL/gmsx;
  241.  
  242. # tikz to Postscript
  243. $cuerpo =~ s/
  244.      (
  245.         (?:\\tikzset(\{(?:\{.*?\}|[^\{])*\}).*?)? # si está lo guardo
  246.               (?:\\begin\{tikzpicture\})       # aquí comienza la búsqueda
  247.                             .*?                # guardo el contenido en $1
  248.                     (?:\\end\{tikzpicture\})   # termina la búsqueda
  249.                 ) # cierra $1
  250.                 /$BPL\n$1\n$EPL/gmsx;
  251.  
  252. # rest to Postscript
  253. my $export  = qr/(forest|ganttchart|tikzcd|circuitikz|dependency|$other\*?)/x;
  254.  
  255. $cuerpo =~ s/(\\begin\{($export)\} (.*?)  \\end\{\g{-2}\})/$BPL\n$1\n$EPL/gmsx;
  256.  
  257. # Write
  258. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  259.    print   $SALIDA "$cabeza$cuerpo$final";
  260. close $SALIDA;
  261.  
  262. ##---------------------------- PARTE 3 -------------------------------##
  263. #-------------------------- Reverse changes ---------------------------#
  264. my %cambios = (
  265. # pst/tikz set    
  266.     '\PSSET'                    =>      '\psset',
  267.     '\TIKZSET'                  =>      '\tikzset',                    
  268. # pspicture    
  269.     '\TRICKS'                   =>      '\pspicture',
  270.     '\ENDTRICKS'                =>      '\endpspicture',            
  271. # pspicture
  272.     '\begin{TRICKS'             =>      '\begin{pspicture',
  273.     '\end{TRICKS'               =>      '\end{pspicture',
  274. # $other    
  275.     '\begin{OTHER'              =>      "\\begin\{$other",             
  276.     '\end{OTHER'                =>      "\\end\{$other",
  277. # document
  278.     '\begin{DOCTRICKS}'         =>      '\begin{document}',
  279.     '\end{DOCTRICKS}'           =>      '\end{document}',
  280. # tikzpicture
  281.     '\begin{TIKZPICTURE}'       =>      '\begin{tikzpicture}',
  282.     '\end{TIKZPICTURE}'         =>      '\end{tikzpicture}',
  283. # pgfinterruptpicture
  284.     '\begin{PGFINTERRUPTPICTURE'=>      '\begin{pgfinterruptpicture',
  285.     '\end{PGFINTERRUPTPICTURE'  =>      '\end{pgfinterruptpicture',
  286. # pgfpicture
  287.     '\begin{PGFPICTURE}'        =>      '\begin{pgfpicture}',
  288.     '\end{PGFPICTURE}'          =>      '\end{pgfpicture}',
  289. # ganttchart
  290.     '\begin{GANTTCHART}'        =>      '\begin{ganttchart}',
  291.     '\end{GANTTCHART}'          =>      '\end{ganttchart}',
  292. # circuitikz
  293.     '\begin{CIRCUITIKZ}'        =>      '\begin{circuitikz}',
  294.     '\end{CIRCUITIKZ}'          =>      '\end{circuitikz}',
  295. # forest    
  296.     '\begin{FOREST}'            =>      '\begin{forest}',
  297.     '\end{FOREST}'              =>      '\end{forest}',
  298. # tikzcd
  299.     '\begin{TIKZCD}'            =>      '\begin{tikzcd}',
  300.     '\end{TIKZCD}'              =>      '\end{tikzcd}',
  301. # dependency
  302.     '\begin{DEPENDENCY}'        =>      '\begin{dependency}',
  303.     '\end{DEPENDENCY}'          =>      '\end{dependency}',
  304. );
  305.  
  306. #-------------------------- Back Postscript ---------------------------#
  307. my @lineas;
  308. {
  309.    open my $FILE,'<',"$tempDir/$name-tmp$ext";
  310.    @lineas = <$FILE>;
  311.    close $FILE;
  312. }
  313. # reverse in postscript environment
  314. for (@lineas) {
  315.     if (/\\begin\{($POSTSCRIPT)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  316.         while (my($busco, $cambio) = each %cambios) {
  317.             s/\Q$busco\E/$cambio/g;
  318.         }
  319.     } # close postscript environment changes
  320. }
  321.    
  322. # Write
  323. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  324. print   $SALIDA @lineas;
  325. close   $SALIDA;
  326.  
  327. ##---------------------------- PARTE 4 -------------------------------##
  328. #--------------- Extract source code for PST/PGF/TIKZ -----------------#
  329. open my $ENTRADA, '<',"$tempDir/$name-tmp$ext";
  330. my $archivo;
  331. {
  332.     local $/;
  333.     $archivo = <$ENTRADA>;
  334. }
  335. close $ENTRADA;
  336.  
  337. # Dividir el archivo
  338. my($cabeza,$cuerpo,$final) = $archivo =~ m/\A (.+?) (^\\begin{document} .+)(^\\end{document}.*)\z/msx;
  339.  
  340. $cabeza .= <<"EXTRA";
  341. \\pagestyle{empty}
  342. EXTRA
  343.  
  344. # Poner el atributo añadido a PostScript
  345. while ($cuerpo =~ /\\begin\{postscript\}/gsm) {
  346.  
  347.     my $corchetes = $1;
  348.     my($pos_inicial, $pos_final) = ($-[1], $+[1]);      # posición donde están los corchetes
  349.  
  350.     if (not $corchetes) {
  351.         $pos_inicial = $pos_final = $+[0];              # si no hay corchetes, nos ponemos al final de \begin
  352.     }
  353.     if (not $corchetes  or  $corchetes =~ /\[\s*\]/) {  # si no hay corchetes, o están vacíos,
  354.         $corchetes = "[$graphics-$exacount}]";          # ponemos los nuestros
  355.     }
  356.     substr($cuerpo, $pos_inicial, $pos_final - $pos_inicial) = $corchetes;    
  357.     pos($cuerpo) = $pos_inicial + length $corchetes;    # reposicionamos la búsqueda de la exp. reg.
  358. }
  359. continue {
  360.     $exacount++;
  361. }
  362.  
  363. #---------------------- Extract source code in images -----------------#
  364. while ($cuerpo =~ /$BP\[.+?(?<img_src_name>$imageDir\/.+?-\d+)\}\](?<code>.+?)(?=^$EP)/gsm) {
  365.     open my $SALIDA, '>', "$+{'img_src_name'}$ext";
  366.     print $SALIDA <<"EOC";
  367. $cabeza\\begin{document}$+{'code'}\\end{document}
  368. EOC
  369. close $SALIDA;
  370. }
  371.  
  372. __END__
Coloreado en 0.011 segundos, usando GeSHi 1.0.8.4
Teniendo este archivo de entrada:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. % Las líneas que están en
  3. % éste sector no deben modificarse
  4. \usepackage{pst-all}
  5. \usepackage[siunitx]{circuitikz}
  6. \begin{document}
  7. Lo que sigue no debe quedar dentro de Postscript
  8. \begin{verbatim}
  9. \begin{tikzpicture}
  10. code
  11. \end{tikzpicture}
  12. \end{verbatim}
  13.  
  14. Lo que sigue no debe quedar dentro de Postscript
  15. \begin{verbatim}
  16. \begin{pspicture}(-11,0)(11,0)  
  17. code
  18. \end{pspicture}
  19. \end{verbatim}
  20.  
  21. Cambiamos ésta línea \verb|\begin{pspicture*} o \begin{tikzpicture} \begin{other}|
  22. y lo que sigue a mayuscula
  23. %\begin{tikzpicture}
  24. % code
  25. %\end{tikzpicture}
  26.  
  27. Este entono no debe quedar anidado
  28. \begin{postscript}
  29. \psset{code}
  30. \begin{pspicture}(-11,0)(11,0)  
  31. code
  32. \end{pspicture}
  33. \end{postscript}
  34.  
  35. Este entono no debe quedar anidado
  36. \begin{postscript}
  37. \begin{tikzpicture}[scale=2]
  38. code
  39. \end{tikzpicture}
  40. \end{postscript}
  41.  
  42. Esto debe quedar dentro de Postscript
  43. \begin{tikzpicture}
  44. code
  45. \end{tikzpicture}
  46.  
  47. Esto debe quedar dentro de Postscript
  48. \psset{xunit=0.5cm, yunit=0.5cm, yAxis=false}
  49. \begin{pspicture}(-11,0)(11,0)  
  50. \psaxes[Dx=5, subticks=5]{<->}(0,0)(-11,0)(11,0)
  51. \psline[linewidth=3pt, linecolor=cyan]{o->}(-2,0)(11,0)
  52. \end{pspicture}
  53.  
  54. Este entono no debe quedar anidado
  55. \begin{postscript}
  56. \begin{tikzcd}
  57. \shadedraw [shading=ball] (0,0) circle (2cm);
  58. \end{tikzcd}
  59. \end{postscript}
  60.  
  61. Este entono no debe quedar anidado dentro de PostScript
  62. \begin{tikzpicture}
  63. \begin{circuitikz}
  64. code
  65. \end{circuitikz}
  66. \end{tikzpicture}
  67.  
  68. Esto debe quedar dentro de Postscript
  69. \begin{circuitikz}
  70. code
  71. \end{circuitikz}
  72.  
  73. Final del test
  74. \end{document}
  75. No tocar
  76. \begin{pspicture}(-11,0)(11,0)  
  77. code
  78. \end{pspicture}
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
obtengo éste archivo de salida:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. % Las líneas que están en
  3. % éste sector no deben modificarse
  4. \usepackage{pst-all}
  5. \usepackage[siunitx]{circuitikz}
  6. \begin{document}
  7. Lo que sigue no debe quedar dentro de Postscript
  8. \begin{verbatim}
  9. \begin{TIKZPICTURE}
  10. code
  11. \end{TIKZPICTURE}
  12. \end{verbatim}
  13.  
  14. Lo que sigue no debe quedar dentro de Postscript
  15. \begin{verbatim}
  16. \begin{TRICKS}(-11,0)(11,0)    
  17. code
  18. \end{TRICKS}
  19. \end{verbatim}
  20.  
  21. Cambiamos ésta línea \verb|\begin{TRICKS*} o \begin{TIKZPICTURE} \begin{OTHER}|
  22. y lo que sigue a mayuscula
  23. %\begin{TIKZPICTURE}
  24. % code
  25. %\end{TIKZPICTURE}
  26.  
  27. Este entono no debe quedar anidado
  28. \begin{postscript}
  29. \psset{code}
  30. \begin{pspicture}(-11,0)(11,0)  
  31. code
  32. \end{pspicture}
  33. \end{postscript}
  34.  
  35. Este entono no debe quedar anidado
  36. \begin{postscript}
  37. \begin{tikzpicture}[scale=2]
  38. code
  39. \end{tikzpicture}
  40. \end{postscript}
  41.  
  42. Esto debe quedar dentro de Postscript
  43. \begin{postscript}
  44. \begin{tikzpicture}
  45. code
  46. \end{tikzpicture}
  47. \end{postscript}
  48.  
  49. Esto debe quedar dentro de Postscript
  50. \begin{postscript}
  51. \psset{xunit=0.5cm, yunit=0.5cm, yAxis=false}
  52. \begin{pspicture}(-11,0)(11,0)  
  53. \psaxes[Dx=5, subticks=5]{<->}(0,0)(-11,0)(11,0)
  54. \psline[linewidth=3pt, linecolor=cyan]{o->}(-2,0)(11,0)
  55. \end{pspicture}
  56. \end{postscript}
  57.  
  58. Este entono no debe quedar anidado
  59. \begin{postscript}
  60. \begin{tikzcd}
  61. \shadedraw [shading=ball] (0,0) circle (2cm);
  62. \end{tikzcd}
  63. \end{postscript}
  64.  
  65. Este entono no debe quedar anidado dentro de PostScript
  66. \begin{postscript}
  67. \begin{tikzpicture}
  68. \begin{circuitikz}
  69. code
  70. \end{circuitikz}
  71. \end{tikzpicture}
  72. \end{postscript}
  73.  
  74. Esto debe quedar dentro de Postscript
  75. \begin{postscript}
  76. \begin{circuitikz}
  77. code
  78. \end{circuitikz}
  79. \end{postscript}
  80.  
  81. Final del test
  82. \end{document}
  83. No tocar
  84. \begin{pspicture}(-11,0)(11,0)  
  85. code
  86. \end{pspicture}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Es decir, todo lo que me interesa está dentro de \begin{postscript} ... \end{postscript}.
Quizás se puede hacer más corto y reducir la cantidad de veces que abro y cierro el archivo. A final deseo agregar
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my $grap="\\includegraphics[scale=1]{$name-fig-";
  2. my $close = '}';
  3. my $IMGno = 1;
  4. $cuerpo =~ s/$BP.+?$EP/$grap.$IMGno++.$close/gemsx;
  5. print $cuerpo;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
para crear un archivo en el cual TODOS los \begin{postscript} ... \end{postscript} se cambien por \includegraphics[scale=1]{$name-fig-1}, \includegraphics[scale=1]{$name-fig-2}, etc.
Saludos
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Expresión regular para texto anidado

Notapor pablgonz » 2015-01-04 20:52 @911

Le di vueltas toda la tarde, pero no pude reducir la cantidad de veces que abro y cierro el archivo. Esta es la versión final:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use v5.18;
  3. use re 'eval';
  4. use autodie;                    # muere si ocurre un error
  5. use File::Basename;             # separa el archivo de entrada
  6. use Config;
  7.  
  8. # Constantes
  9. my $tempDir = ".";              # temporary directory
  10. my $imageDir = "images";        # where to save the images
  11. my $ignore = "ignore";          # ignore verbatim environment
  12. my $exacount = 1;               # Counter for images
  13. my $other = "other";            # otro entorno
  14. #--------------------- Arreglo de la extensión -------------------------
  15. my @SuffixList = ('.tex', '', '.ltx');               # posible extensión
  16. my ($name, $path, $ext) = fileparse($ARGV[0], @SuffixList);
  17. $ext = '.tex' if not $ext;
  18.  
  19. #---------------- Creamos el directorio para las imágenes --------------
  20. -e $imageDir or mkdir($imageDir,0744) or die "No puedo crear $imageDir: $!\n";
  21. # Constantes para regex
  22. my $BP = '\\\\begin{postscript}';
  23. my $EP = '\\\\end{postscript}';
  24. my $BPL = '\begin{postscript}';
  25. my $EPL = '\end{postscript}';
  26. my $sipgf = 'pgfpicture';
  27. my $nopgf = 'pgfinterruptpicture';
  28. my $graphics = "graphic=\{\[scale=1\]$imageDir/$name-fig";
  29.  
  30. #------------ Creamos un hash con los cambios para verbatim -----------#
  31. my %cambios = (
  32. # pst/tikz set    
  33.         '\psset'                    => '\PSSET',
  34.         '\tikzset'                  => '\TIKZSET',
  35. # pspicture    
  36.         '\pspicture'                => '\TRICKS',
  37.         '\endpspicture'             => '\ENDTRICKS',
  38. # pspicture
  39.         '\begin{pspicture'          => '\begin{TRICKS',
  40.         '\end{pspicture'            => '\end{TRICKS',
  41. # postscript
  42.         '\begin{postscript}'        => '\begin{POSTRICKS}',
  43.         '\end{postscript}'          => '\end{POSTRICKS}',
  44. # $other    
  45.         "\\begin\{$other"           => '\begin{OTHER',
  46.         "\\end\{$other"             => '\end{OTHER',
  47. # document
  48.         '\begin{document}'          => '\begin{DOCTRICKS}',
  49.         '\end{document}'            => '\end{DOCTRICKS}',
  50. # tikzpicture
  51.         '\begin{tikzpicture}'       => '\begin{TIKZPICTURE}',
  52.         '\end{tikzpicture}'         => '\end{TIKZPICTURE}',
  53. # pgfinterruptpicture
  54.         '\begin{pgfinterruptpicture'=> '\begin{PGFINTERRUPTPICTURE',
  55.         '\end{pgfinterruptpicture'  => '\end{PGFINTERRUPTPICTURE',
  56. # pgfpicture
  57.         '\begin{pgfpicture}'        => '\begin{PGFPICTURE}',
  58.         '\end{pgfpicture}'          => '\end{PGFPICTURE}',
  59. # ganttchart
  60.         '\begin{ganttchart}'        => '\begin{GANTTCHART}',
  61.         '\end{ganttchart}'          => '\end{GANTTCHART}',
  62. # circuitikz
  63.         '\begin{circuitikz}'        => '\begin{CIRCUITIKZ}',
  64.         '\end{circuitikz}'          => '\end{CIRCUITIKZ}',
  65. # forest    
  66.         '\begin{forest}'            => '\begin{FOREST}',
  67.         '\end{forest}'              => '\end{FOREST}',
  68. # tikzcd
  69.         '\begin{tikzcd}'            => '\begin{TIKZCD}',
  70.         '\end{tikzcd}'              => '\end{TIKZCD}',
  71. # dependency
  72.         '\begin{dependency}'        => '\begin{DEPENDENCY}',
  73.         '\end{dependency}'          => '\end{DEPENDENCY}',
  74. );
  75.  
  76. #------------------------ Coment inline Verbatim ----------------------#
  77. open my $ENTRADA, '<', "$name$ext";
  78. my $archivo;
  79. {
  80.         local $/;
  81.         $archivo = <$ENTRADA>;
  82. }
  83. close $ENTRADA;
  84.  
  85. # Variables y constantes
  86. my $no_del = "\0";
  87. my $del    = $no_del;
  88.  
  89. # Reglas
  90. my $llaves      = qr/\{ .+? \}                                                                  /x;
  91. my $no_corchete = qr/(?:\[ .+? \])?                                                             /x;
  92. my $delimitador = qr/\{ (?<del>.+?) \}                                                          /x;
  93. my $verb        = qr/(spv|v|V)erb [*]?                                                          /ix;
  94. my $lst         = qr/lstinline (?!\*) $no_corchete                                              /ix;
  95. my $mint        = qr/mint      (?!\*) $no_corchete $llaves                                      /ix;
  96. my $marca       = qr/\\ (?:$verb | $lst | $mint ) (\S) .+? \g{-1}                               /x;
  97. my $comentario  = qr/^ \s* \%+ .+? $                                                            /mx;
  98. my $definedel   = qr/\\ (?:   DefineShortVerb | lstMakeShortInline  ) $no_corchete $delimitador /ix;
  99. my $indefinedel = qr/\\ (?: UndefineShortVerb | lstDeleteShortInline) $llaves                   /ix;
  100.  
  101. while ($archivo =~
  102.                 /   $marca
  103.                 |   $comentario
  104.                 |   $definedel
  105.                 |   $indefinedel
  106.                 |   $del .+? $del                                                       # delimitado
  107.                 /pgmx) {
  108.  
  109.                 my($pos_inicial, $pos_final) = ($-[0], $+[0]);                          # posiciones
  110.                 my $encontrado = ${^MATCH};                                             # lo encontrado
  111.  
  112.         if ($encontrado =~ /$definedel/){                                           # definimos delimitador
  113.                                                 $del = $+{del};
  114.                                                 $del = "\Q$+{del}" if substr($del,0,1) ne '\\';         # es necesario "escapar" el delimitador
  115.                                 }
  116.         elsif($encontrado =~ /$indefinedel/) {                                      # indefinimos delimitador
  117.                                  $del = $no_del;                                      
  118.                 }
  119.         else {                                                                      # aquí se hacen los cambios
  120.                 while (my($busco, $cambio) = each %cambios) {
  121.                                            $encontrado =~ s/\Q$busco\E/$cambio/g;                   # es necesario escapar $busco
  122.                                                 }
  123.                 substr $archivo, $pos_inicial, $pos_final-$pos_inicial, $encontrado;     # insertamos los nuevos cambios
  124.  
  125.                 pos($archivo)= $pos_inicial + length $encontrado;                        # re posicionamos la siguiente búsqueda
  126.                 }
  127. }
  128.  
  129. # Write
  130. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  131.    print   $SALIDA "$archivo";
  132. close $SALIDA;
  133.  
  134. #--------------------- Coment Verbatim environment --------------------#
  135.  
  136. my @lineas;
  137. {
  138.    open my $FILE,'<',"$tempDir/$name-tmp$ext";
  139.    @lineas = <$FILE>;
  140.    close $FILE;
  141. }
  142.  
  143. # Verbatim environments
  144. my $ENTORNO  = qr/(?: (v|V)erbatim\*?| PSTexample | LTXexample| $ignore\*? | PSTcode | tcblisting\*? | spverbatim | minted | lstlisting | alltt | comment\*? | xcomment)/xi;
  145.  
  146. # postscript environment
  147. my $POSTSCRIPT = qr/(?: postscript)/xi;
  148.  
  149. # tikzpicture environment
  150. my $TIKZENV    = qr/(?: tikzpicture)/xi;
  151. #    
  152. my $DEL;
  153. # tcbverb verbatim
  154. my $tcbverb = qr/\\(?:tcboxverb|myverb)/;
  155. my $arg_brac = qr/(?:\[.+?\])?/;
  156. my $arg_curl = qr/\{(.+)\}/;          
  157.  
  158. # coment verbatim environment
  159. for (@lineas) {
  160.         if (/\\begin\{($ENTORNO)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  161.                 while (my($busco, $cambio) = each %cambios) {
  162.                         s/\Q$busco\E/$cambio/g;
  163.                 }
  164.         }
  165. }
  166. # coment tcolorbox inline
  167. for (@lineas) {
  168.         if (m/$tcbverb$arg_brac$arg_curl/) {
  169.                 while (my($busco, $cambio) = each %cambios) {
  170.                         s/\Q$busco\E/$cambio/g;
  171.                 }
  172.         } # close
  173.  }
  174. # remove postscript from hash
  175. delete @cambios{'\begin{postscript}','\end{postscript}'};
  176. # coment in postscript environment
  177. for (@lineas) {
  178.         if (/\\begin\{($POSTSCRIPT)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  179.                 while (my($busco, $cambio) = each %cambios) {
  180.                         s/\Q$busco\E/$cambio/g;
  181.                 }
  182.         } # close postcript environment
  183. }
  184. # remove tikzpicture from hash
  185. delete @cambios{'\begin{tikzpicture}','\end{tikzpicture}'};
  186. # coment in tikzpicture environment
  187. for (@lineas) {
  188.         if (/\\begin\{($TIKZENV)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  189.                 while (my($busco, $cambio) = each %cambios) {
  190.                         s/\Q$busco\E/$cambio/g;
  191.                 }
  192.         } # close TIKZ environment
  193. }
  194.  
  195. # Write file
  196. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  197. print   $SALIDA @lineas;
  198. close   $SALIDA;
  199.  
  200. ##--------------------------- PARTE 2 --------------------------------##
  201. #------------- Convert ALL into Postscript environments ---------------#
  202. open my $ENTRADA, '<', "$tempDir/$name-tmp$ext";
  203. my $archivo;
  204. {
  205.         local $/;
  206.         $archivo = <$ENTRADA>;
  207. }
  208. close $ENTRADA;
  209.  
  210. ## Partición del documento
  211.  
  212. my($cabeza,$cuerpo,$final) = $archivo =~ m/\A (.+?) (\\begin{document} .+?)(\\end{document}.*)\z/msx;
  213.  
  214. # \pspicture to \begin{pspicture}
  215. $cuerpo =~ s/\\pspicture(\*)?(.+?)\\endpspicture/\\begin{pspicture$1}$2\\end{pspicture$1}/gmsx;
  216.  
  217. # pspicture to Postscript
  218. $cuerpo =~ s/
  219.         (
  220.                 (?:\\psset\{[^\}]+\}.*?)?
  221.                 (?:\\begin\{pspicture(\*)?\})
  222.                                 .*?
  223.                 (?:\\end\{pspicture(\*)?\})
  224.         )
  225.         /$BPL\n$1\n$EPL/gmsx;
  226.  
  227. # pgfpicture to Postscript
  228. $cuerpo =~ s/
  229.         (
  230.                 \\begin{$sipgf}
  231.                         .*?
  232.                         (
  233.                                 \\begin{$nopgf}
  234.                                 .+?
  235.                                 \\end{$nopgf}
  236.                                 .*?
  237.                         )*?
  238.                 \\end{$sipgf}
  239.         )
  240.         /$BPL\n$1\n$EPL/gmsx;
  241.  
  242. # tikz to Postscript
  243. $cuerpo =~ s/
  244.          (
  245.                 (?:\\tikzset(\{(?:\{.*?\}|[^\{])*\}).*?)? # si está lo guardo
  246.                           (?:\\begin\{tikzpicture\})       # aquí comienza la búsqueda
  247.                                                         .*?                # guardo el contenido en $1
  248.                                         (?:\\end\{tikzpicture\})   # termina la búsqueda
  249.                                 ) # cierra $1
  250.                                 /$BPL\n$1\n$EPL/gmsx;
  251.  
  252. # rest to Postscript
  253. my $export  = qr/(forest|ganttchart|tikzcd|circuitikz|dependency|$other\*?)/x;
  254.  
  255. $cuerpo =~ s/(\\begin\{($export)\} (.*?)  \\end\{\g{-2}\})/$BPL\n$1\n$EPL/gmsx;
  256.  
  257. # Write
  258. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  259.    print   $SALIDA "$cabeza$cuerpo$final";
  260. close $SALIDA;
  261.  
  262. ##---------------------------- PARTE 3 -------------------------------##
  263. #-------------------------- Reverse changes ---------------------------#
  264. my %cambios = (
  265. # pst/tikz set    
  266.         '\PSSET'                    =>      '\psset',
  267.         '\TIKZSET'                  =>      '\tikzset',                    
  268. # pspicture    
  269.         '\TRICKS'                   =>      '\pspicture',
  270.         '\ENDTRICKS'                =>      '\endpspicture',            
  271. # pspicture
  272.         '\begin{TRICKS'             =>      '\begin{pspicture',
  273.         '\end{TRICKS'               =>      '\end{pspicture',
  274. # $other    
  275.         '\begin{OTHER'              =>      "\\begin\{$other",            
  276.         '\end{OTHER'                =>      "\\end\{$other",
  277. # document
  278.         '\begin{DOCTRICKS}'         =>      '\begin{document}',
  279.         '\end{DOCTRICKS}'           =>      '\end{document}',
  280. # tikzpicture
  281.         '\begin{TIKZPICTURE}'       =>      '\begin{tikzpicture}',
  282.         '\end{TIKZPICTURE}'         =>      '\end{tikzpicture}',
  283. # pgfinterruptpicture
  284.         '\begin{PGFINTERRUPTPICTURE'=>      '\begin{pgfinterruptpicture',
  285.         '\end{PGFINTERRUPTPICTURE'  =>      '\end{pgfinterruptpicture',
  286. # pgfpicture
  287.         '\begin{PGFPICTURE}'        =>      '\begin{pgfpicture}',
  288.         '\end{PGFPICTURE}'          =>      '\end{pgfpicture}',
  289. # ganttchart
  290.         '\begin{GANTTCHART}'        =>      '\begin{ganttchart}',
  291.         '\end{GANTTCHART}'          =>      '\end{ganttchart}',
  292. # circuitikz
  293.         '\begin{CIRCUITIKZ}'        =>      '\begin{circuitikz}',
  294.         '\end{CIRCUITIKZ}'          =>      '\end{circuitikz}',
  295. # forest    
  296.         '\begin{FOREST}'            =>      '\begin{forest}',
  297.         '\end{FOREST}'              =>      '\end{forest}',
  298. # tikzcd
  299.         '\begin{TIKZCD}'            =>      '\begin{tikzcd}',
  300.         '\end{TIKZCD}'              =>      '\end{tikzcd}',
  301. # dependency
  302.         '\begin{DEPENDENCY}'        =>      '\begin{dependency}',
  303.         '\end{DEPENDENCY}'          =>      '\end{dependency}',
  304. );
  305.  
  306. #-------------------------- Back Postscript ---------------------------#
  307. my @lineas;
  308. {
  309.    open my $FILE,'<',"$tempDir/$name-tmp$ext";
  310.    @lineas = <$FILE>;
  311.    close $FILE;
  312. }
  313. # reverse in postscript environment
  314. for (@lineas) {
  315.         if (/\\begin\{($POSTSCRIPT)(?{ $DEL = "\Q$^N" })\}/ .. /\\end\{$DEL\}/) {
  316.                 while (my($busco, $cambio) = each %cambios) {
  317.                         s/\Q$busco\E/$cambio/g;
  318.                 }
  319.         } # close postscript environment changes
  320. }
  321.    
  322. # Write
  323. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  324. print   $SALIDA @lineas;
  325. close   $SALIDA;
  326.  
  327. ##---------------------------- PARTE 4 -------------------------------##
  328. #--------------- Extract source code for PST/PGF/TIKZ -----------------#
  329. open my $ENTRADA, '<',"$tempDir/$name-tmp$ext";
  330. my $archivo;
  331. {
  332.         local $/;
  333.         $archivo = <$ENTRADA>;
  334. }
  335. close $ENTRADA;
  336.  
  337. # Dividir el archivo
  338. my($cabeza,$cuerpo,$final) = $archivo =~ m/\A (.*?) (\\begin{document} .*?)(\\end{document}.*)\z/msx;
  339.  
  340. # Poner el atributo añadido a PostScript
  341. while ($cuerpo =~ /\\begin\{postscript\}/gsm) {
  342.  
  343.         my $corchetes = $1;
  344.         my($pos_inicial, $pos_final) = ($-[1], $+[1]);      # posición donde están los corchetes
  345.  
  346.         if (not $corchetes) {
  347.                 $pos_inicial = $pos_final = $+[0];              # si no hay corchetes, nos ponemos al final de \begin
  348.         }
  349.         if (not $corchetes  or  $corchetes =~ /\[\s*\]/) {  # si no hay corchetes, o están vacíos,
  350.                 $corchetes = "[$graphics-$exacount}]";          # ponemos los nuestros
  351.         }
  352.         substr($cuerpo, $pos_inicial, $pos_final - $pos_inicial) = $corchetes;    
  353.         pos($cuerpo) = $pos_inicial + length $corchetes;    # reposicionamos la búsqueda de la exp. reg.
  354. }
  355. continue {
  356.         $exacount++;
  357. }
  358.  
  359. #---------------------- Extract source code in images -----------------#
  360. while ($cuerpo =~ /$BP\[.+?(?<img_src_name>$imageDir\/.+?-\d+)\}\](?<code>.+?)(?=^$EP)/gsm) {
  361.         open my $SALIDA, '>', "$+{'img_src_name'}$ext";
  362.         print $SALIDA <<"EOC";
  363. $cabeza\\pagestyle{empty}\n\\begin{document}$+{'code'}\\end{document}
  364. EOC
  365. close $SALIDA;
  366. }
  367.  
  368. #----------------- Convert Postscript to includegraphics --------------#
  369. my $grap="\\includegraphics[scale=1]{$name-fig-";
  370. my $close = '}';
  371. my $IMGno = 1;
  372. $cuerpo =~ s/$BP.+?$EP/$grap.$IMGno++.$close/gemsx;
  373.  
  374. #------------------------ Clean output file  --------------------------#
  375. # append postscript to hash
  376. $cambios{'\begin{POSTRICKS}'} = '\begin{postscript}';
  377. $cambios{'\end{POSTRICKS}'} = '\end{postscript}';
  378.  
  379. # Constantes
  380. my $BEGINDOC = quotemeta('\begin{document}');
  381. my $USEPACK  = quotemeta('\usepackage');
  382. my $REQPACK  = quotemeta('\usepackage');
  383. my $GRAPHICX = quotemeta('{graphicx}');
  384.  
  385. # Exp. Reg.
  386. my $CORCHETES = qr/\[ [^]]*? \]/x;
  387. my $PALABRAS  = qr/\b (?: pst-\w+ | pstricks (?: -add )? | psfrag |psgo |vaucanson-g| auto-pst-pdf | graphicx )/x;
  388. my $FAMILIA   = qr/\{ \s* $PALABRAS (?: \s* [,] \s* $PALABRAS )* \s* \}/x;
  389.  
  390. # comentar
  391. $cabeza =~ s/ ^ ($USEPACK $CORCHETES $GRAPHICX) /%$1/msxg;
  392.  
  393. # eliminar líneas enteras
  394. $cabeza =~ s/ ^ $USEPACK (?: $CORCHETES )? $FAMILIA \n//msxg;
  395.  
  396. # eliminar palabras sueltas
  397. $cabeza =~ s/ (?: ^ $USEPACK \{ | \G) [^}]*? \K (,?) \s* $PALABRAS (\s*) (,?) /$1 and $3 ? ',' : $1 ? $2 : ''/gemsx;
  398.      
  399. # Añadir
  400. $cabeza .= <<"EXTRA";
  401. \\usepackage{graphicx}
  402. \\graphicspath{{$imageDir/}}
  403. \\usepackage{grfext}
  404. \\PrependGraphicsExtensions*{.pdf}
  405. EXTRA
  406.  
  407. # Clear PST content in preamble
  408. $cabeza =~ s/\\usepackage\{\}/% delete/gmsx;
  409. $cabeza =~ s/\\psset\{.+?\}/% \\psset delete/gmsx;
  410. $cabeza =~ s/\\SpecialCoor/% \\SpecialCoor/gmsx;
  411.  
  412. # Recorremos el archivo y realizamos los cambios
  413. while (my($busco, $cambio) = each %cambios) {
  414.             $cabeza =~ s/\Q$busco\E/$cambio/g;
  415.                         $cuerpo =~ s/\Q$busco\E/$cambio/g;
  416.             }
  417.  
  418. # write
  419. open my $SALIDA, '>', "$tempDir/$name-out$ext";
  420. print   $SALIDA "$cabeza$cuerpo$final";
  421. close   $SALIDA;
  422.  
  423. __END__
  424.  
Coloreado en 0.011 segundos, usando GeSHi 1.0.8.4
La cual con el un archivo de entrada de la forma (test.tex):
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \begin{comment}
  3. % Las líneas que están aquí no se deben modificar
  4. \begin{tikzpicture}
  5. code code
  6. \end{tikzpicture}
  7. \begin{document}
  8. \end{comment}
  9. %\begin{pspicture}      
  10. \usepackage{pst-all}
  11. \usepackage[siunitx]{circuitikz}
  12. \begin{document}
  13.  
  14. Lo que sigue no debe quedar dentro de Postscript, lo ignoramos
  15. \begin{verbatim}
  16. \begin{tikzpicture}
  17. no tocar
  18. \end{tikzpicture}
  19. \end{verbatim}
  20.  
  21. Ésta línea \verb|\begin{pspicture*} o \begin{tikzpicture} \begin{other}|
  22. junto a las que comienzan con % no nos interesan
  23. %\begin{tikzpicture}
  24. % no tocar
  25. %\end{tikzpicture}
  26.  
  27. Este entono no debe quedar anidado
  28. \begin{postscript}
  29. \psset{code}
  30. \begin{pspicture}(-11,0)(11,0)  
  31. Esta sera la figura 1
  32. \end{pspicture}
  33. \end{postscript}
  34.  
  35. Lo que sigue no debe quedar dentro de Postscript, lo ignoramos
  36. \begin{ignore}
  37. \begin{pspicture}(-11,0)(11,0)  
  38. no tocar
  39. \end{pspicture}
  40. \end{ignore}
  41.  
  42. Este entono no debe quedar anidado
  43. \begin{postscript}
  44. \begin{tikzpicture}[scale=2]
  45. Esta sera la figura 2
  46. \end{tikzpicture}
  47. \end{postscript}
  48.  
  49. Esto debe quedar dentro de Postscript
  50. \begin{tikzpicture}
  51. Esta sera la figura 3
  52. \end{tikzpicture}
  53.  
  54. Esto debe quedar dentro de Postscript
  55. \begin{tikzpicture}
  56. \begin{circuitikz}
  57. Esta sera la figura 4
  58. \end{circuitikz}
  59. \end{tikzpicture}
  60.  
  61. Esto debe quedar dentro de Postscript
  62. \begin{circuitikz}
  63. Esta sera la figura 5
  64. \end{circuitikz}
  65.  
  66. Final del archivo.
  67. \end{document} % de ésta línea en adelante no se debe tocar
  68. \begin{pspicture}
  69. no tocar
  70. \end{pspicture}
  71. \end{document}
  72.  
  73. \begin{pspicture}(-11,0)(11,0)  
  74. no tocar
  75. \end{pspicture}
  76.  
  77. \begin{circuitikz}
  78. no tocar
  79. \end{circuitikz}
  80.  
  81.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Genera test-tmp.tex:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \begin{comment}
  3. % Las líneas que están aquí no se deben modificar
  4. \begin{TIKZPICTURE}
  5. code code
  6. \end{TIKZPICTURE}
  7. \begin{DOCTRICKS}
  8. \end{comment}
  9. %\begin{TRICKS}        
  10. \usepackage{pst-all}
  11. \usepackage[siunitx]{circuitikz}
  12. \begin{document}
  13.  
  14. Lo que sigue no debe quedar dentro de Postscript, lo ignoramos
  15. \begin{verbatim}
  16. \begin{TIKZPICTURE}
  17. no tocar
  18. \end{TIKZPICTURE}
  19. \end{verbatim}
  20.  
  21. Ésta línea \verb|\begin{TRICKS*} o \begin{TIKZPICTURE} \begin{OTHER}|
  22. junto a las que comienzan con % no nos interesan
  23. %\begin{TIKZPICTURE}
  24. % no tocar
  25. %\end{TIKZPICTURE}
  26.  
  27. Este entono no debe quedar anidado
  28. \begin{postscript}
  29. \psset{code}
  30. \begin{pspicture}(-11,0)(11,0)  
  31. Esta sera la figura 1
  32. \end{pspicture}
  33. \end{postscript}
  34.  
  35. Lo que sigue no debe quedar dentro de Postscript, lo ignoramos
  36. \begin{ignore}
  37. \begin{TRICKS}(-11,0)(11,0)    
  38. no tocar
  39. \end{TRICKS}
  40. \end{ignore}
  41.  
  42. Este entono no debe quedar anidado
  43. \begin{postscript}
  44. \begin{tikzpicture}[scale=2]
  45. Esta sera la figura 2
  46. \end{tikzpicture}
  47. \end{postscript}
  48.  
  49. Esto debe quedar dentro de Postscript
  50. \begin{postscript}
  51. \begin{tikzpicture}
  52. Esta sera la figura 3
  53. \end{tikzpicture}
  54. \end{postscript}
  55.  
  56. Esto debe quedar dentro de Postscript
  57. \begin{postscript}
  58. \begin{tikzpicture}
  59. \begin{circuitikz}
  60. Esta sera la figura 4
  61. \end{circuitikz}
  62. \end{tikzpicture}
  63. \end{postscript}
  64.  
  65. Esto debe quedar dentro de Postscript
  66. \begin{postscript}
  67. \begin{circuitikz}
  68. Esta sera la figura 5
  69. \end{circuitikz}
  70. \end{postscript}
  71.  
  72. Final del archivo.
  73. \end{document} % de ésta línea en adelante no se debe tocar
  74. \begin{pspicture}
  75. no tocar
  76. \end{pspicture}
  77. \end{document}
  78.  
  79. \begin{pspicture}(-11,0)(11,0)  
  80. no tocar
  81. \end{pspicture}
  82.  
  83. \begin{circuitikz}
  84. no tocar
  85. \end{circuitikz}
  86.  
  87.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
y genera test-out.tex:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \begin{comment}
  3. % Las líneas que están aquí no se deben modificar
  4. \begin{tikzpicture}
  5. code code
  6. \end{tikzpicture}
  7. \begin{document}
  8. \end{comment}
  9. %\begin{pspicture}      
  10. % delete
  11. \usepackage[siunitx]{circuitikz}
  12. \usepackage{graphicx}
  13. \graphicspath{{images/}}
  14. \usepackage{grfext}
  15. \PrependGraphicsExtensions*{.pdf}
  16. \begin{document}
  17.  
  18. Lo que sigue no debe quedar dentro de Postscript, lo ignoramos
  19. \begin{verbatim}
  20. \begin{tikzpicture}
  21. no tocar
  22. \end{tikzpicture}
  23. \end{verbatim}
  24.  
  25. Ésta línea \verb|\begin{pspicture*} o \begin{tikzpicture} \begin{other}|
  26. junto a las que comienzan con % no nos interesan
  27. %\begin{tikzpicture}
  28. % no tocar
  29. %\end{tikzpicture}
  30.  
  31. Este entono no debe quedar anidado
  32. \includegraphics[scale=1]{test-fig-1}
  33.  
  34. Lo que sigue no debe quedar dentro de Postscript, lo ignoramos
  35. \begin{ignore}
  36. \begin{pspicture}(-11,0)(11,0)  
  37. no tocar
  38. \end{pspicture}
  39. \end{ignore}
  40.  
  41. Este entono no debe quedar anidado
  42. \includegraphics[scale=1]{test-fig-2}
  43.  
  44. Esto debe quedar dentro de Postscript
  45. \includegraphics[scale=1]{test-fig-3}
  46.  
  47. Esto debe quedar dentro de Postscript
  48. \includegraphics[scale=1]{test-fig-4}
  49.  
  50. Esto debe quedar dentro de Postscript
  51. \includegraphics[scale=1]{test-fig-5}
  52.  
  53. Final del archivo.
  54. \end{document} % de ésta línea en adelante no se debe tocar
  55. \begin{pspicture}
  56. no tocar
  57. \end{pspicture}
  58. \end{document}
  59.  
  60. \begin{pspicture}(-11,0)(11,0)  
  61. no tocar
  62. \end{pspicture}
  63.  
  64. \begin{circuitikz}
  65. no tocar
  66. \end{circuitikz}
  67.  
  68.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
juntos a los ficheros test-fig-1.tex, test-fig-2.tex, test-fig-3.tex, test-fig-4.tex y test-fig-5.tex
que son de ésta forma:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \begin{comment}
  3. % Las líneas que están aquí no se deben modificar
  4. \begin{TIKZPICTURE}
  5. code code
  6. \end{TIKZPICTURE}
  7. \begin{DOCTRICKS}
  8. \end{comment}
  9. %\begin{TRICKS}        
  10. \usepackage{pst-all}
  11. \usepackage[siunitx]{circuitikz}
  12. \pagestyle{empty}
  13. \begin{document}
  14. \begin{tikzpicture}
  15. Esta sera la figura 3
  16. \end{tikzpicture}
  17. \end{document}
  18.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Me encantaría poder optimizar el código en el tema de la apertura y cierre de archivos, intenté hacer el cambio que me propusiste arriba y no hubo caso, no obtenía el fichero que deseaba.
Saludos nuevamente.
Pablo.
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Expresión regular para texto anidado

Notapor explorer » 2015-01-08 11:47 @532

¿Para qué usas use re "eval"?
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Expresión regular para texto anidado

Notapor pablgonz » 2015-01-08 14:26 @643

Parte del código es de un mensaje anterior: http://perlenespanol.com/foro/acotar-expresion-regular-t8380-50.html de cuando tenía Perl v5.14.2.
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Expresión regular para texto anidado

Notapor explorer » 2015-01-08 14:47 @657

Ya... La pregunta es si sabes para qué sirve ;)
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Expresión regular para texto anidado

Notapor pablgonz » 2015-01-08 15:52 @703

Veamos si estoy en lo correcto, sirve para cambiar el significado de
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. (?{ $DEL = "\Q$^N" })
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

ya que no se puede interpolar una cadena en un patrón que contiene bloques de código.
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Expresión regular para texto anidado

Notapor pablgonz » 2015-01-11 14:25 @642

Quité la línea de use re 'eval' y cambié un poco de código a esto:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. # por líneas
  2. my @lineas = split /\n/, $archivo;
  3. # completo
  4. $archivo = join("\n", @lineas);  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
y he logrado reducir la cantidad de veces que abro y cierro el archivo. ¿Se puede escribir distinto ésta parte del código?
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my $grap="\\includegraphics[scale=1]{$name-fig-";
  2. my $close = '}';
  3. my $IMGno = 1;
  4. $cuerpo =~ s/$BP.+?$EP/$grap.$IMGno++.$close/gemsx;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Sé que con /e evalúo la parte izquierda y luego hago los cambios pero la única forma que encontré de "escribir la frase que necesito" fue concatenando, no pude interpolar "$IMGno++" en la expresión regular. Supongo que existe algo más "bonito".

Saludos.
Última edición por explorer el 2015-01-11 14:44 @655, editado 1 vez en total
Razón: Quite => Quité; cambie => cambié; ésto => esto; ésta => esta; interrogantes; se => Sé;
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Expresión regular para texto anidado

Notapor explorer » 2015-01-11 14:58 @665

Las líneas que usaste es la idea que te comenté unos mensajes antes: se puede evitar la escritura/lectura de los archivos intermedios porque la única diferencia es que pasas la información de formato array, con líneas, a un escalar, con todas las líneas concatenadas.

La parte derecha de la expresión regular se podría escribir así:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $cuerpo =~ s/$BP.+?$EP/$grap@{[$IMGno++]}$close/msg;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
pero no sé si es más bonito... usa algo de magia ;)
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

AnteriorSiguiente

Volver a Básico

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 10 invitados