AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / computer / Perguntas / 1682413
Accepted
ChrisAga
ChrisAga
Asked: 2021-10-19 06:57:21 +0800 CST2021-10-19 06:57:21 +0800 CST 2021-10-19 06:57:21 +0800 CST

Duas colunas pdf de markdown com script pandoc e lua

  • 772

Eu quero renderizar um documento pdf de duas colunas usando divs cercados de remarcação. O exemplo mínimo é este:

:::::::::::::: {.columns data-latex=""}
::: {.column width="40%" data-latex="[t]{0.4\textwidth}"}
contents...
:::
::: {.column width="60%" data-latex="[t]{0.6\textwidth}"}
contents...
:::
::::::::::::::

A renderização está OK em html, mas aparentemente alguém decidiu que a renderização de várias colunas em látex é apenas para beamer, então não funciona com látex simples e depois com pdf. Não posso mudar para o mecanismo html pdf do pandoc, pois preciso de modelos de látex para meu documento final.

O ambiente de látex minipage parece muito conveniente para conseguir o que eu quero. Depois de muitas investigações, cheguei com este filtro lua:

local pandocList = require 'pandoc.List'

Div = function (div)
  local options = div.attributes['data-latex']
  if options == nil then return nil end

  -- if the output format is not latex, the object is left unchanged
  if FORMAT ~= 'latex' and FORMAT ~= 'beamer' then
    div.attributes['data-latex'] = nil
    return div
  end

  local env = div.classes[1]
  -- if the div has no class, the object is left unchanged
  if not env then return nil end

  local returnedList
  
  -- build the returned list of blocks
  if env == 'column' then
    local beginEnv = pandocList:new{pandoc.RawBlock('tex', '\\begin' .. '{' .. 'minipage' .. '}' .. options)}
    local endEnv = pandocList:new{pandoc.RawBlock('tex', '\\end{' .. 'minipage' .. '}')}
    returnedList = beginEnv .. div.content .. endEnv
  end
  return returnedList
end

Infelizmente, o documento de látex gerado ( pandoc --lua-filter ./latex-div.lua -o test.latex test.md) é o seguinte, que não renderiza como pretendido devido à linha em branco entre o final da primeira minipágina e o início da segunda:

\begin{document}

\begin{minipage}[t]{0.4\textwidth}

contents\ldots{}

\end{minipage}

\begin{minipage}[t]{0.6\textwidth}

contents\ldots{}

\end{minipage}

\end{document}

Estou quase lá. Como posso me livrar dessa linha em branco indesejada sem reprocessar o arquivo de látex?

markdown latex
  • 2 2 respostas
  • 571 Views

