0

I have a chatlog file (chat.tex), and would like to include different parts of it in different parts of my document.

I can extract the relevant parts I want using regular expressions, or string indexing, for example:

chat.tex

% 2021-12-30 00:00:00
First text of the day

% 2021-12-30 00:00:01 Second text of the day

% 2021-12-30 00:00:02 Third text of the day

% 2021-12-30 00:00:03 Fourth text of the day

I would like to include in one part of the document all text between % 2021-12-30 00:00:01 and % 2021-12-30 00:00:03:


Second text of the day

% 2021-12-30 00:00:02 Third text of the day

Ideally, to prevent multiple read requests to the chat.tex file, its content should be stored as a variable, and one would get the text from that variable.

Code if this was python:

chat = open("chat.tex", "r").read()
def extract(start, end):
  return chat[chat.index(start):chat.index(end)]

extract('% 2021-12-30 00:00:01', '% 2021-12-30 00:00:03')

(This might be partially a duplicate of Parse a file with a regexp and return first match - but I do not understand the answer, and think it might be very outdated, and costly in my scenario. I also do not specifically intend to include a file based on line numbers \input only part of file, without losing SyncTeX support?)

Amit
  • 133

1 Answers1

0

Thanks to @user202729 the solution is as follows:

  1. Change the tex engine to lualatex, as this solution depends on some lua code.
  2. Create a lua function to read the file and look for the lines:
-- chat.lua

local f = assert(io.open("chat.tex", "r")) local chat_file = f:read("*all") f:close()

function readchat(starts, ends) i1 = string.find(chat_file, starts) + string.len(starts) i2 = string.find(chat_file, ends) - 2

sub_content = string.sub(chat_file, i1, i2)

--- tex.print treats the string as one line...
for line in string.gmatch(sub_content,"[^\r\n]*") do tex.print(line) end end

  1. Create a latex alias to that function
\newcommand{\readchat}[2]{\directlua{readchat(#1, #2)}}
  1. Include the lua file in the beginning of the document
\directlua{dofile("chat.lua")}
  1. Search for a match
\readchat{"7/1/21T18:11:46"}{"7/2/21T09:44:20"}
Amit
  • 133