Class: Limarka::Conversor

Inherits:
Object
  • Object
show all
Defined in:
lib/limarka/conversor.rb

Overview

Essa class é responsável por ser a abstração de converter o arquivo em Markdown para Latex.

Constant Summary collapse

PRETEXTUAL =
"templates/pretextual.tex"
POSTEXTUAL =
"templates/postextual.tex"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(trabalho, options) ⇒ Conversor

Returns a new instance of Conversor.

Parameters:



28
29
30
31
32
# File 'lib/limarka/conversor.rb', line 28

def initialize(trabalho, options)
  self.t = trabalho
  self.options = options
  self.usa_pdftotext = true
end

Instance Attribute Details

#optionsObject

opções de execução

See Also:



20
21
22
# File 'lib/limarka/conversor.rb', line 20

def options
  @options
end

#postextual_texObject

Returns the value of attribute postextual_tex.



22
23
24
# File 'lib/limarka/conversor.rb', line 22

def postextual_tex
  @postextual_tex
end

#pretextual_texObject

Returns the value of attribute pretextual_tex.



21
22
23
# File 'lib/limarka/conversor.rb', line 21

def pretextual_tex
  @pretextual_tex
end

#tObject

o trabalho



17
18
19
# File 'lib/limarka/conversor.rb', line 17

def t
  @t
end

#texto_texObject

Returns the value of attribute texto_tex.



23
24
25
# File 'lib/limarka/conversor.rb', line 23

def texto_tex
  @texto_tex
end

#txtObject

Returns the value of attribute txt.



24
25
26
# File 'lib/limarka/conversor.rb', line 24

def txt
  @txt
end

#usa_pdftotextObject

Returns the value of attribute usa_pdftotext.



25
26
27
# File 'lib/limarka/conversor.rb', line 25

def usa_pdftotext
  @usa_pdftotext
end

Class Method Details

.tex_file(configuracao) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/limarka/conversor.rb', line 232

def self.tex_file(configuracao)
  if (configuracao['graduacao'] and configuracao['projeto']) then
    'xxx-Monografia-projeto.tex'
  elsif (configuracao['graduacao'] and not configuracao['projeto']) then
    'xxx-Monografia.tex'
  elsif (configuracao['especializacao'] and configuracao['projeto']) then
    'xxx-TFC-projeto.tex'
  elsif (configuracao['especializacao'] and not configuracao['projeto']) then
    'xxx-TFC.tex'
  elsif (configuracao['mestrado'] and configuracao['projeto']) then
    'xxx-Dissertacao-projeto.tex'
  elsif (configuracao['mestrado'] and not configuracao['projeto']) then
    'xxx-Dissertacao.tex'
  elsif (configuracao['doutorado'] and configuracao['projeto']) then
    'xxx-Tese-projeto.tex'
  elsif (configuracao['doutorado'] and not configuracao['projeto']) then
    'xxx-Tese.tex'
  else
    # valor padrão, caso não configurado.
    'xxx-Monografia-projeto.tex'
  end

end

Instance Method Details

#compilaObject

Compila tex_file no diretorio atual, retorna o conteudo somente texto do PDF



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/limarka/conversor.rb', line 59

def compila
  Dir.chdir(options[:output_dir]) do
    basename = File.basename(texto_tex_file, '.tex')
    system "latexmk --quiet --xelatex -f #{basename}",  :out=>'xxx-latexmk-std.txt', :err=>'xxx-latexmk-erros.txt'
    if (usa_pdftotext) then
      system "pdftotext -enc UTF-8 #{basename}.pdf"
      # Comando sed para corrigir junção do fi (ligatures)
      # https://superuser.com/questions/220363/cleaning-up-pdftotext-font-issues/231637#231637
      system "sed -i -e 's/ffi/ffi/g' -e 's/fi/fi/g' -e 's/ff/ff/g' -e 's/fl/fl/g' -e 's/ffl/ffl/g' #{basename}.txt"
      File.open("#{basename}.txt", 'r') {|f| @txt = f.read}
    end
  end