2 respostas

  • Voted
  1. Best Answer
    ChrisAga
    2021-11-12T06:58:41+08:002021-11-12T06:58:41+08:00

    Acontece que existe uma solução mais simples usando Tex \mboxpara fazer as duas minipáginas ficarem juntas apesar da linha em branco.

    local pandocList = require 'pandoc.List'
    
    Div = function (div)
      local options = div.attributes['data-latex']
      if options == nil then return nil end
    
      -- if the output format is not latex, the object is left unchanged
      if FORMAT ~= 'latex' and FORMAT ~= 'beamer' then
        div.attributes['data-latex'] = nil
        return div
      end
    
      local env = div.classes[1]
      -- if the div has no class, the object is left unchanged
      if not env then return nil end
    
      local returnedList
      
      -- build the returned list of blocks
      if env == 'column' then
        local beginEnv = pandocList:new{pandoc.RawBlock('tex', '\\begin' .. '{' .. 'minipage' .. '}' .. options)}
        local endEnv = pandocList:new{pandoc.RawBlock('tex', '\\end{' .. 'minipage' .. '}')}
        returnedList = beginEnv .. div.content .. endEnv
    
      elseif env == 'columns' then
        -- it turns-out that a simple Tex \mbox do the job
        begin_env = List:new{pandoc.RawBlock('tex', '\\mbox{')}
        end_env = List:new{pandoc.RawBlock('tex', '}')}
        returned_list = begin_env .. div.content .. end_env
      end
      return returnedList
    end
    

    O código de látex resultante é:

    \begin{document}
    
    \mbox{
    
    \begin{minipage}[t]{0.4\textwidth}
    
    contents\ldots{}
    
    \end{minipage}\begin{minipage}[t]{0.6\textwidth}
    
    contents\ldots{}
    
    \end{minipage}
    
    }
    
    \end{document}
    

    Desde então, postei um filtro mais abrangente em um repositório git junto com outros filtros que podem ser úteis também.

    • 1
  2. ChrisAga
    2021-10-23T04:52:12+08:002021-10-23T04:52:12+08:00

    Após novas investigações tentar e erros. Eventualmente, sou capaz de responder à minha própria pergunta (no caso de ser útil para alguém).

    Como os divs aninhados são processados ​​antes do div pai, é possível reprocessá-los para fechar um ambiente de minipágina e abrir o próximo no mesmo pandoc.RawBlock (e obviamente se livrar da linha em branco indesejada).

    Aqui está o novo código do filtro lua:

    local pandocList = require 'pandoc.List'
    
    Div = function (div)
      local options = div.attributes['data-latex']
      if options == nil then return nil end
    
      -- if the output format is not latex, the object is left unchanged
      if FORMAT ~= 'latex' and FORMAT ~= 'beamer' then
        div.attributes['data-latex'] = nil
        return div
      end
    
      local env = div.classes[1]
      -- if the div has no class, the object is left unchanged
      if not env then return nil end
    
      local returnedList
      
      -- build the returned list of blocks
      if env == 'column' then
        local beginEnv = pandocList:new{pandoc.RawBlock('tex', '\\begin' .. '{' .. 'minipage' .. '}' .. options)}
        local endEnv = pandocList:new{pandoc.RawBlock('tex', '\\end{' .. 'minipage' .. '}')}
        returnedList = beginEnv .. div.content .. endEnv
    
      elseif env == 'columns' then
        -- merge two consecutives RawBlocks (\end... and \begin...)
        -- to get rid of the extra blank line
        local blocks = div.content
        local rbtxt = ''
    
        for i = #blocks-1, 1, -1 do
          if i > 1 and blocks[i].tag == 'RawBlock' and blocks[i].text:match 'end' 
          and blocks[i+1].tag == 'RawBlock' and blocks[i+1].text:match 'begin' then
            rbtxt = blocks[i].text .. blocks[i+1].text
            blocks:remove(i+1)
            blocks[i].text = rbtxt
          end
        end
        returnedList=blocks
      end
      return returnedList
    end
    

    O documento de látex gerado está correto agora:

    \begin{document}
    
    \begin{minipage}[t]{0.4\textwidth}
    
    contents\ldots{}
    
    \end{minipage}\begin{minipage}[t]{0.6\textwidth}
    
    contents\ldots{}
    
    \end{minipage}
    
    \end{document}
    
    • 0

relate perguntas

  • MarkdownPreview em Sublime-text3 abre o aplicativo Signal, em vez da guia do navegador

  • Latex tabularx problema com espaçamento

  • Problema LaTeX com bibliografia

  • Pandoc: Notas de rodapé duplicadas - vários arquivos - mesmo nome

  • Mac: arquivo markdown, não foi possível editar

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como posso reduzir o consumo do processo `vmmem`?

    • 11 respostas
  • Marko Smith

    Baixar vídeo do Microsoft Stream

    • 4 respostas
  • Marko Smith

    O Google Chrome DevTools falhou ao analisar o SourceMap: chrome-extension

    • 6 respostas
  • Marko Smith

    O visualizador de fotos do Windows não pode ser executado porque não há memória suficiente?

    • 5 respostas
  • Marko Smith

    Como faço para ativar o WindowsXP agora que o suporte acabou?

    • 6 respostas
  • Marko Smith

    Área de trabalho remota congelando intermitentemente

    • 7 respostas
  • Marko Smith

    O que significa ter uma máscara de sub-rede /32?

    • 6 respostas
  • Marko Smith

    Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows?

    • 1 respostas
  • Marko Smith

    O VirtualBox falha ao iniciar com VERR_NEM_VM_CREATE_FAILED

    • 8 respostas
  • Marko Smith

    Os aplicativos não aparecem nas configurações de privacidade da câmera e do microfone no MacBook

    • 5 respostas
  • Martin Hope
    Saaru Lindestøkke Por que os arquivos tar.xz são 15x menores ao usar a biblioteca tar do Python em comparação com o tar do macOS? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh Como posso reduzir o consumo do processo `vmmem`? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Pesquisa do Windows 10 não está carregando, mostrando janela em branco 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    v15 Por que uma conexão de Internet gigabit/s via cabo (coaxial) não oferece velocidades simétricas como fibra? 2020-01-25 08:53:31 +0800 CST
  • Martin Hope
    andre_ss6 Área de trabalho remota congelando intermitentemente 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney Por que colocar um ponto após o URL remove as informações de login? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca Todos os meus complementos do Firefox foram desativados repentinamente, como posso reativá-los? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK É possível criar um código QR usando texto? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 Altere o nome da ramificação padrão do git init 2019-04-01 06:16:56 +0800 CST

Hot tag

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve