• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

sile-typesetter / sile / 3849002768

pending completion
3849002768

push

github

GitHub
Merge f1334c9ed into 13df3c1f5

53 of 53 new or added lines in 7 files covered. (100.0%)

11 of 14758 relevant lines covered (0.07%)

0.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/classes/base.lua
1
local class = pl.class()
×
2
class.type = "class"
×
3
class._name = "base"
×
4

5
class._initialized = false
×
6
class.deferredLegacyInit = {}
×
7
class.deferredInit = {}
×
8
class.pageTemplate = { frames = {}, firstContentFrame = nil }
×
9
class.defaultFrameset = {}
×
10
class.firstContentFrame = "page"
×
11
class.options = setmetatable({}, {
×
12
    _opts = {},
13
    __newindex = function (self, key, value)
14
      local opts = getmetatable(self)._opts
×
15
      if type(opts[key]) == "function" then
×
16
        opts[key](class, value)
×
17
      elseif type(value) == "function" then
×
18
        opts[key] = value
×
19
      elseif type(key) == "number" then
×
20
        return nil
×
21
      else
22
        SU.error("Attempted to set an undeclared class option '" .. key .. "'")
×
23
      end
24
    end,
25
    __index = function (self, key)
26
      if key == "super" then return nil end
×
27
      if type(key) == "number" then return nil end
×
28
      local opt = getmetatable(self)._opts[key]
×
29
      if type(opt) == "function" then
×
30
        return opt(class)
×
31
      elseif opt then
×
32
        return opt
×
33
      else
34
        SU.error("Attempted to get an undeclared class option '" .. key .. "'")
×
35
      end
36
    end
37
  })
38
class.hooks = {
×
39
  newpage = {},
40
  endpage = {},
41
  finish = {},
42
}
43

44
class.packages = {}
×
45

46
function class:_init (options)
×
47
  SILE.scratch.half_initialized_class = self
×
48
  if self == options then options = {} end
×
49
  SILE.languageSupport.loadLanguage('und') -- preload for unlocalized fallbacks
×
50
  self:declareOptions()
×
51
  self:registerRawHandlers()
×
52
  self:declareSettings()
×
53
  self:registerCommands()
×
54
  self:setOptions(options)
×
55
  self:declareFrames(self.defaultFrameset)
×
56
  self:registerPostinit(function (self_)
×
57
      if type(self.firstContentFrame) == "string" then
×
58
        self_.pageTemplate.firstContentFrame = self_.pageTemplate.frames[self_.firstContentFrame]
×
59
      end
60
      local frame = self_:initialFrame()
×
61
      SILE.typesetter = SILE.typesetters.base(frame)
×
62
      SILE.typesetter:registerPageEndHook(function ()
×
63
        SU.debug("frames", function ()
×
64
          for _, v in pairs(SILE.frames) do SILE.outputter:debugFrame(v) end
×
65
          return "Drew debug outlines around frames"
×
66
        end)
67
      end)
68
    end)
69
end
70

71
function class:_post_init ()
×
72
  self._initialized = true
×
73
  for i, func in ipairs(self.deferredInit) do
×
74
    func(self)
×
75
    self.deferredInit[i] = nil
×
76
  end
77
  SILE.scratch.half_initialized_class = nil
×
78
end
79

80
function class:setOptions (options)
×
81
  options = options or {}
×
82
  options.papersize = options.papersize or "a4"
×
83
  for option, value in pairs(options) do
×
84
    self.options[option] = value
×
85
  end
86
end
87

88
function class:declareOption (option, setter)
×
89
  rawset(getmetatable(self.options)._opts, option, nil)
×
90
  self.options[option] = setter
×
91
end
92

93
function class:declareOptions ()
×
94
  self:declareOption("class", function (_, name)
×
95
    if name then
×
96
      if self._legacy then
×
97
        self._name = name
×
98
      elseif name ~= self._name then
×
99
        SU.error("Cannot change class name after instantiation, derive a new class instead.")
×
100
      end
101
    end
102
    return self._name
×
103
  end)
104
  self:declareOption("papersize", function (_, size)
×
105
    if size then
×
106
      self.papersize = size
×
107
      SILE.documentState.paperSize = SILE.papersize(size)
×
108
      SILE.documentState.orgPaperSize = SILE.documentState.paperSize
×
109
      SILE.newFrame({
×
110
        id = "page",
111
        left = 0,
112
        top = 0,
113
        right = SILE.documentState.paperSize[1],
114
        bottom = SILE.documentState.paperSize[2]
×
115
      })
116
    end
117
    return self.papersize
×
118
  end)
119
end
120

121
function class.declareSettings (_)
×
122
  SILE.settings:declare({
×
123
    parameter = "current.parindent",
124
    type = "glue or nil",
125
    default = nil,
126
    help = "Glue at start of paragraph"
×
127
  })
128
  SILE.settings:declare({
×
129
    parameter = "current.hangIndent",
130
    type = "integer or nil",
131
    default = nil,
132
    help = "Size of hanging indent"
×
133
  })
134
  SILE.settings:declare({
×
135
    parameter = "current.hangAfter",
136
    type = "integer or nil",
137
    default = nil,
138
    help = "Number of lines affected by handIndent"
×
139
  })
140
end
141

142
function class:loadPackage (packname, options)
×
143
  local pack = require(("packages.%s"):format(packname))
×
144
  if type(pack) == "table" and pack.type == "package" then -- new package
×
145
    self.packages[pack._name] = pack(options)
×
146
  else -- legacy package
147
    self:initPackage(pack, options)
×
148
  end
149
end
150

151
function class:initPackage (pack, options)
×
152
  SU.deprecated("class:initPackage(options)", "package(options)", "0.14.0", "0.16.0", [[
×
153
  This package appears to be a legacy format package. It returns a table
154
  an expects SILE to guess a bit about what to do. New packages inherit
155
  from the base class and have a constructor function (_init) that
156
  automatically handles setup.]])
×
157
  if type(pack) == "table" then
×
158
    if pack.exports then pl.tablex.update(self, pack.exports) end
×
159
    if type(pack.declareSettings) == "function" then
×
160
      pack.declareSettings(self)
×
161
    end
162
    if type(pack.registerRawHandlers) == "function" then
×
163
      pack.registerRawHandlers(self)
×
164
    end
165
    if type(pack.registerCommands) == "function" then
×
166
      pack.registerCommands(self)
×
167
    end
168
    if type(pack.init) == "function" then
×
169
      self:registerPostinit(pack.init, options)
×
170
    end
171
  end
172
end
173

174
function class:registerLegacyPostinit (func, options)
×
175
  if self._initialized then return func(self, options) end
×
176
  table.insert(self.deferredLegacyInit, function (_)
×
177
      func(self, options)
×
178
    end)
179
end
180

181
function class:registerPostinit (func, options)
×
182
  if self._initialized then return func(self, options) end
×
183
  table.insert(self.deferredInit, function (_)
×
184
      func(self, options)
×
185
    end)
186
end
187

188
function class:registerHook (category, func)
×
189
  for _, func_ in ipairs(self.hooks[category]) do
×
190
    if func_ == func then
×
191
      return
×
192
      --[[ See https://github.com/sile-typesetter/sile/issues/1531
193
      return SU.warn("Attempted to set the same function hook twice, probably unintended, skipping.")
194
      -- If the same function signature is already set a package is probably being
195
      -- re-initialized. Ditch the first instance of the hook so that it runs in
196
      -- the order of last initialization.
197
      self.hooks[category][_] = nil
198
      ]]
199
    end
200
  end
201
  table.insert(self.hooks[category], func)
×
202
end
203

204
function class:runHooks (category, options)
×
205
  for _, func in ipairs(self.hooks[category]) do
×
206
    SU.debug("classhooks", "Running hook from", category, options and "with options " .. #options)
×
207
    func(self, options)
×
208
  end
209
end
210

211
function class.registerCommand (_, name, func, help, pack)
×
212
  SILE.Commands[name] = func
×
213
  if not pack then
×
214
    local where = debug.getinfo(2).source
×
215
    pack = where:match("(%w+).lua")
×
216
  end
217
  --if not help and not pack:match(".sil") then SU.error("Could not define command '"..name.."' (in package "..pack..") - no help text" ) end
218
  SILE.Help[name] = {
×
219
    description = help,
220
    where = pack
×
221
  }
222
end
223

224
function class.registerRawHandler (_, format, callback)
×
225
  SILE.rawHandlers[format] = callback
×
226
end
227

228
function class:registerRawHandlers ()
×
229

230
  self:registerRawHandler("text", function (_, content)
×
231
    SILE.settings:temporarily(function()
×
232
      SILE.settings:set("typesetter.parseppattern", "\n")
×
233
      SILE.settings:set("typesetter.obeyspaces", true)
×
234
      SILE.typesetter:typeset(content[1])
×
235
    end)
236
  end)
237

238
end
239

240
local function packOptions (options)
241
  local relevant = pl.tablex.copy(options)
×
242
  relevant.src = nil
×
243
  relevant.format = nil
×
244
  relevant.module = nil
×
245
  relevant.require = nil
×
246
  return relevant
×
247
end
248

249
function class:registerCommands ()
×
250

251
  local function replaceProcessBy(replacement, tree)
252
    if type(tree) ~= "table" then return tree end
×
253
    local ret = pl.tablex.deepcopy(tree)
×
254
    if tree.command == "process" then
×
255
      return replacement
×
256
    else
257
      for i, child in ipairs(tree) do
×
258
        ret[i] = replaceProcessBy(replacement, child)
×
259
      end
260
      return ret
×
261
    end
262
  end
263

264
  self:registerCommand("define", function (options, content)
×
265
    SU.required(options, "command", "defining command")
×
266
    if type(content) == "function" then
×
267
      -- A macro defined as a function can take no argument, so we register
268
      -- it as-is.
269
      self:registerCommand(options["command"], content)
×
270
      return
×
271
    elseif options.command == "process" then
×
272
      SU.warn("Did you mean to re-definine the `\\process` macro? That probably won't go well.")
×
273
    end
274
    self:registerCommand(options["command"], function (_, inner_content)
×
275
      SU.debug("macros", "Processing macro \\" .. options["command"])
×
276
      local macroArg
277
      if type(inner_content) == "function" then
×
278
        macroArg = inner_content
×
279
      elseif type(inner_content) == "table" then
×
280
        macroArg = pl.tablex.copy(inner_content)
×
281
        macroArg.command = nil
×
282
        macroArg.id = nil
×
283
      elseif inner_content == nil then
×
284
        macroArg = {}
×
285
      else
286
        SU.error("Unhandled content type " .. type(inner_content) .. " passed to macro \\" .. options["command"], true)
×
287
      end
288
      -- Replace every occurrence of \process in `content` (the macro
289
      -- body) with `macroArg`, then have SILE go through the new `content`.
290
      local newContent = replaceProcessBy(macroArg, content)
×
291
      SILE.process(newContent)
×
292
      SU.debug("macros", "Finished processing \\" .. options["command"])
×
293
    end, options.help, SILE.currentlyProcessingFile)
×
294
  end, "Define a new macro. \\define[command=example]{ ... \\process }")
×
295

296
  -- A utility function that allows SILE.call() to be used as a noop wrapper.
297
  self:registerCommand("noop", function (_, content)
×
298
    SILE.process(content)
×
299
  end)
300

301
  -- The document (SIL) or sile (XML) command is always the sigular leaf at the
302
  -- top level of our AST. The work you might expect to see happen here is
303
  -- actually handled by SILE.inputter:classInit() before we get here, so these
304
  -- are just pass through functions. Theoretically, this could be a useful
305
  -- point to hook into-especially for included documents.
306
  self:registerCommand("document", function (_, content)
×
307
    SILE.process(content)
×
308
  end)
309
  self:registerCommand("sile", function (_, content)
×
310
    SILE.process(content)
×
311
  end)
312

313
  self:registerCommand("comment", function (_, _)
×
314
  end, "Ignores any text within this command's body.")
×
315

316
  self:registerCommand("process", function ()
×
317
    SU.error("Encountered unsubstituted \\process.")
×
318
  end, "Within a macro definition, processes the contents of the macro body.")
×
319

320
  self:registerCommand("script", function (options, content)
×
321
    local packopts = packOptions(options)
×
322
    if SU.hasContent(content) then
×
323
      return SILE.processString(content[1], options.format or "lua", nil, packopts)
×
324
    elseif options.src then
×
325
      return SILE.require(options.src)
×
326
    else
327
      SU.error("\\script function requires inline content or a src file path")
×
328
      return SILE.processString(content[1], options.format or "lua", nil, packopts)
×
329
    end
330
  end, "Runs lua code. The code may be supplied either inline or using src=...")
×
331

332
  self:registerCommand("include", function (options, content)
×
333
    local packopts = packOptions(options)
×
334
    if SU.hasContent(content) then
×
335
      local doc = SU.contentToString(content)
×
336
      return SILE.processString(doc, options.format, nil, packopts)
×
337
    elseif options.src then
×
338
      return SILE.processFile(options.src, options.format, packopts)
×
339
    else
340
      SU.error("\\include function requires inline content or a src file path")
×
341
    end
342
  end, "Includes a content file for processing.")
×
343

344
  self:registerCommand("lua", function (options, content)
×
345
    local packopts = packOptions(options)
×
346
    if SU.hasContent(content) then
×
347
      local doc = SU.contentToString(content)
×
348
      return SILE.processString(doc, "lua", nil, packopts)
×
349
    elseif options.src then
×
350
      return SILE.processFile(options.src, "lua", packopts)
×
351
    elseif options.require then
×
352
      local module = SU.required(options, "require", "lua")
×
353
      return require(module)
×
354
    else
355
      SU.error("\\lua function requires inline content or a src file path or a require module name")
×
356
    end
357
  end, "Run Lua code. The code may be supplied either inline, using require=... for a Lua module, or using src=... for a file path")
×
358

359
  self:registerCommand("sil", function (options, content)
×
360
    local packopts = packOptions(options)
×
361
    if SU.hasContent(content) then
×
362
      local doc = SU.contentToString(content)
×
363
      return SILE.processString(doc, "sil")
×
364
    elseif options.src then
×
365
      return SILE.processFile(options.src, "sil", packopts)
×
366
    else
367
      SU.error("\\sil function requires inline content or a src file path")
×
368
    end
369
  end, "Process sil content. The content may be supplied either inline or using src=...")
×
370

371
  self:registerCommand("xml", function (options, content)
×
372
    local packopts = packOptions(options)
×
373
    if SU.hasContent(content) then
×
374
      local doc = SU.contentToString(content)
×
375
      return SILE.processString(doc, "xml", nil, packopts)
×
376
    elseif options.src then
×
377
      return SILE.processFile(options.src, "xml", packopts)
×
378
    else
379
      SU.error("\\xml function requires inline content or a src file path")
×
380
    end
381
  end, "Process xml content. The content may be supplied either inline or using src=...")
×
382

383
  self:registerCommand("use", function (options, content)
×
384
    local packopts = packOptions(options)
×
385
    if content[1] and string.len(content[1]) > 0 then
×
386
      local doc = SU.contentToString(content)
×
387
      SILE.processString(doc, "lua", nil, packopts)
×
388
    else
389
      if options.src then
×
390
        SU.warn("Use of 'src' with \\use is discouraged because some of it's path handling\n  will eventually be deprecated. Use 'module' instead when possible.")
×
391
        SILE.processFile(options.src, "lua", packopts)
×
392
      else
393
        local module = SU.required(options, "module", "use")
×
394
        SILE.use(module, packopts)
×
395
      end
396
    end
397
  end, "Load and initialize a SILE module (can be a package, a shaper, a typesetter, or whatever). Use module=... to specif what to load or include module code inline.")
×
398

399
  self:registerCommand("raw", function (options, content)
×
400
    local rawtype = SU.required(options, "type", "raw")
×
401
    local handler = SILE.rawHandlers[rawtype]
×
402
    if not handler then SU.error("No inline handler for '"..rawtype.."'") end
×
403
    handler(options, content)
×
404
  end, "Invoke a raw passthrough handler")
×
405

406
  self:registerCommand("pagetemplate", function (options, content)
×
407
    SILE.typesetter:pushState()
×
408
    SILE.documentState.thisPageTemplate = { frames = {} }
×
409
    SILE.process(content)
×
410
    SILE.documentState.thisPageTemplate.firstContentFrame = SILE.getFrame(options["first-content-frame"])
×
411
    SILE.typesetter:initFrame(SILE.documentState.thisPageTemplate.firstContentFrame)
×
412
    SILE.typesetter:popState()
×
413
  end, "Defines a new page template for the current page and sets the typesetter to use it.")
×
414

415
  self:registerCommand("frame", function (options, _)
×
416
    SILE.documentState.thisPageTemplate.frames[options.id] = SILE.newFrame(options)
×
417
  end, "Declares (or re-declares) a frame on this page.")
×
418

419
  self:registerCommand("penalty", function (options, _)
×
420
    if options.vertical and not SILE.typesetter:vmode() then
×
421
      SILE.typesetter:leaveHmode()
×
422
    end
423
    if SILE.typesetter:vmode() then
×
424
      SILE.typesetter:pushVpenalty({ penalty = tonumber(options.penalty) })
×
425
    else
426
      SILE.typesetter:pushPenalty({ penalty = tonumber(options.penalty) })
×
427
    end
428
  end, "Inserts a penalty node. Option is penalty= for the size of the penalty.")
×
429

430
  self:registerCommand("discretionary", function (options, _)
×
431
    local discretionary = SILE.nodefactory.discretionary({})
×
432
    if options.prebreak then
×
433
      SILE.call("hbox", {}, function () SILE.typesetter:typeset(options.prebreak) end)
×
434
      discretionary.prebreak = { SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] }
×
435
      SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil
×
436
    end
437
    if options.postbreak then
×
438
      SILE.call("hbox", {}, function () SILE.typesetter:typeset(options.postbreak) end)
×
439
      discretionary.postbreak = { SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] }
×
440
      SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil
×
441
    end
442
    if options.replacement then
×
443
      SILE.call("hbox", {}, function () SILE.typesetter:typeset(options.replacement) end)
×
444
      discretionary.replacement = { SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] }
×
445
      SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil
×
446
    end
447
    table.insert(SILE.typesetter.state.nodes, discretionary)
×
448
  end, "Inserts a discretionary node.")
×
449

450
  self:registerCommand("glue", function (options, _)
×
451
    local width = SU.cast("length", options.width):absolute()
×
452
    SILE.typesetter:pushGlue(width)
×
453
  end, "Inserts a glue node. The width option denotes the glue dimension.")
×
454

455
  self:registerCommand("kern", function (options, _)
×
456
    local width = SU.cast("length", options.width):absolute()
×
457
    SILE.typesetter:pushHorizontal(SILE.nodefactory.kern(width))
×
458
  end, "Inserts a glue node. The width option denotes the glue dimension.")
×
459

460
  self:registerCommand("skip", function (options, _)
×
461
    options.discardable = options.discardable or false
×
462
    options.height = SILE.length(options.height):absolute()
×
463
    SILE.typesetter:leaveHmode()
×
464
    if options.discardable then
×
465
      SILE.typesetter:pushVglue(options)
×
466
    else
467
      SILE.typesetter:pushExplicitVglue(options)
×
468
    end
469
  end, "Inserts vertical skip. The height options denotes the skip dimension.")
×
470

471
  self:registerCommand("par", function (_, _)
×
472
    SILE.typesetter:endline()
×
473
  end, "Ends the current paragraph.")
×
474

475
end
476

477
function class:initialFrame ()
×
478
  SILE.documentState.thisPageTemplate = pl.tablex.deepcopy(self.pageTemplate)
×
479
  SILE.frames = { page = SILE.frames.page }
×
480
  for k, v in pairs(SILE.documentState.thisPageTemplate.frames) do
×
481
    SILE.frames[k] = v
×
482
  end
483
  if not SILE.documentState.thisPageTemplate.firstContentFrame then
×
484
    SILE.documentState.thisPageTemplate.firstContentFrame = SILE.frames[self.firstContentFrame]
×
485
  end
486
  SILE.documentState.thisPageTemplate.firstContentFrame:invalidate()
×
487
  return SILE.documentState.thisPageTemplate.firstContentFrame
×
488
end
489

490
function class:declareFrame (id, spec)
×
491
  spec.id = id
×
492
  if spec.solve then
×
493
    self.pageTemplate.frames[id] = spec
×
494
  else
495
    self.pageTemplate.frames[id] = SILE.newFrame(spec)
×
496
  end
497
  --   next = spec.next,
498
  --   left = spec.left and fW(spec.left),