end

#convertObject

Converte o trabalho para Latex



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/limarka/conversor.rb', line 36

def convert()
  FileUtils.mkdir_p(options[:output_dir])

  # A invocação de pandoc passando parâmetro como --before-body necessita
  # de ser realizado através de arquivos, portanto, serão criados arquivos
  # temporários para sua execução
  pretextual_tempfile = Tempfile.new('pretextual')
  postextual_tempfile = Tempfile.new('postextual')
  begin
    pretextual(pretextual_tempfile)
    postextual(postextual_tempfile)
    textual(pretextual_tempfile,postextual_tempfile)

    ensure
      pretextual_tempfile.close
      pretextual_tempfile.unlink
      postextual_tempfile.close
      postextual_tempfile.unlink
  end
end

#cria_xxx_referenciasObject

Cria arquivo temporário de referencias.

Separa o título em subtítulo quando contém ‘:`.



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/limarka/conversor.rb', line 139

def cria_xxx_referencias
  referencias_tempfile = Tempfile.new('referencias')
  File.open(referencias_tempfile, 'w') {|file| file.write(t.referencias)}
  b = BibTeX.open(referencias_tempfile.path)
  b.each do |entry|
    if entry.title.include?(':') then
      s = entry.title.split(':')
      if entry.title.start_with?("{") and entry.title.end_with?("}") then
        s[0] = s[0][1..-1] # remove {
        s[1] = s[1][1..-1] # remove }
      end
      entry['title'] = s[0].strip
      entry['subtitle'] = s[1].strip
    end
  end

  b.save_to referencias_bib_file
end

#filtrosObject



186
187
188
189
190
191
192
# File 'lib/limarka/conversor.rb', line 186

def filtros
  result = ""
  if options[:filtros]
    result = options[:filtros].reduce("") { |cmd, filtro| "#{cmd} --filter #{filtro}" }
  end
  result
end

#filtros_luaObject



178
179
180
181
182
183
184
# File 'lib/limarka/conversor.rb', line 178

def filtros_lua
  result = ""
  if options[:filtros_lua]
    result = options[:filtros_lua].reduce("") { |cmd, filtro| "#{cmd} --lua-filter #{filtro}" }
  end
  result
end

#hash_to_yaml(h) ⇒ Object



73
74
75
76
77
78
# File 'lib/limarka/conversor.rb', line 73

def hash_to_yaml(h)
  s = StringIO.new
  s << h.to_yaml
  s << "---\n\n"
  s.string
end

#pdf_fileObject



220
221
222
# File 'lib/limarka/conversor.rb', line 220

def pdf_file
  texto_tex_file.sub('.tex','.pdf')
end

#postextual(tempfile) ⇒ Object

Escreve no arquivo o conteúdo gerado referente ao pós-textual do documento.

Parameters:

  • tempfile

    arquivo onde será escrito



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/limarka/conversor.rb', line 115

def postextual(tempfile)
  # Referências (obrigatório)
  # Glossário (opcional)
  # Apêndice (opcional)
  # Anexo (opcional)
  # Índice (opcional)

  s = StringIO.new

  s << secao_referencias
  s << secao_glossario
  s << secao_apendices
  s << secao_anexos
  s << secao_indice

  cria_xxx_referencias

  @postextual_tex = s.string
  File.open(tempfile, 'w') { |file| file.write(postextual_tex) }
end

#postextual_tex_fileObject



213
214
215
# File 'lib/limarka/conversor.rb', line 213

def postextual_tex_file
  "#{options[:output_dir]}/xxx-postextual.tex"
end

#pretextual(tempfile) ⇒ Object

Escreve no arquivo o conteúdo gerado referente ao pretextual do documento.

Parameters:

  • tempfile

    arquivo onde será escrito



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
# File 'lib/limarka/conversor.rb', line 86

def pretextual(tempfile)
  s = StringIO.new
  necessita_de_arquivo_de_texto = ["errata"]
  ["folha_de_rosto", "errata", "folha_de_aprovacao", "dedicatoria", "agradecimentos",
  "epigrafe", "resumo", "abstract", "lista_ilustracoes", "lista_tabelas",
  "lista_siglas", "lista_simbolos", "sumario"].each_with_index do |secao,indice|
    template = "pretextual#{indice+1}-#{secao}"
    Open3.popen3("pandoc -f #{@t.formato} \"--data-dir=#{options[:templates_dir]}\" --template=#{template} -t latex --filter #{pandoc_abnt_path}") {|stdin, stdout, stderr, wait_thr|
      stdin.write(hash_to_yaml(t.configuracao))
      stdin.write("\n")
      if t.errata? and necessita_de_arquivo_de_texto.include?(secao) then
        arquivo_de_entrada = "#{secao}.md"
        conteudo = File.read(arquivo_de_entrada)
        stdin.write(conteudo)
      end
      stdin.close
      s << stdout.read
      exit_status = wait_thr.value # Process::Status object returned.
      if(exit_status!=0) then puts ("Erro: " + stderr.read).red end
    }
  end
  @pretextual_tex = s.string
  File.open(tempfile, 'w') { |file| file.write(pretextual_tex) }
#      puts "#{PRETEXTUAL} criado".green
end

#pretextual_tex_fileObject



210
211
212
# File 'lib/limarka/conversor.rb', line 210

def pretextual_tex_file
  "#{options[:output_dir]}/xxx-pretextual.tex"
end

#referencias_bib_fileObject



224
225
226
# File 'lib/limarka/conversor.rb', line 224

def referencias_bib_file
  "#{options[:output_dir]}/xxx-referencias.bib"
end

#secao_anexosObject



166
167
168
# File 'lib/limarka/conversor.rb', line 166

def secao_anexos
  secao("postextual4-anexos", t.anexos?, t.anexos)
end

#secao_apendicesObject



162
163
164
# File 'lib/limarka/conversor.rb', line 162

def secao_apendices
  secao("postextual3-apendices", t.apendices?, t.apendices)
end

#secao_glossarioObject

Note:

Ainda não implementado



171
172
# File 'lib/limarka/conversor.rb', line 171

def secao_glossario
end

#secao_indiceObject

Note:

Ainda não implementado



175
176
# File 'lib/limarka/conversor.rb', line 175

def secao_indice
end

#secao_referenciasObject



158
159
160
# File 'lib/limarka/conversor.rb', line 158

def secao_referencias
  secao("postextual1-referencias", false, t.referencias)
end

#texto_tex_fileObject



217
218
219
# File 'lib/limarka/conversor.rb', line 217

def texto_tex_file
  "#{options[:output_dir]}/#{Conversor.tex_file(t.configuracao)}"
end

#textual(pretextual_tempfile, postextual_tempfile) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/limarka/conversor.rb', line 194

def textual(pretextual_tempfile, postextual_tempfile)
  valida_yaml
  Open3.popen3("pandoc -f #{@t.formato} -t latex -s \"--data-dir=#{options[:templates_dir]}\" --template=trabalho-academico --top-level-division=chapter --include-before-body=#{pretextual_tempfile.path}  --include-after-body=#{postextual_tempfile.path} #{filtros_lua} #{filtros} --filter #{pandoc_abnt_path}") {|stdin, stdout, stderr, wait_thr|
    stdin.write(File.read(options[:templates_dir] + '/templates/configuracao-tecnica.yaml'))
    stdin.write("\n")
    stdin.write(hash_to_yaml(t.configuracao))
    stdin.write("\n")
    stdin.write(t.texto)
    stdin.close
    @texto_tex = stdout.read
    exit_status = wait_thr.value # Process::Status object returned.
    if(exit_status!=0) then puts ("Erro: " + stderr.read).red end
  }
  File.open(texto_tex_file, 'w')  { |f| f.write(@texto_tex)}
end

#valida_yamlObject



228
229
230
# File 'lib/limarka/conversor.rb', line 228

def valida_yaml
  # não faz nada por enquanto
end