499
  --   right = spec.right and fW(spec.right),
500
  --   top = spec.top and fH(spec.top),
501
  --   bottom = spec.bottom and fH(spec.bottom),
502
  --   height = spec.height and fH(spec.height),
503
  --   width = spec.width and fH(spec.width),
504
  --   id = id
505
  -- })
506
end
507

508
function class:declareFrames (specs)
×
509
  if specs then
×
510
    for k, v in pairs(specs) do self:declareFrame(k, v) end
×
511
  end
512
end
513

514
-- WARNING: not called as class method
515
function class.newPar (typesetter)
×
516
  typesetter:pushGlue(SILE.settings:get("current.parindent") or SILE.settings:get("document.parindent"))
×
517
  SILE.settings:set("current.parindent", nil)
×
518
  local hangIndent = SILE.settings:get("current.hangIndent")
×
519
  if hangIndent then
×
520
    SILE.settings:set("linebreak.hangIndent", hangIndent)
×
521
  end
522
  local hangAfter = SILE.settings:get("current.hangAfter")
×
523
  if hangAfter then
×
524
    SILE.settings:set("linebreak.hangAfter", hangAfter)
×
525
  end
526
end
527

528
-- WARNING: not called as class method
529
function class.endPar (typesetter)
×
530
  typesetter:pushVglue(SILE.settings:get("document.parskip"))
×
531
  if SILE.settings:get("current.hangIndent") then
×
532
    SILE.settings:set("current.hangIndent", nil)
×
533
    SILE.settings:set("linebreak.hangIndent", nil)
×
534
  end
535
  if SILE.settings:get("current.hangAfter") then
×
536
    SILE.settings:set("current.hangAfter", nil)
×
537
    SILE.settings:set("linebreak.hangAfter", nil)
×
538
  end
539
end
540

541
function class:newPage ()
×
542
  SILE.outputter:newPage()
×
543
  self:runHooks("newpage")
×
544
  -- Any other output-routiney things will be done here by inheritors
545
  return self:initialFrame()
×
546
end
547

548
function class:endPage ()
×
549
  SILE.typesetter.frame:leave(SILE.typesetter)
×
550
  self:runHooks("endpage")
×
551
  -- I'm trying to call up a new frame here, don't cause a page break in the current one
552
  -- SILE.typesetter:leaveHmode()
553
  -- Any other output-routiney things will be done here by inheritors
554
end
555

556
function class:finish ()
×
557
  SILE.inputter:postamble()
×
558
  SILE.call("vfill")
×
559
  while not SILE.typesetter:isQueueEmpty() do
×
560
    SILE.call("supereject")
×
561
    SILE.typesetter:leaveHmode(true)
×
562
    SILE.typesetter:buildPage()
×
563
    if not SILE.typesetter:isQueueEmpty() then
×
564
      SILE.typesetter:initNextFrame()
×
565
    end
566
  end
567
  SILE.typesetter:runHooks("pageend") -- normally run by the typesetter
×
568
  self:endPage()
×
569
    if SILE.typesetter then
×
570
      assert(SILE.typesetter:isQueueEmpty(), "queues not empty")
×
571
    end
572
  SILE.outputter:finish()
×
573
  self:runHooks("finish")
×
574
end
575

576
return class
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc