Class: Deplate::Core

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/deplate/core.rb,
lib/deplate/mod/utf8.rb,
lib/deplate/mod/anyword.rb,
lib/deplate/mod/makefile.rb,
lib/deplate/mod/noindent.rb,
lib/deplate/mod/colored-log.rb,
lib/deplate/mod/guesslanguage.rb,
lib/deplate/mod/entities-encode.rb,
lib/deplate/mod/lang-zh_CN-autospace.rb,
lib/deplate/mod/lang-zh_CN.rb,
lib/deplate/mod/linkmap.rb,
lib/deplate/input/play.rb

Overview

colored-log.rb @Author: Thomas Link (micathom AT gmail com) @Website: deplate.sf.net/ @License: GPL (see www.gnu.org/licenses/gpl.txt) @Created: 05-Mai-2005. @Revision: 0.4

Description

Enable colored log output

Direct Known Subclasses

DeplateForTemplates

Constant Summary collapse

Version =
'0.8.5'
VersionSfx =

VersionSfx = ‘a’

'final'
MicroRev =
'3176'
CfgDir =
'/etc/deplate.rc'
LibDir =
File.dirname(__FILE__)
DataDir =
File.join(Config::CONFIG['datadir'], 'deplate')
EtcDirs =
[]
FileCache =

FileCache = File.join(CfgDir, ‘file_list.dat’)

nil
@@vanilla =
false
@@quiet =

shut up

false
@@colored_output =

color output

false
@@modules =

A hash of known modules and their ruby require filenames

{}
@@formatters =

A hash of known formatters and their ruby require filenames

{}
@@css =

A hash of known css files and their ruby file names

{}
@@templates =

A hash of known templates and their ruby file names

{}
@@symbols =

A hash of known encodings and the corresponding module

{}
@@input_defs =

A hash of known input definitions and their ruby require filenames

{}
@@metadata_formats =

A hash of known metadata formatters and their ruby require filenames

{}
@@deplate_template =

This variable (array of strings) can contain some deplate markup that will be prepended to every file read

[]
@@messages =

A hash of => message class.

{}
@@messages_last =

The class of the message catalog that was loaded last

nil
@@message_object =

An instance of Deplate::Messages that is used for translating messages.

nil
@@slot_names =

The values for slot names are currently pre-defined in this hash. In the future they will be calculated dynamically as required. <TBD>This will be subject of change.

{
    #pre matter
    :prematter_begin => 0,
    :doc_def         => 5,
    :doc_beg         => 8,
    :head_beg        => 10,
    :fmt_packages    => 13,
    :mod_packages    => 15,
    :user_packages   => 20,
    :head            => 30,
    :head_meta       => 31,
    :meta            => 31,
    :head_identifier => 32,
    :head_title      => 33,
    :head_extra      => 34,
    :user_head       => 35,
    :mod_head        => 40,
    :user_head       => 50,
    :htmlsite_prev   => 55,
    :htmlsite_up     => 56,
    :htmlsite_next   => 57,
    # Synonyms for the above 3
    :htmlslides_prev => 55,
    :htmlslides_up   => 56,
    :htmlslides_next => 57,
    :html_relations  => 58,
    :css             => 60,
    :styles          => 65,
    :javascript      => 70,
    :head_end        => 80,
    :body_beg        => 90,
    :header          => 95,
    :prematter_end   => 100,
    :body_pre        => 105,
     #body
    :inner_body_begin => 0,
    :navbar_js       => 4,
    :navbar_top      => 5,
    :body_title      => 20,
    :body            => 50,
    :footnotes       => 75,
    :navbar_bottom   => 95,
    :inner_body_end  => 100,
    
    #post matter
    :body_post           => 0,
    :postmatter_begin    => 1,
    :footer              => 5,
    :html_pageicons_beg  => 10,
    :html_pageicons      => 11,
    :html_pageicons_end  => 12,
    :pre_body_end    => 15,
    :body_end        => 20,
    :doc_end         => 50,
    :postmatter_end  => 100,
}
@@formatter_classes =

A hash of formatter names and corresponding classes

{}
@@bib_style =
{}
@@input_classes =

A hash of names of input formats and corresponding classes

{}
@@log_destination =

The IO where to display messages.

$stderr

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(formatter_name = 'html', args = {}) ⇒ Core

formatter_name

A formatter name

args

A hash



1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
# File 'lib/deplate/core.rb', line 1655

def initialize(formatter_name='html', args={})
    @args         = args
    @slot_names   = @@slot_names.dup
    @options      = Deplate::Core.deplate_options(args[:options])
    @sources      = args[:sources] || @options.files
    @dest         = args[:dest]    || @options.out   || ''
    @vanilla      = @@vanilla || args[:vanilla] || false

    # set_safe
    
    reset(!args[:inherit_options])
    @output = Deplate::Output.new(self)
    # @output.destination = File.join(@options.dir, @dest)
    @output.destination = @dest
    
    call_methods_matching(self, /^deplate_initialize_/)

    formatter_class = args[:formatter] || @@formatter_classes[formatter_name]
    if formatter_class
        log('Initializing formatter')
        @formatter = formatter_class.new(self, args)
        call_methods_matching(self, /^formatter_initialize_/)
        call_methods_matching(@formatter, /^formatter_initialize_/)

        log('Initializing modules')
        call_methods_matching(self, /^module_initialize_/)

        log('Setting up text scanner')
        call_methods_matching(self, /^input_initialize_/)
        call_methods_matching(self, /^hook_pre_input_initialize_/)
        initialize_input(args)
        call_methods_matching(self, /^hook_post_input_initialize_/)

        log('Setting up formatter')
        call_methods_matching(@formatter, /^hook_pre_setup_/)
        @formatter.setup
        call_methods_matching(@formatter, /^hook_post_setup_/)

        log('User initialization')
        user_initialize if defined?(user_initialize)
        
        reset_output
        set_standard_clips

        if args[:now]
            log('Here we go ...')
            call_methods_matching(self, /^hook_pre_go_/)
            call_methods_matching(@formatter, /^hook_pre_go_/)
            go_now
            call_methods_matching(self, /^hook_post_go_/)
            call_methods_matching(@formatter, /^hook_post_go_/)
        end
    else
        log(['No or unknown formatter', formatter_name], :error)
    end
end

Class Attribute Details

.cjk_noncharsObject (readonly)

Returns the value of attribute cjk_nonchars.



32
33
34
# File 'lib/deplate/mod/lang-zh_CN-autospace.rb', line 32

def cjk_nonchars
  @cjk_nonchars
end

.cjk_rx_aObject (readonly)

Returns the value of attribute cjk_rx_a.



32
33
34
# File 'lib/deplate/mod/lang-zh_CN-autospace.rb', line 32

def cjk_rx_a
  @cjk_rx_a
end

.cjk_rx_CObject (readonly)

Returns the value of attribute cjk_rx_C.



32
33
34
# File 'lib/deplate/mod/lang-zh_CN-autospace.rb', line 32

def cjk_rx_C
  @cjk_rx_C
end

Instance Attribute Details

#accum_elementsObject

An array holding the elements after reading the input files.



1639
1640
1641
# File 'lib/deplate/core.rb', line 1639

def accum_elements
  @accum_elements
end

#clipsObject

A hash (id => object)



1611
1612
1613
# File 'lib/deplate/core.rb', line 1611

def clips
  @clips
end

#collected_outputObject

An array of collected output objects (@output).



1635
1636
1637
# File 'lib/deplate/core.rb', line 1635

def collected_output
  @collected_output
end

#current_sourceObject

Returns the value of attribute current_source.



1647
1648
1649
# File 'lib/deplate/core.rb', line 1647

def current_source
  @current_source
end

#current_source_statsObject

Returns the value of attribute current_source_stats.



1647
1648
1649
# File 'lib/deplate/core.rb', line 1647

def current_source_stats
  @current_source_stats
end

#destObject

The base output file.



1637
1638
1639
# File 'lib/deplate/core.rb', line 1637

def dest
  @dest
end

#footnote_last_idxObject

A running index.



1601
1602
1603
# File 'lib/deplate/core.rb', line 1601

def footnote_last_idx
  @footnote_last_idx
end

#footnotesObject

Other document specific variables. A hash containing the footnotes (id => object)



1597
1598
1599
# File 'lib/deplate/core.rb', line 1597

def footnotes
  @footnotes
end

#footnotes_usedObject

An array holding already consumed footnotes IDs.



1599
1600
1601
# File 'lib/deplate/core.rb', line 1599

def footnotes_used
  @footnotes_used
end

#formatterObject (readonly)

The formatter this instance of deplate uses.



1590
1591
1592
# File 'lib/deplate/core.rb', line 1590

def formatter
  @formatter
end

#headingsObject

A hash (level_string => object); currently only used by the structured formatter.



1608
1609
1610
# File 'lib/deplate/core.rb', line 1608

def headings
  @headings
end

#indexObject

A hash (label => [IndexEntry]).



1604
1605
1606
# File 'lib/deplate/core.rb', line 1604

def index
  @index
end

#inputObject (readonly)

The current input filter.



1626
1627
1628
# File 'lib/deplate/core.rb', line 1626

def input
  @input
end

#label_aliasesObject

A hash (label => corresponding elements).



1620
1621
1622
# File 'lib/deplate/core.rb', line 1620

def label_aliases
  @label_aliases
end

#labelsObject

A hash (label => level_string). Use of this hash should be replaced with uses of @label_aliases<TBD>



1615
1616
1617
# File 'lib/deplate/core.rb', line 1615

def labels
  @labels
end

#labels_floatingObject

An array used to postpone labels until there is some regular output.



1618
1619
1620
# File 'lib/deplate/core.rb', line 1618

def labels_floating
  @labels_floating
end

#optionsObject (readonly)

A open structure that holds this instance’s options.



1585
1586
1587
# File 'lib/deplate/core.rb', line 1585

def options
  @options
end

#outputObject (readonly)

The current output object (Deplate::Output).



1629
1630
1631
# File 'lib/deplate/core.rb', line 1629

def output
  @output
end

#output_filenameObject

An ordered array of output filenames.



1631
1632
1633
# File 'lib/deplate/core.rb', line 1631

def output_filename
  @output_filename
end

#output_headingsObject

An ordered array of top level/page headings.



1633
1634
1635
# File 'lib/deplate/core.rb', line 1633

def output_headings
  @output_headings
end

#postponed_printObject

An array of Proc objects that will be evaluated after printing any other elements.



1645
1646
1647
# File 'lib/deplate/core.rb', line 1645

def postponed_print
  @postponed_print
end

#preprocessObject

An array of Proc objects that will be evaluated before processing any other elements.



1642
1643
1644
# File 'lib/deplate/core.rb', line 1642

def preprocess
  @preprocess
end

#slot_namesObject (readonly)

A hash (slot name => number).



1623
1624
1625
# File 'lib/deplate/core.rb', line 1623

def slot_names
  @slot_names
end

#switchesObject

a stack with if/elseif status; skip input if the top-switch is true



1650
1651
1652
# File 'lib/deplate/core.rb', line 1650

def switches
  @switches
end

#vanillaObject (readonly)

Returns the value of attribute vanilla.



1587
1588
1589
# File 'lib/deplate/core.rb', line 1587

def vanilla
  @vanilla
end

#variablesObject

A hash that holds the current document’s variables.



1593
1594
1595
# File 'lib/deplate/core.rb', line 1593

def variables
  @variables
end

Class Method Details

.allow(arr, ids, source = nil) ⇒ Object

Set certain allow flags in array.



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# File 'lib/deplate/core.rb', line 595

def allow(arr, ids, source=nil)
    case ids
    when String
        ids = Deplate::Core.split_list(ids, ',', '; ', source)
        # ids = ids.scan(/[a-zA-Z.:]/)
    when Array
    else
        log(['Internal error', 'allow', ids], :error, source)
    end
    ids.each do |i|
        m = i[0..0]
        case m
        when '-'
            arr.delete(i[1..-1])
        when '+'
            arr << i[1..-1]
        else
            arr << i
        end
    end
    arr
end

.authors_split(text) ⇒ Object



1151
1152
1153
# File 'lib/deplate/core.rb', line 1151

def authors_split(text)
    text.split(/\s+and\s+/) if text
end

.canonic_args(hash, key, val, source = nil) ⇒ Object



1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
# File 'lib/deplate/core.rb', line 1028

def canonic_args(hash, key, val, source=nil)
    if key[-1..-1] == '!'
        key  = key[0..-2]
        type = :bool
    end
    if key =~ /^no[A-Z]/
        key  = key[2..2].downcase + key[3..-1]
        val  = false
        type = :bool
    elsif val.nil?
        type = :bool
        val  = true
    else
        case val
        when nil, 'true'
            type = :bool
            val  = true
        when 'false'
            type = :bool
            val  = false
        else
            type = :string
            if val =~ /^"(.*?)"$/
                val = val[1..-2]
            elsif val =~ /^\((.*?)\)$/
                val = val[1..-2]
            else
                # val.scan(/\\\\|\s/).each do |s|
                #     if s =~ /\s/
                #         Deplate::Core.log(['Deprecated syntax', 
                #             'Character should be preceded by a backslash', 
                #             s.inspect, val],
                #             :anyway, source)
                #     end
                # end
                val = val.strip
            end
            val = Deplate::Core.remove_backslashes(val)
        end
    end
    case type
    when :bool
        if key =~ /^\$[^\[]+\[/
            nokey = key.sub(/\[./) {|t| "[no#{t[1..1].upcase}"}
            hash[nokey] = !val
        else
            hash["no#{key[0..0].upcase}#{key[1..-1]}"] = !val
        end
    end
    hash[key] = val
    hash
end

.canonic_file_name(name, sfx, args = {}) ⇒ Object

Return the canonic file name for name. maj and min correspond to section numbers.



1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
# File 'lib/deplate/core.rb', line 1182

def canonic_file_name(name, sfx, args={})
    maj  = args[:maj]
    min  = args[:min]
    dir  = args[:dir]
    raw  = args[:raw]
    name = File.basename(name, '.*')
    name = clean_filename(name) unless raw
    if !name or (maj and maj != 0)
        canonic_numbered_file_name(name, sfx, maj, min, dir)
    elsif min and min != 0
        # fn = "%s.%02d%s" % [name, min, sfx]
        canonic_numbered_file_name(name, sfx, 0, min, dir)
    else
        fn = name + (sfx || '')
        dir ? File.join(dir, fn) : fn
    end
end

.clean_filename(text, args = {}) ⇒ Object



1200
1201
1202
1203
# File 'lib/deplate/core.rb', line 1200

def clean_filename(text, args={})
    args[:replacement] ||= '='
    return clean_name(text, args)
end

.clean_name(text, args = {}) ⇒ Object

Return an encoded name



1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
# File 'lib/deplate/core.rb', line 1206

def clean_name(text, args={})
  if text
    chars  = args[:chars] || '[:cntrl:].+*:"?<>|&\\\/%'
    chars += replacement = args[:replacement] || '_'
    if (extrachars = args[:extra])
      chars += extrachars
    end
    text = text.gsub(/[#{chars}]/) do |text|
        case text
        when replacement
            replacement * 2
        else
            # replacement + "%02X" % text[0]
            replacement + text.unpack('H2')[0].upcase
        end
    end
  end
end

.collect_deplate_options(id = nil, subdir = '', args = {}) ⇒ Object

Collect all available modules/parts/libraries etc. Check the file system and the “builtin” modules (e.g., when using the win32 exerb distribution).



1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
# File 'lib/deplate/core.rb', line 1333

def collect_deplate_options(id=nil, subdir='', args={})
    suffix = args[:suffix] || '.rb'
    use_rc = args[:rc] || false
    hash   = {}
    for d in library_directories(@@vanilla, use_rc, [subdir])
        collect_deplate_options_in_hash(hash, suffix, Dir[File.join(d, '*%s' % suffix)], nil, args)
    end

    builtin = "builtin_#{id}"
    if id and respond_to?(builtin)
        files = send(builtin)
        # files.collect! {|f| "#{f}.rb"}
        collect_deplate_options_in_hash(hash, suffix, files, File.join('deplate', subdir), args)
    end
   
    return hash.keys.sort, hash
end

.collect_standardObject

Collect all available modules, formatters, css files, and templates.



960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
# File 'lib/deplate/core.rb', line 960

def collect_standard
    if FileCache and File.exist?(FileCache)
        File.open(FileCache) do |f|
            data = Marshal.load(f)
            if data['version'] == Deplate::Core.microversion
                modules,    @@modules    = data['modules']
                formatters, @@formatters = data['formatters']
                themes,     @@themes     = data['themes']
                csss,       @@css        = data['css']
                templates,  @@templates  = data['templates']
                input_defs, @@input_defs = data['input']
                meta_fmts,  @@metadata_formats = data['metadata']
                Deplate::Core.log(['Using file cache', FileCache])
                return modules, formatters, csss, templates, input_defs, meta_fmts
            else
                Deplate::Core.log(['Old file cache', FileCache])
            end
        end
    end
    modules,    @@modules    = collect_deplate_options('modules',   'mod')
    formatters, @@formatters = collect_deplate_options('formatters','fmt')
    input_defs, @@input_defs = collect_deplate_options('input',     'input')
    meta_fmts,  @@metadata_formats = collect_deplate_options('metadata', 'metadata')
    themes,     @@themes     = collect_deplate_options('themes', 'themes',
                                                      :directories => true,
                                                      :suffix => '',
                                                      :rc => true)
    csss,       @@css        = collect_deplate_options('css',       'css', 
                                                       :suffix => '.css',
                                                       :rc => true)
    templates,  @@templates  = collect_deplate_options('templates', 'templates',
                                                      :suffix => '',
                                                      :rc => true)
        
    if FileCache
        File.open(FileCache, 'w+') do |f|
            data = {
                'version'    => Deplate::Core.microversion,
                'modules'    => [modules,    @@modules],
                'formatters' => [formatters, @@formatters],
                'themes'     => [themes,     @@themes],
                'css'        => [csss,       @@css],
                'templates'  => [templates,  @@templates],
                'input'      => [input_defs, @@input_defs],
                'metadata'   => [meta_fmts,  @@metadata_formats],
            }
            Marshal.dump(data, f)
            Deplate::Core.log(['Create file cache', FileCache])
        end
    end
    return modules, formatters, themes, csss, templates, input_defs, meta_fmts
end

.collect_theme(hash, theme_dir, subdir, suffix) ⇒ Object



1323
1324
1325
1326
1327
1328
# File 'lib/deplate/core.rb', line 1323

def collect_theme(hash, theme_dir, subdir, suffix)
    for f in Dir[File.join(theme_dir, subdir, "*#{suffix}")]
        name = File.basename(f, suffix)
        hash[name] = f
    end
end

.current_pwd(deplate = nil) ⇒ Object



1382
1383
1384
1385
1386
1387
1388
# File 'lib/deplate/core.rb', line 1382

def current_pwd(deplate=nil)
    if deplate and deplate.current_source
        File.dirname(deplate.current_source)
    else
        Dir.pwd
    end
end

.declare_bibstyle(bib_class, style) ⇒ Object



1306
1307
1308
# File 'lib/deplate/core.rb', line 1306

def declare_bibstyle(bib_class, style)
    @@bib_style[style] = bib_class
end

.declare_formatter(formatter_class, name = nil) ⇒ Object

Make a formatter class publically known.



1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
# File 'lib/deplate/core.rb', line 1311

def declare_formatter(formatter_class, name=nil)
    @@formatter_classes[formatter_class.myname] = formatter_class
    name = (name || formatter_class.myname).gsub(/[^[:alnum:]_]/, '_')
    self.class_eval do
        define_method("to_#{name}") do |text, *args|
            sourcename, _ = args
            reset(true)
            format_with_formatter(formatter_class, text, sourcename)
        end
    end
end

.declare_input_format(input_class, name = nil) ⇒ Object



1302
1303
1304
# File 'lib/deplate/core.rb', line 1302

def declare_input_format(input_class, name=nil)
    @@input_classes[name || input_class.myname] = input_class
end

.declare_symbols(name, klass) ⇒ Object



1298
1299
1300
# File 'lib/deplate/core.rb', line 1298

def declare_symbols(name, klass)
    @@symbols[name] = klass
end

.deplate(args = ARGV) ⇒ Object

Do what has to be done. This is the method that gets called when invoking deplate from the command line. It checks the command line arguments, sets up a Deplate::Core object, and makes it convert the input files.



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'lib/deplate/core.rb', line 178

def deplate(args=ARGV)
    log(['Configuration directory', CfgDir], :debug)
    if ENV['DeplateOptions']
        for keyval in Deplate::Core.split_list(ENV['DeplateOptions'], ';')
            key, val = keyval.split(/\s*=\s*/)
            case key
            when 'vanilla'
                @@vanilla = @vanilla = true
            end
        end
    end
    modules, formatters, themes, csss, templates, input_defs, meta_fmts = collect_standard
    
    options = deplate_options
    opts    = OptionParser.new do |opts|
        opts.banner =  'Usage: deplate.rb [OPTIONS] FILE [OTHER FILES ...]'
        opts.separator ''
        opts.separator 'deplate is a free software with ABSOLUTELY NO WARRANTY under'
        opts.separator 'the terms of the GNU General Public License version 2.'
        opts.separator ''

        opts.separator 'General Options:'
        
        opts.on('-a', '--[no-]ask', 
                'On certain actions, query user before overwriting files') do |bool|
            log("options.ask_user = #{bool}")
            options.ask_user = bool
        end

        opts.on('-A', '--allow ALLOW', 
                'Allow certain things: l, r, t, w, W, x, X, $') do |string|
            allow(options.allow, string, '[COMMAND LINE ARGUMENT]')
            log("options.allow = #{string}")
        end
    
        opts.on('-c', '--config FILE', String, 
                'Alternative user cfg file') do |file|
            log("options.cfg = #{file}")
            options.cfg = [file]
        end

        opts.on('--[no-]clean', 'Clean up temporary files') do |b|
            log("options.clean = #{b}")
            options.clean = b
        end

        opts.on('--color', 'Colored output') do |b|
            log("options.color = #{b}")
            enable_color(options)
        end

        opts.on('--css NAME', csss, 
                'Copy NAME.css to the destination directory, if inexistent') do |file|
            log("options.css = #{file}")
            options.css << [file]
        end

        opts.on('--copy-css NAME', csss, 
                'Copy NAME.css to the destination directory') do |file|
            log("options.css = #{file}")
            options.css << [file, true]
        end

        opts.on('-d', '--dir DIR', String, 'Output directory') do |dir|
            log("options.dir = #{dir}")
            ensure_dir_exists(dir, options)
            options.dir = dir
            # if dir.kind_of?(String) and File.directory?(dir)
            #     options.dir = dir
            # else
            #     log(["Directory doesn't exist", dir], :error)
            # end
        end

        opts.on('-D', '--define NAME=VALUE', String,
                'Define a document option') do |text|
            m = /^(\w+?)(=(.*))?$/.match(text)
            if m
                k = m[1]
                v = m[3]
                log(%{options.variables[#{k}] = "#{v}"})
                canonic_args(options.variables, k, v)
            else
                log(["Malformed variable definition on command line", text], :error)
            end
        end

        opts.on('-e', '--[no-]each', 'Handle each file separately') do |bool|
            log("options.each = #{bool}")
            options.each = bool
        end

        opts.on('--[no-]force', 'Force output') do |bool|
            log("options.force = #{bool}")
            options.force = bool
        end
        
        opts.on('-f', '--format FORMAT', String,
                'Output format (default: html)') do |fmt|
            log("options.fmt = #{fmt}")
            if formatters.include?(fmt)
                options.fmt = fmt
            else
                log(["Unknown formatter", fmt, formatters], :error)
                exit 5
            end
        end

        opts.on('--[no-]included', 'Output body only') do |bool|
            log("options.included = #{bool}")
            options.included = bool
        end

        opts.on('-i', '--input NAME', String, 'Input definition') do |str|
            log("options.input_def = #{str}")
            options.input_def = str
        end

        opts.on('--list FILE', String, 
                'A file that contains a list of input files') do |file|
            log("options.list = #{file}")
            options.list = file
        end

        opts.on('--log FILE', String, 
                'A file (or - for stdout) where to put the log') do |file|
            case file
            when '-'
                file = $stdout
            else
                file = File.expand_path(file)
            end
            log("options.log = #{file}")
            @@log_destination = file
        end

        opts.on('--[no-]loop', 'Read from stdin forever and ever') do |bool|
            log("options.loop = #{bool}")
            options.loop = bool
        end
        
        opts.on('--metadata [NAME]', meta_fmts, 
                'Save metadata in this format (default: yaml)') do |str|
            str ||= 'yaml'
            log("options.metadata_model = #{str}")
            unstopable_require(@@metadata_formats[str])
        end

        opts.on('-m', '--module MODULE', modules, 'Load a module') do |str|
            log("options.modules << #{str}")
            options.modules << str
        end

        opts.on('-o', '--out FILE', String, "Output to file or stdout ('-')") do |file|
            log("options.out = #{file}")
            d, f = File.split(file)
            if d != '.'
                options.dir = d
            end
            options.out         = f
            options.explicitOut = true
        end
        
        opts.on('-p', '--pattern GLOBPATTERN', String, 'File name pattern') do |str|
            log("options.file_pattern = #{remove_backslashes(str)}")
            options.file_pattern = remove_backslashes(str)
        end
        
        opts.on('-P', '--exclude GLOBPATTERN', String, 
                'Excluded file name pattern') do |str|
            log("options.file_excl_pattern = #{remove_backslashes(str)}")
            options.file_excl_pattern = remove_backslashes(str)
        end
        
        opts.on('-r', '--[no-]recurse', 'Recurse into directories') do |bool|
            log("options.recurse = #{bool}")
            options.recurse = bool
        end

        opts.on('--reset-filecache', 'Reset the file database') do |bool|
            log("options.reset_filecache = #{bool}")
            if File.exist?(FileCache)
                File.delete(FileCache) 
                log("Deleting file database. Files will be re-scanned on next run.", :anyway)
            end
            exit 0
        end

        opts.on('-R', '--[no-]Recurse', 'Recurse and rebuild hierarchy') do |bool|
            log("options.recurse_hierarchy = #{bool}")
            options.recurse = bool
            options.recurse_hierarchy = bool
        end

        opts.on('-s', '--skeleton NAME', String, 'Make skeleton available') do |str|
            log("options.skeletons << #{str}")
            options.skeletons << str
        end
        
        opts.on('--[no-]simple-names', 'Disable simple wiki names') do |bool|
            unless bool
                options.disabled_particles << Deplate::HyperLink::Simple
            end
        end
        
        opts.on('--split-level LEVEL', Integer, 'Heading level for splitting') do |i|
            log("options.split_level = #{i}")
            options.split_level = i
        end
        
        opts.on('--suffix SUFFIX', String, 'Suffix for output files') do |str|
            log("options.suffix = #{str}")
            options.suffix = str
        end
        
        opts.on('-t', '--template NAME', String, 'Template to use') do |str|
            if @@templates.has_key?(str) or File.exist?(str)
                log("options.template = #{@@templates[str]}")
                options.template = str
            else
                log(['Template not found', str], :error)
                exit 5
            end
        end
       
        opts.on('--theme THEME', String, 'Theme to use') do |value|
            set_theme(options, value)
        end

        opts.on('--[no-]vanilla', 'Ignore user configuration') do |bool|
            log("options.vanilla = #{bool}")
            @@vanilla = bool
        end

        opts.on('-x', '--allow-ruby [RUBY SAFE]', Integer,
                'Allow the execution of ruby code') do |level|
            if level
                options.allow_ruby = level
                allow(options.allow, level, '[COMMAND LINE ARGUMENT]')
            else
                options.allow_ruby = true
                allow(options.allow, 'x')
            end
            log("options.allow_ruby = #{options.allow_ruby}")
        end
        
        opts.on('-X', '--[no-]allow-exec', '--[no-]external',
                'Allow the execution of helper applications') do |bool|
            options.allow_external = bool
            allow(options.allow, 'X', '[COMMAND LINE ARGUMENT]')
            log("options.allow_external = #{bool}")
        end
    
        opts.separator ' '
        opts.separator 'LaTeX Formatter:'

        opts.on('--[no-]pdf', 'Prepare for use with pdf(la)tex') do |bool|
            log("options.pdftex = #{bool}")
            options.pdftex = bool
            options.variables['pdfOutput'] = true
        end

        opts.separator ' '
        opts.separator 'Available input defintions:'
        opts.separator input_defs.join(', ')
        
        opts.separator ' '
        opts.separator 'Available formatters:'
        opts.separator formatters.join(', ')
        
        opts.separator ' '
        opts.separator 'Available metadata formats:'
        opts.separator meta_fmts.join(', ')

        opts.separator ' '
        opts.separator 'Available modules:'
        opts.separator modules.join(', ')

        if themes
            opts.separator ' '
            opts.separator 'Available themes:'
            opts.separator themes.join(', ')
        end

        opts.separator ' '
        opts.separator 'Available css files:'
        opts.separator csss.join(', ')

        opts.separator ' '
        opts.separator 'Available templates:'
        opts.separator templates.join(', ')

        opts.separator ' '
        opts.separator 'Other Options:'

        opts.on('--debug [LEVEL]', Integer, 'Show debug messages') do |v|
            if v
                @log_treshhold = v
            end
            $DEBUG = TRUE
            $VERBOSE = TRUE
        end

        opts.on('--[no-]profile', 'Profile execution') do |b|
            log("profile = #{b}")
            # require "profile" if b
        end
        
        opts.on('--[no-]quiet', 'Be quiet') do |bool|
            log("quiet = #{bool}")
            @@quiet = bool
        end

        opts.on('-v', '--[no-]verbose', 'Run verbosely') do |v|
            log("verbose = #{v}")
            $VERBOSE = v
        end

        opts.on_tail('-h', '--help', 'Show this message') do
            puts opts
            exit 1
        end

        opts.on_tail('--list-modules [REGEXP]', Regexp,
                     'List modules matching a pattern') do |rx|
            m = rx.nil? ? modules : modules.find_all {|n| n =~ rx}
            puts m.join("\n")
            exit 1
        end

        opts.on_tail('--list-css [REGEXP]', Regexp,
                     'List css files matching a pattern') do |rx|
            m = rx.nil? ? csss : csss.find_all {|n| n =~ rx}
            puts m.join("\n")
            exit 1
        end

        opts.on_tail('--version', 'Show version') do
            puts version
            exit 0
        end
        
        opts.on_tail('--microversion', 'Show version') do
            puts microversion
            exit 0
        end
    end
    options.opts = opts

    @@command_line_args = args.dup
    unless options.ini_command_line_arguments.empty?
        args += options.ini_command_line_arguments
        options.ini_command_line_arguments = []
    end
    options.files = opts.parse!(args)

    if options.list
        accum = []
        File.open(options.list) do |io|
            io.each {|l| accum << l.chomp}
        end
        options.files = accum + options.files
    else
        if options.files.empty?
            failhelp(opts, 'No input files given!')
        end
    end

    options.fmt ||= 'html'
    require_standard(options)

    formatter_class = @@formatter_classes[options.fmt]
    
    # if options.multi_file_output
    #     if !options.dir
    #         failhelp(opts, "Output to multiple files requires the --dir option!")
    #     elsif options.each
    #         failhelp(opts, "Cannot use --each and multi-file output at the same time!")
    #     end
    # end
    
    if formatter_class
        formatter_class.set_options_for_file(options, options.files[0])
        prc = Deplate::Core.new(options.fmt,
                          :formatter => formatter_class, 
                          :options => options, 
                          :now => true)
    else
        log(["Unknown formatter", options.fmt], :error)
        exit 5
    end
end

.deplate_options(inherit = nil) ⇒ Object

Set up the standard options structure.

inherit

A OpenStruct; if provided, reuse it



871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
# File 'lib/deplate/core.rb', line 871

def deplate_options(inherit=nil)
    options               = inherit || OpenStruct.new
    options.ini_command_line_arguments ||= []
    options.modules     ||= []
    options.headings    ||= []
    options.resources   ||= []
    options.prelude     ||= []
    options.clean       ||= true
    options.force       ||= true
    options.css         ||= []
    options.variables   ||= Deplate::Variables.new
    deplate_predefined_variables(options)
    options.clips       ||= {}
    options.ext         ||= ''
    # options.dir         ||= '.'
    options.allow       ||= []
    options.skeletons   ||= []
    options.split_level ||= 1
    options.disabled_particles ||= []
    options.autoindexed        ||= []
    options.abbrevs     ||= {}
    reset_listings_and_counters(options, true)
    read_ini(options) unless inherit
    return options
end

.deplate_predefined_variables(options) ⇒ Object



897
898
899
# File 'lib/deplate/core.rb', line 897

def deplate_predefined_variables(options)
    options.variables['env'] = ENV
end

.enable_color(options) ⇒ Object

Enable colored log output

options

A OpenStruct as returned by Deplate::Core.deplate_options



944
945
946
947
948
949
950
951
952
953
954
955
956
957
# File 'lib/deplate/core.rb', line 944

def enable_color(options)
    unless @@colored_output
        unstopable_require('term/ansicolor') do
            eval <<-EOR
            class Deplate::Color
                class << self
                    include Term::ANSIColor
                end
            end
            EOR
            @@colored_output = options.color = true
        end
    end
end

.ensure_dir_exists(dir, options = nil) ⇒ Object

Make sure dir exists



1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
# File 'lib/deplate/core.rb', line 1226

def ensure_dir_exists(dir, options=nil)
    unless File.exist?(dir) or dir.empty? or dir == '.'
        if !options or 
            options.force or 
            Deplate::Core.query_user(options, 
                                     "Create directory '#{dir}' (y/N)? ", 
                                     'y')
            parent = File.dirname(dir)
            unless File.exist?(parent)
                ensure_dir_exists(parent, options)
            end
            Deplate::Core.log(["Creating directory", dir])
            Dir.mkdir(dir)
        else
            log(["Directory doesn't exist", dir, Dir.pwd], :error)
            exit 5
        end
    end
end

.ensure_suffix(name, suffix) ⇒ Object



1246
1247
1248
1249
1250
1251
1252
1253
# File 'lib/deplate/core.rb', line 1246

def ensure_suffix(name, suffix)
    ext = File.extname(name)
    if ext != suffix
        return name + suffix
    else
        return name
    end
end

.escape_characters(text, args) ⇒ Object



1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
# File 'lib/deplate/core.rb', line 1129

def escape_characters(text, args)
    esc = args[:esc] || args[:escape] || args['esc'] || args['escape'] || ''
    ebs = args[:escapebackslash] || args['escapebackslash'] || args['template'] || 0
    case ebs
    when true
        ebs = 1
    else
        ebs = ebs.to_i
    end
    if esc.include?('\\')
        esc = esc.delete('\\')
        ebs ||= 1
    end
    if ebs > 0
        text = text.gsub(/\\/, '\\\\' * ebs)
    end
    unless esc.empty?
        text = text.gsub(/([#{esc}])/, '\\\\\\1')
    end
    text
end

.file_join(*path) ⇒ Object

Purge *path and return it as sting



1268
1269
1270
1271
1272
1273
# File 'lib/deplate/core.rb', line 1268

def file_join(*path)
    path.compact!
    path.delete(".")
    path.delete("")
    File.join(*path)
end

.get_index_name(idx) ⇒ Object

Clean idx‘s (a instance of Deplate::IndexEntry) name from backslashes



1156
1157
1158
1159
# File 'lib/deplate/core.rb', line 1156

def get_index_name(idx)
    # return remove_backslashes(idx.name.split(/\s*\|\s*/)[0])
    return remove_backslashes(idx.name)
end

.get_out_fullname(fname, suffix, options, args = {}) ⇒ Object

Get the canonic output filename for fname.

fname

The input file name

suffix

The suffix to use

options

A OpenStruct as returned by Deplate::Core.deplate_options

maj

The major section/page number

maj

The minor section/page number



1281
1282
1283
1284
# File 'lib/deplate/core.rb', line 1281

def get_out_fullname(fname, suffix, options, args={})
    # File.join(options.dir, get_out_name(fname, suffix, options, args))
    file_join(options.dir, get_out_name(fname, suffix, options, args))
end

.get_out_name(fname, suffix, options, args = {}) ⇒ Object



1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
# File 'lib/deplate/core.rb', line 1286

def get_out_name(fname, suffix, options, args={})
    path = []
    path << get_out_name_dir(fname, options)
    if suffix
        fn  = File.basename(fname, '.*')
        path << canonic_file_name(fn, suffix, args)
    else
        path << fname
    end
    file_join(*path)
end

.get_out_name_dir(fname, options) ⇒ Object

Return the output directory for fname



1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
# File 'lib/deplate/core.rb', line 1256

def get_out_name_dir(fname, options)
    if options.recurse_hierarchy
        # dir = File.dirname(fname).split(Regexp.new(Regexp.escape(File::SEPARATOR)))[1..-1]
        # dir = File.dirname(fname).split(Regexp.new(Regexp.escape(File::SEPARATOR)))
        # return File.join(*dir)
        return File.dirname(fname)
    else
        return '.'
    end
end

.is_allowed?(options, ids, args = {}) ⇒ Boolean

Check whether a certain action is allowed

Returns:

  • (Boolean)


619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
# File 'lib/deplate/core.rb', line 619

def is_allowed?(options, ids, args={})
    arr = options.allow
    if arr.include?('all')
        return true
    end
    case ids
    when String
        ids = Deplate::Core.split_list(ids, ',', '; ')
    when Array
    else
        log(['Internal error', 'allow', ids], :error)
    end
    for i in ids
        if arr.include?(i)
            return true
        end
    end
    logger = args[:logger]
    logger.log(['No permission', ids.join(', ')], :anyway) if logger
    return false
end

.is_file?(fname) ⇒ Boolean

Returns:

  • (Boolean)


1378
1379
1380
# File 'lib/deplate/core.rb', line 1378

def is_file?(fname)
    return !fname.empty? && File.exists?(fname) && !File.directory?(fname)
end

.library_directories(vanilla, use_rc, subdirs) ⇒ Object

Return an array of directories that could contain deplate files.



1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
# File 'lib/deplate/core.rb', line 1353

def library_directories(vanilla, use_rc, subdirs)
    @library_directories ||= {}
    acc = []
    dirs = [DataDir, LibDir]
    dirs.unshift(CfgDir) unless vanilla
    dirs.unshift(*EtcDirs)
    dirs.unshift(File.join(current_pwd, 'deplate.rc')) if use_rc
    for subdir in subdirs
        unless @library_directories[subdir]
            ad = []
            for dir in dirs
                if dir
                    fd = File.join(dir, subdir)
                    if File.exist?(fd)
                        ad << fd
                    end
                end
            end
            @library_directories[subdir] = ad
        end
        acc += @library_directories[subdir]
    end
    acc
end

.load_user_config(options, file) ⇒ Object



856
857
858
859
860
861
862
863
864
865
866
867
# File 'lib/deplate/core.rb', line 856

def load_user_config(options, file)
    if File.exist?(file)
        if File.stat(file).directory?
            for f in Dir[File.join(file, '*.rb')]
                user_config(options, f)
            end
        else
            Deplate::Core.log(["Loading", file])
            load(file)
        end
    end
end

.log(text, condition = nil, source = nil) ⇒ Object

This is the actual logging method. Every log message should pass through this method.



1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
# File 'lib/deplate/core.rb', line 1015

def log(text, condition=nil, source=nil)
    if log_valid_condition?(condition)
        text = log_filter(text)
        if source
            msg = log_build_message(text, condition, source.file, source.begin, source.end)
        else
            msg = log_build_message(text, condition)
        end
        log_to(msg)
        log_to(caller.join("\n")) if $DEBUG and condition == :error
    end
end

.microversionObject

Return the current micorversion number as string.



933
934
935
936
937
938
939
940
# File 'lib/deplate/core.rb', line 933

def microversion
    [
        Deplate::Core::Version, 
        Deplate::Core::VersionSfx,
        '-',
        Deplate::Core::MicroRev,
    ].join
end

.props(proplist, field) ⇒ Object

Retrieve field information from a “property list” as used form, e.g., specifying column widths in tables



1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/deplate/core.rb', line 1163

def props(proplist, field)
    if proplist
        Deplate::Core.split_list(proplist, ',', ';').collect do |c|
            rv = nil
            for key, val in c.scan(/(\w+?)[:.](\S+)/)
                if key == field
                    rv = val
                    break
                end
            end
            rv
        end
    else
        []
    end
end

.push_value(var, value, sep = ',') ⇒ Object



1121
1122
1123
1124
1125
1126
1127
# File 'lib/deplate/core.rb', line 1121

def push_value(var, value, sep=',')
    if var and !var.empty?
        [var, sep, value].join
    else
        value
    end
end

.query_user(options, msg, results, rv = true) ⇒ Object



1081
1082
1083
1084
1085
1086
1087
1088
1089
# File 'lib/deplate/core.rb', line 1081

def query_user(options, msg, results, rv=true)
    ok = if options and options.ask
             puts msg
             results.include?(gets.chomp)
         else
             true
         end
    ok ? rv : !rv
end

.quiet?Boolean

Returns:

  • (Boolean)


1390
1391
1392
# File 'lib/deplate/core.rb', line 1390

def quiet?
    @@quiet
end

.read_ini(options) ⇒ Object

Read CfgDir/deplate.ini

This file knows the following commands/entries

mod NAME

Load module NAME

fmt NAME

Set the default formatter

clip NAME=TEXT

Set a clip

wiki NAME.SUFFIX BASEURL

Define an interwiki

wikichars UPPER LOWER

Define the set of allowed

character in wiki names
VAR=VALUE

Set the variable VAR to VALUE

$ENV=VALUE

Set the environment variable VAR to VALUE

Lines beginning with one of ‘;#%’ are considered comments.



680
681
682
683
# File 'lib/deplate/core.rb', line 680

def read_ini(options)
    read_ini_file(options, File.join(CfgDir, 'deplate.ini'))
    read_ini_file(options, File.join(Dir.pwd, "deplate.rc", 'deplate.ini')) if is_allowed?(options, 'r')
end

.read_ini_file(options, inifile) ⇒ Object



685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
# File 'lib/deplate/core.rb', line 685

def read_ini_file(options, inifile)
    if File.exist?(inifile)
        mode   = :normal
        acc    = []
        endm   = nil
        setter = nil
        File.open(inifile) do |io|
            until io.eof?
                line = io.gets
                line.chomp!
                case mode
                when :normal
                    if line =~ /^\s*[;#%*]/
                        # comment
                        next
                    elsif line =~ /^(-\S+)(\s+(.*?)\s*)?$/
                        options.ini_command_line_arguments << $1
                        options.ini_command_line_arguments << $3 if $3
                    elsif line =~ /^\s*allow\s+(.+?)\s*$/
                        allow(options.allow, $1, Deplate::Source.new(inifile))
                    elsif line =~ /^\s*mod\s+(\S+)/
                        mod = $1
                        if mod[0..0] == '-'
                            options.modules.delete(mod[1..-1])
                        else
                            options.modules << $1
                        end
                    elsif line =~ /^\s*fmt\s+(\S+)/
                        options.fmt = $1
                    elsif line =~ /^\s*clip\s+([^\s=]+)\s*=\s*(.+)/
                        options.clips[$1] = $2
                    elsif line =~ /^\s*wiki ([A-Z]+)(\.\w+)?\s*=\s*(.+)/
                        Deplate::InterWiki.add($1, $3, $2)
                    elsif line =~ /^\s*wikichars\s*(\S+)\s*(\S+)/
                        Deplate::HyperLink.setup($1, $2)
                    elsif line =~ /^\s*encoding\s+(.+)/
                        options.variables['encoding'] = $1
                    elsif line =~ /^\s*app\s*([_\w]+)\s*=\s*(.+)/
                        Deplate::External.def_app $1, $2
                    elsif line =~ /^\s*(option\s+|:)([_\w]+)([!~]|\s*([?%])?=\s*(.+))/
                        case $3
                        when '!'
                            val = true
                        when '~'
                            val = false
                        else
                            case $4
                            when '?'
                                case $5
                                when 'true', 'yes', 'on'
                                    val = true
                                when 'false', 'no', 'off'
                                    val = false
                                else
                                    Deplate::Core.log(['Malformed configuration line', line], :error)
                                    next
                                end
                            when '%'
                                val = $5.to_i
                            else
                                val = $5
                            end
                        end
                    options.send("#$2=", val)
                    elsif line =~ /^\s*\$(\S+)\s*=\s*(.+)/
                        ENV[$1] = $2
                    elsif line =~ /^\s*(\S+)\s*=<<(.+)/
                        mode = :multiline
                        endm = $2
                        setter = lambda {|val| canonic_args(options.variables, $1, val)}
                    elsif line =~ /^\s*(\S+)\s*=\s*(.+)/
                        canonic_args(options.variables, $1, $2)
                    elsif !line.empty?
                        Deplate::Core.log(['Malformed configuration line', line], :error)
                    end
                when :multiline
                    if line == endm
                        setter.call(acc)
                        acc  = []
                        mode = :normal
                    else
                        acc << line
                    end
                else
                    raise "Invalid mode"
                end
            end
        end
    end
end

.remove_backslashes(text) ⇒ Object

Remove all backslashes from text



1092
1093
1094
# File 'lib/deplate/core.rb', line 1092

def remove_backslashes(text)
    return text.gsub(/\\(.)/, '\\1') if text
end

.require_formatter(options, fmt = nil) ⇒ Object

Load the formatter named in options.fmt.

options

A OpenStruct as returned by Deplate::Core.deplate_options



788
789
790
791
792
793
794
795
796
797
798
799
800
801
# File 'lib/deplate/core.rb', line 788

def require_formatter(options, fmt=nil)
    fmt ||= options.fmt
    if @@formatter_classes[fmt]
        Deplate::Core.log(['Formatter already loaded', fmt])
    else
        Deplate::Core.log(['Require formatter', fmt])
        fmtf = @@formatters[fmt]
        require fmtf
    end
    for fmt in @@formatter_classes[fmt].formatter_family_members.reverse
        user_config(options, File.join('after', 'fmt', '%s.rb' % fmt), CfgDir)
        user_config(options, File.join('after', 'fmt', fmt), CfgDir)
    end
end

.require_input(options, input_name = nil) ⇒ Object

Load the input definition if any.

options

A OpenStruct as returned by Deplate::Core.deplate_options



778
779
780
781
782
783
784
# File 'lib/deplate/core.rb', line 778

def require_input(options, input_name=nil)
    name = input_name || options.input_def
    rb   = @@input_defs[name]
    if rb
        require rb
    end
end

.require_module(options, module_name) ⇒ Object

Load a module.

options

A OpenStruct as returned by Deplate::Core.deplate_options

module_name

The name of the module to be loaded



806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
# File 'lib/deplate/core.rb', line 806

def require_module(options, module_name)
    Deplate::Core.log(['Require module', module_name])
    mf = @@modules[module_name]
    vsave, $VERBOSE = $VERBOSE, false
    begin
        require mf
        user_config(options, File.join('after', 'mod', '%s.rb' % module_name), CfgDir)
        user_config(options, File.join('after', 'mod', module_name), CfgDir)
        return true
    rescue Exception => e
        Deplate::Core.log(['Loading module failed', module_name, e], :error)
        Deplate::Core.log(['Known modules', @@modules], :debug)
        return false
    ensure
        $VERBOSE = vsave
    end
end

.require_standard(options) ⇒ Object

Load the formatter, all required modules, and the user configuration files.



573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/deplate/core.rb', line 573

def require_standard(options)
    require_input(options)

    require_formatter(options)
    
    for m in options.modules
        require_module(options, m) if m
    end

    # require 'deplate/mod/en' if we haven't loaded any lang 
    # module yet.
    require_module(options, 'lang-en') unless @@messages_last

    # load general user config
    options.cfg ||= ['config.rb', CfgDir]
    unless @@vanilla
        user_config(options, *options.cfg)
        user_setup(options) if defined?(user_setup)
    end
end

.reset_listings_and_counters(options, conditionally = false) ⇒ Object



901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
# File 'lib/deplate/core.rb', line 901

def reset_listings_and_counters(options, conditionally=false)
    unless conditionally and options.counters
        c = options.counters = Deplate::Counters.new(self)
        c.def_counter('toc')
        c.def_counter('lot', :parent => 'toc:1')
        c.def_counter('lof', :parent => 'toc:1')
    end
    unless conditionally and options.listings
        l = options.listings = Deplate::Listings.new(self)
        l.def_listing('toc', nil,
                      'prefix' => 'hd',
                      'entity' => 'heading'
                     )
        l.def_listing('lot', nil,
                      'prefix'  => 'tab',
                      # 'counter' => :tables,
                      'entity'  => 'table'
                     )
        l.def_listing('lof', nil,
                      'prefix'  => 'fig',
                      # 'counter' => :figures,
                      'entity'  => 'figure'
                     )
    end
end

.set_theme(options, name) ⇒ Object



642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# File 'lib/deplate/core.rb', line 642

def set_theme(options, name)
    theme_dir = @@themes[name]
    if theme_dir
        EtcDirs.unshift(theme_dir)
        collect_theme(@@css, theme_dir, 'css', '.css')
        collect_theme(@@templates, theme_dir, 'templates', '')
        for resource in Dir[File.join(theme_dir, 'resources', '*')]
            options.resources << [resource, false]
        end
        prelude = File.join(theme_dir, 'prelude.txt')
        if File.exist?(prelude)
            options.prelude.concat(File.readlines(prelude).map {|l| l.chomp})
        end
        if is_allowed?(options, 's')
            read_ini_file(options, File.join(theme_dir, 'theme.ini'))
            unless options.ini_command_line_arguments.empty?
                options.opts.parse!(options.ini_command_line_arguments)
            end
        end
    else
        log(['Unknown theme', name], :error)
    end
end

.split_list(string, chars = nil, deprecated = nil, source = nil, doubt = :use_deprecated) ⇒ Object



1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
# File 'lib/deplate/core.rb', line 1096

def split_list(string, chars=nil, deprecated=nil, source=nil, doubt=:use_deprecated)
    if string
        chars ||= ','
        list = string.scan(/((?:\\.|[^#{chars}\\]+)+)(?:[#{chars}]\s*|\Z)/).flatten
        list = list.map {|e| remove_backslashes(e)}
        if deprecated
            list1 = split_list(string, deprecated)
            if list1 != list and 
                # (list1.size > 1 or list1[0] != string) and 
                string !~ /[#{chars}]/ and string =~ /[#{deprecated}]/
                # case doubt
                # when :use_deprecated
                    Deplate::Core.log(['Assuming the use of deprecated list separators', deprecated.inspect, string.inspect], :error, source)
                    return list1
                # else
                #     Deplate::Core.log(['Possible use of deprecated list separators', deprecated.inspect, string.inspect], :anyway, source)
                # end
            end
        end
        return list
    else
        return []
    end
end

.unstopable_require(name) ⇒ Object

require NAME but don’t stop if an error occurs; takes an optional block as argument, which is called when the file was successfully loaded.

name

A string passed on to require



827
828
829
830
831
832
833
834
835
836
# File 'lib/deplate/core.rb', line 827

def unstopable_require(name)
    begin
        require name
        if block_given?
            yield
        end
    rescue Exception => e
        log(["Require failed", name, e], :error)
    end
end

.user_config(options, file, dir = nil) ⇒ Object

Load the user configuration for a file/module.

options

A OpenStruct as returned by Deplate::Core.deplate_options

file

Either a file name or a directory; if it is a

directory, all ruby files in that directory will be loaded


842
843
844
845
846
847
848
849
850
851
852
853
854
# File 'lib/deplate/core.rb', line 842

def user_config(options, file, dir=nil)
    unless @@vanilla
        if dir
            dirs = [dir]
            dirs << File.join(current_pwd, 'deplate.rc') if is_allowed?(options, 'r')
            for f in dirs
                load_user_config(options, File.join(f, file))
            end
        else
            load_user_config(options, file)
        end
    end
end

.user_setup(options) ⇒ Object



14
15
16
# File 'lib/deplate/mod/colored-log.rb', line 14

def self.user_setup(options)
    enable_color(options)
end

.versionObject

Return the current version number as string.



928
929
930
# File 'lib/deplate/core.rb', line 928

def version
    Deplate::Core::Version
end

Instance Method Details

#add_index(container, names, level_as_string = '') ⇒ Object

Register a new index entry.



2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
# File 'lib/deplate/core.rb', line 2988

def add_index(container, names, level_as_string='')
    @index_last_idx += 1
    id    = "idx00#{@index_last_idx}"
    words = names.split(/\s*\|\s*/)
    lname = Deplate::Core.remove_backslashes(words[0])
    if container
        # container = container.top_container || container
        level_as_string = container.level_as_string
    end
    if @options.dont_index.delete(lname)
        return nil
    else
        i = @index[lname]
        unless i
            i = @index.find do |k, a|
                a.find do |i|
                    i.synonymes.find {|j| words.include?(j)}
                end
            end
            if i
                lname = i[0]
                i = @index[lname]
            end
        end
        if @options.each
            f = file_with_suffix(File.basename(@current_source), @options.suffix, true)
        elsif @options.multi_file_output
            f = nil
        else
            f = @dest
        end
        d = Deplate::IndexEntry.new(container) do |idx|
            idx.name            = lname
            idx.synonymes       = words
            idx.label           = id
            idx.file            = f
            idx.level_as_string = level_as_string
        end
        if i
            i << d
        else
            @index[lname] = [d]
        end
        return d
    end
end

#add_label(invoker, label, level_as_string, opts = {}) ⇒ Object

Register a new label.

invoker

The labelled object

label

The label name

level_as_string

The section heading’s level as string (redundant???)



2860
2861
2862
2863
2864
2865
2866
2867
# File 'lib/deplate/core.rb', line 2860

def add_label(invoker, label, level_as_string, opts={})
    if !opts[:anyway] and (@labels[label] or @label_aliases[label])
        invoker.log(['Label already defined', label, level_as_string], :error)
    else
        @labels[label]        = level_as_string
        @label_aliases[label] = opts[:container] || invoker
    end
end

#allow_externalObject

Return whether external applications may be run



2458
2459
2460
# File 'lib/deplate/core.rb', line 2458

def allow_external
    @options.allow_external || is_allowed?('X')
end

#allow_rubyObject

Return whether ruby code may be evaluated.



2453
2454
2455
# File 'lib/deplate/core.rb', line 2453

def allow_ruby
    @options.allow_ruby || is_allowed?('x')
end

#auto_numbered(base, args = nil) ⇒ Object



2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
# File 'lib/deplate/core.rb', line 2284

def auto_numbered(base, args=nil)
    if args
        n = if (s = args[:set])
                @auto_numbered[base] = s
            elsif (s = args[:inc])
                if @auto_numbered[base]
                    @auto_numbered[base] += s
                else
                    @auto_numbered[base] = 0
                end
            else
                log(['Internal error', 'auto_numbered', base, args], :error)
                nil
            end
        if (t = args[:fmt])
            t % n
        elsif (t = args[:fmt0])
            if n > 0
                t % n
            else
                t % nil
            end
        else
            n
        end
    else
        return @auto_numbered[base]
    end
end

#auxiliary_auto_filename(type, idx, body = nil, suffix = nil) ⇒ Object

Get the name for automatically generated auxiliary files (e.g., when no ID was provided)



2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
# File 'lib/deplate/core.rb', line 2067

def auxiliary_auto_filename(type, idx, body=nil, suffix=nil)
    if @variables['mandatoryID']
        raise msg('No ID given')
    else
        prefix = @variables['prefixID']
        if prefix.nil?
            prefix = Deplate::Core.clean_filename(File.basename(@dest, '.*'))
        end
        fn = [prefix]
        fn << ["_#{type}_#{idx}"]
        fn << '.' << suffix if suffix
        return fn.join
    end
end

#auxiliary_dirname(full_name = false, ensure_dir_exists = false) ⇒ Object

Get the dir for auxiliary files; take care of the auxiliaryDirSuffix variable

  • If auxiliaryDirSuffix isn’t defined, return default if non-nil.

  • Create dir if ensure_dir_exists is true.



2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
# File 'lib/deplate/core.rb', line 2097

def auxiliary_dirname(full_name=false, ensure_dir_exists=false)
    path  = []
    path  << File.dirname(@dest) if full_name
    aux   = @variables['auxiliaryDir']
    if aux
        path << aux
    else
        sdsfx = @variables['auxiliaryDirSuffix']
        path  << File.basename(@dest, '.*') + sdsfx if sdsfx
    end
    rv = Deplate::Core.file_join(*path)
    ensure_dir_exists(rv) if ensure_dir_exists
    rv
end

#auxiliary_filename(filename, full_name = false) ⇒ Object

Get the proper filename for an auxiliary file, respecting the value of auxiliaryDirSuffix



2084
2085
2086
2087
2088
2089
2090
2091
# File 'lib/deplate/core.rb', line 2084

def auxiliary_filename(filename, full_name=false)
    sd = auxiliary_dirname(full_name)
    if sd
        return Deplate::Core.file_join(sd, filename)
    else
        return filename
    end
end

#bib_styler(style) ⇒ Object



3109
3110
3111
3112
# File 'lib/deplate/core.rb', line 3109

def bib_styler(style)
    styler = @@bib_style[style] || @@bib_style['default']
    styler.new(self)
end

#body_stringObject

Return all the formatted output as string.



2666
2667
2668
# File 'lib/deplate/core.rb', line 2666

def body_string
    return @collected_output.collect {|o| o.join("\n")}.join("\n")
end

#body_writeObject

Write the output to the disk.



2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
# File 'lib/deplate/core.rb', line 2671

def body_write
    rv = nil
    method = uri_method_name_with_prefix("body_write_to_", @dest)
    log(["Writing output file(s)", @collected_output.size])
    if method
        for output in @collected_output
            rv = send(method, @dest, output)
        end
    elsif @dest == '-'
        sep = @variables["stdoutSeparator"]
        for output in @collected_output
            puts(output.join("\n"))
            puts sep if sep
        end
    elsif @options.multi_file_output
        @collected_output.each_with_index do |output, i|
            if output.body_empty?
                log("Empty body ... skipping")
            else
                dest = output.destination
                rv ||= dest
                log(["Writing file", i, dest])
                write_file(dest) do |io|
                    io.puts(output.join("\n"))
                end
                call_methods_matching(@formatter, /^hook_post_write_file_/)
                output.(@metadata)
                if @options. and output.
                    md_dest = Deplate::Core.file_join(@options.dir, output.)
                    log(["Saving metadata", md_dest])
                    (md_dest, output)
                end
            end
        end
    else
        dest = @collected_output.first.destination
        # dest = @dest
        log(["Writing file", dest])
        write_file(dest) do |io|
            for output in @collected_output
                io.puts(output.join("\n"))
            end
            io.puts
        end
        call_methods_matching(@formatter, /^hook_post_write_file_/)
        if @options.
            md = @metadata.dup
            for output in @collected_output
                if output.
                    for key, data in output.
                        for e in data
                            (e, md)
                        end
                    end
                end
            end
            unless md.empty?
                output  = @collected_output.first
                md_dest = auxiliary_filename(output.(@dest), true)
                log(["Saving metadata", md_dest])
                (md_dest, output, md)
            end
        end
    end
    rv || @dest
end

#break_output(minor = false) ⇒ Object

Insert a page/output break.



2660
2661
2662
2663
# File 'lib/deplate/core.rb', line 2660

def break_output(minor=false)
    @output.body_flush
    new_output(@output)
end

#call_methods_matching(obj, rx, *args) ⇒ Object

Call all of obj’s methods matching rx



1838
1839
1840
1841
1842
1843
1844
# File 'lib/deplate/core.rb', line 1838

def call_methods_matching(obj, rx, *args)
    unless @vanilla
        for m in matching_methods(obj, rx)
            obj.send(m, *args)
        end
    end
end

#clean_makefile_name(text, multiplier = 1) ⇒ Object



208
209
210
211
# File 'lib/deplate/mod/makefile.rb', line 208

def clean_makefile_name(text, multiplier=1)
    backslash = '\\\\' * multiplier
    text.gsub(/[$]/, "#{backslash}\\0")
end

#collected_cssObject

Get all css files that are required by the current document.



2531
2532
2533
# File 'lib/deplate/core.rb', line 2531

def collected_css
    @@css
end

#copy_file(from, to) ⇒ Object

Copy a file.



2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
# File 'lib/deplate/core.rb', line 2804

def copy_file(from, to)
    if File.directory?(to)
        to = File.join(to, File.basename(from))
        dir = to
    else
        dir = File.dirname(to)
    end
    if File.exist?(to)
        log(['File already exists', to])
    else
        ok = if @options.ask
                 puts "File '#{file}' already exists. Overwrite (y/N)? "
                 gets.chomp == 'y'
             else
                 true
             end
        if ok
            ensure_dir_exists(dir)
            FileUtils.cp_r(from, to)
            log(['Copy file', from, to])
        end
    end
end

#copy_resourcesObject



2739
2740
2741
2742
2743
2744
2745
2746
2747
# File 'lib/deplate/core.rb', line 2739

def copy_resources
    @options.resources.each do |src, anyway|
        res  = File.basename(src)
        dest = auxiliary_filename(res, true)
        if anyway or !File.exist?(dest)
            copy_file(src, dest)
        end
    end
end

#current_headingObject



2828
2829
2830
# File 'lib/deplate/core.rb', line 2828

def current_heading
    @options.counters.get('toc')
end

#current_heading_elementObject



2832
2833
2834
2835
# File 'lib/deplate/core.rb', line 2832

def current_heading_element
    e = @options.counters.get('toc', true)
    e && e[:container]
end

#deplate_initialize_guesslanguageObject



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/deplate/mod/guesslanguage.rb', line 12

def deplate_initialize_guesslanguage
    @options.guesslanguage = Guesslanguage.new
    @options.guesslanguage_once = false
    @options.guesslanguage_collected = {}
    for dir in Deplate::Core.library_directories(@vanilla, true, ['locale'])
        for file in Dir[File.join(dir, '*_data')]
            lang = File.basename(file, '.*')
            text = File.read(file)
            @options.guesslanguage.register(lang, text)
            log(['Guesslanguage', lang, file])
        end
    end
end

#deplate_initialize_makefileObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/deplate/mod/makefile.rb', line 16

def deplate_initialize_makefile
    options      = @@command_line_args
    for f in @options.files.reverse
        if options.last == f
            options.pop
        else
            log(['Internal error', 'Makefile', @@command_line_args], :error)
            options = []
            break
        end
    end
    unless options.empty?
        options.each_with_index do |e,i|
            if e == 'makefile'
                o = options[i - 1]
                if o == '-m' or o == '--module'
                    options.slice!(i-1 .. i)
                    break
                end
            end
        end
    end

    base, *files = @options.files
    base0        = File.basename(base, '.*')
    suffix       = clean_makefile_name(File.extname(base))

    if @variables['genericViewer']
        genericViewer = @variables['genericViewer']
    elsif ENV['genericViewer']
        genericViewer = ENV['genericViewer']
    elsif ENV['GNOME_DESKTOP_SESSION_ID']
        genericViewer = 'gnome-open'
    elsif ENV['KDEDIR']
        genericViewer = 'kfmclient'
    elsif ENV['CYGWIN'] || ENV['CYGWIN_PATH'] || ENV['CYGWIN_HOME']
        genericViewer = 'cygstart'
    else
        genericViewer = 'echo Not supported: genericViewer '
    end

    makefile = <<MAKEFILE
include Makefile.config

all: dbk html pdf tex text man

dvi: ${BASE}.dvi
dbk: ${BASE}.dbk
html: ${BASE}.html
xhtml: ${BASE}.xhtml
pdf:
	make DFLAGS="${DFLAGS} ${OFLAGS} --pdf" "${BASE}.pdf"
php: ${BASE}.php
sweave: ${BASE}.Rnw
tex: ${BASE}.tex
text: ${BASE}.text
man: ${BASE}.1

pdfclean: pdf cleantex
dviclean: dvi cleantex

makefile:
	${DEPLATE} -m makefile ${DFLAGS} ${OFLAGS} ${BASE}#{suffix} ${OTHER}

website:
	make prepare_website
	${DEPLATE} ${DFLAGS} ${OFLAGS} ${WEBSITE_DFLAGS} ${FILE} ${OTHER}
	echo ${WEBSITE_DIR}/${BASE}.html > .last_output

%.html: %#{suffix}
	make prepare_html
	${DEPLATE} ${DFLAGS} ${OFLAGS} ${HTML_DFLAGS} $< ${OTHER}
	echo ${HTML_DIR}/$@ > .last_output

%.xhtml: %#{suffix}
	make prepare_xhtml
	${DEPLATE} ${DFLAGS} ${OFLAGS} ${XHTML_DFLAGS} $< ${OTHER}
	echo ${XHTML_DIR}/$@ > .last_output

%.Rnw: %#{suffix}
	make prepare_sweave
	${DEPLATE} ${DFLAGS} ${OFLAGS} ${SWEAVE_DFLAGS} $< ${OTHER}
	echo ${TEX_DIR}/$@ > .last_output

%.text: %#{suffix}
	make prepare_text
	${DEPLATE} ${DFLAGS} ${OFLAGS} ${TEXT_DFLAGS} $< ${OTHER}
	echo ${TEXT_DIR}/$@ > .last_output

%.php: %#{suffix}
	make prepare_php
	${DEPLATE} ${DFLAGS} ${OFLAGS} ${PHP_DFLAGS} $< ${OTHER}
	echo ${PHP_DIR}/$@ > .last_output

%.dbk: %#{suffix}
	make prepare_dbk
	${DEPLATE} ${DFLAGS} ${OFLAGS} ${DBK_DFLAGS} $< ${OTHER}
	echo ${DBK_DIR}/$@ > .last_output

%.tex: %#{suffix}
	make prepare_tex
	${DEPLATE} ${DFLAGS} ${OFLAGS} ${TEX_DFLAGS} $< ${OTHER}
	echo ${TEX_DIR}/$@ > .last_output

%.ref: %#{suffix}
	make prepare_ref
	${DEPLATE} ${DFLAGS} ${OFLAGS} ${REF_DFLAGS} -o $@ $< ${OTHER}
	echo ${REF_DIR}/$@ > .last_output

%.dvi: %.tex
	make prepare_dvi
	cd ${TEX_DIR}; \\
	latex ${LATEX_FLAGS} $<; \\
	bibtex ${BIBTEX_FLAGS} $*; \\
	latex ${LATEX_FLAGS} $<; \\
	latex ${LATEX_FLAGS} $<;
	echo ${TEX_DIR}/$@ > .last_output

# %.pdf: %.Rnw
sweavepdf:
	make DFLAGS="${DFLAGS} --pdf" sweave
	cd ${TEX_DIR}; \\
	R CMD Sweave ${BASE}.Rnw; \\
	$(call postprocess_sweave, ${BASE}.tex)
	make prepare_pdf
	cd ${TEX_DIR}; \\
	pdflatex ${PDFLATEX_FLAGS} ${BASE}.tex; \\
	bibtex ${BIBTEX_FLAGS} ${BASE}; \\
	pdflatex ${PDFLATEX_FLAGS} ${BASE}.tex; \\
	pdflatex ${PDFLATEX_FLAGS} ${BASE}.tex
	echo ${TEX_DIR}/${BASE}.pdf > .last_output

%.pdf: %.tex
	make prepare_pdf
	cd ${TEX_DIR}; \\
	pdflatex ${PDFLATEX_FLAGS} $<; \\
	bibtex ${BIBTEX_FLAGS} $*; \\
	pdflatex ${PDFLATEX_FLAGS} $<; \\
	pdflatex ${PDFLATEX_FLAGS} $<
	echo ${TEX_DIR}/$@ > .last_output

%.1: %.ref
	cd ${REF_DIR}; \\
	xmlto man $<
	echo ${REF_DIR}/$@ > .last_output

view: show
show:
	#{genericViewer} `cat .last_output`

cleantex:
	cd ${TEX_DIR}; \\
	rm -f *.toc *.aux *.log *.cp *.fn *.tp *.vr *.pg *.ky \\
	*.blg *.bbl *.out *.lot *.ind *.4tc *.4ct \\
	*.ilg *.idx *.idv *.lg *.xref || echo Nothing to be done!

MAKEFILE

    log('Writing Makefile', :anyway)
    File.open(Deplate::Core.file_join(@options.dir, 'Makefile'), 'w') do |io|
        io.puts makefile
    end
    if File.exist?('Makefile.config')
        log('Makefile.config already exists', :anyway)
    else
        log('Writing Makefile.config', :anyway)
        fname = find_in_lib('Makefile.config', :pwd => true)
        if fname
            log(['Makefile.config', fname])
            cfg  = File.open(fname) {|io| io.read}
            tmpl = Deplate::Template.new(:template  => cfg)
            args = {
                'base0'   => clean_makefile_name(base0, 2),
                'base'    => clean_makefile_name(base, 2),
                'files'   => files ? clean_makefile_name(files.join(' '), 2) : nil,
                'options' => clean_makefile_name(options.join(' '), 2),
            }
            config = nil
            Deplate::Define.let_variables(self, args) do
                config = tmpl.fill_in(self)
            end
            File.open(Deplate::Core.file_join(@options.dir, 'Makefile.config'), 'w') do |io|
                io.puts config
            end
        else
            log(['File not found', 'Makefile.config'], :error)
        end
    end
    exit 0
end

#dump_metadata(data) ⇒ Object

A dummy method to be overwritten by a metadata module.



2913
2914
2915
# File 'lib/deplate/core.rb', line 2913

def (data)
    data
end

#each_heading(depth = nil, &block) ⇒ Object

Evaluate block (args: heading, caption) with each heading.



3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
# File 'lib/deplate/core.rb', line 3085

def each_heading(depth=nil, &block)
    case depth
    when :top
        arr   = @output_headings
        depth = false
    else
        arr = @options.listings.get('toc')
    end
    for section in arr
        if !depth or (section and section.level <= depth)
            unless section and section.args["noList"]
                if section.kind_of?(Deplate::NullTop)
                    v = section.caption.elt
                else
                    v = section.description
                    v = v.gsub(/<\/?[^>]*>/, "")
                    v = [section.level_as_string, v].join(" ")  unless section.plain_caption?
                end
                block.call(section, v)
            end
        end
    end
end

#elt_label(prefix, text, plain = false) ⇒ Object

Return the canonic name for an automatically generated label (e.g., figures, tables …)



2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
# File 'lib/deplate/core.rb', line 2635

def elt_label(prefix, text, plain=false)
    if text
        if plain
            return "%s00%s" % [prefix, text.sum]
        else
            return "%s00%s" % [prefix, text.gsub(/\W/, "00")]
        end
    else
        # raise msg("No label")
        log(["No label", prefix], :error)
        return nil
    end
end

#endmessage(id, message) ⇒ Object

Register a new message to be displayed after processing the current document.



1958
1959
1960
# File 'lib/deplate/core.rb', line 1958

def endmessage(id, message)
    @endmessages[id] = message
end

#ensure_dir_exists(dir) ⇒ Object

Make sure dir exists (create it if it doesn’t).



2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
# File 'lib/deplate/core.rb', line 2751

def ensure_dir_exists(dir)
    Deplate::Core.ensure_dir_exists(dir, @options)
    # unless File.exist?(dir)
    #     if @options.force
    #         Deplate::Core.ensure_dir_exists(dir, @options)
    #     else
    #         log(["Destination directory doesn't exist", dir, Dir.pwd], :error)
    #         exit 5
    #     end
    # end
end

#eval_ruby(invoker, args, code) ⇒ Object

Caller requests calling ruby code with some args



2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
# File 'lib/deplate/core.rb', line 2463

def eval_ruby(invoker, args, code)
    ar = allow_ruby
    case ar
    when true
        begin
            # +++ Run this in a thread and set $SAFE for this thread only
            context = (args['context'] || '').downcase
            case context
            when 'ruby'
                return eval(code)
            when 'deplate'
                return self.instance_eval(code)
            when 'self', 'this'
                return invoker.instance_eval(code)
            else
                return Deplate::Void.module_eval(code)
            end
        rescue Exception => e
            src = invoker ? invoker.source : nil
            invoker.log(["Error in ruby code", code, e], :error)
        end
    when 1,2,3,4,5
        result, error = Deplate::Safe.safe(ar, code)
        if error then
            invoker.log(["Error in ruby code", code, error.inspect], :error)
        else
            return result.to_s
        end
    else
        if args['alt']
            return args['alt']
        elsif caller
            invoker.log(["Disabled ruby command", code], :anyway)
        end
    end
end

#file_included?(file, dir = nil, try_suffix = nil) ⇒ Boolean

Return whether file was already included.

Returns:

  • (Boolean)


2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
# File 'lib/deplate/core.rb', line 2536

def file_included?(file, dir=nil, try_suffix=nil)
    dir  = dir || "."
    file = File.expand_path(file, dir)
    rv   = @allsources.keys.include?(file)
    if !rv and try_suffix
        file = File.expand_path(file + try_suffix, dir)
        rv   = @allsources.keys.include?(file)
    end
    return rv
end

#file_label(filename_abs) ⇒ Object

Return the automatically generated label for an included file.



2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
# File 'lib/deplate/core.rb', line 2568

def file_label(filename_abs)
    if filename_abs
        label = @allsources[filename_abs]
        unless label
            # rel   = relative_path(filename_abs, Dir.pwd)
            label = "file%03d" % @allsources.size
            label.gsub!(/\W/, "00")
            @allsources[filename_abs] = label
        end
        return label
    else
        return nil
    end
end

#file_name_by_level(level_as_string) ⇒ Object

Return the output file according to level_as_string.



2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
# File 'lib/deplate/core.rb', line 2601

def file_name_by_level(level_as_string)
    if @options.multi_file_output and level_as_string
        if level_as_string.kind_of?(String)
            las = level_as_string
        else
            las = level_as_string.to_s
        end
        case las
        when '', '0'
            top = top_heading_by_idx(0)
        else
            top = nil
            catch(:ok) do
                each_heading do |heading, title|
                    if heading.level_as_string == las
                        top = heading.top_heading
                        throw :ok
                    end
                end
                # raise "Internal error: unknown level: #{level_as_string}"
                log(['Internal error: Unknown level', level_as_string], :error)
                return nil
            end
        end
        return top.destination
    elsif level_as_string == "0"
        return File.basename(@dest)
    else
        return ""
    end
end

#file_with_suffix(file, sfx = nil, filename_only = false) ⇒ Object

Amend file‘s suffix.



2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
# File 'lib/deplate/core.rb', line 2584

def file_with_suffix(file, sfx=nil, filename_only=false)
    sfx  = sfx || ''
    fn   = File.basename(file, '.*')
    if filename_only
        return fn + sfx
    else
        dir   = File.dirname(file)
        fname = fn + sfx
        if dir == '.'
            return fname
        else
            return File.join(dir, fname)
        end
    end
end

#find_in_lib(fname, args = {}) ⇒ Object



2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
# File 'lib/deplate/core.rb', line 2136

def find_in_lib(fname, args={})
    if args[:pwd]
        fn = File.join(Deplate::Core.current_pwd(self), fname)
        if Deplate::Core.is_file?(fn)
            log(['File in CWD', fn])
            return fn
        end
    end
    files = []
    if @formatter
        @formatter.class.formatter_family_members(:names => args[:formatters]) do |myname|
            dd = File.join('lib', myname, fname)
            files << dd unless files.include?(dd)
        end
    end
    files << File.join(args['subdir'] || 'lib', fname)
    files = Deplate::Core.library_directories(@vanilla, true, files)
    for fn in files
        if Deplate::Core.is_file?(fn)
            log(['File in lib', fn])
            return fn
        end
    end
    return nil
end

#format_file_with_formatter(formatter_class, sourcename) ⇒ Object

Format a file by means of formatter_class that is a child of Deplate::Formatter



2178
2179
2180
2181
2182
# File 'lib/deplate/core.rb', line 2178

def format_file_with_formatter(formatter_class, sourcename)
    with_formatter(formatter_class, sourcename) do
        go_each([sourcename])
    end
end

#format_particles(particles) ⇒ Object

Return an array of unprocessed particles as string.



3066
3067
3068
# File 'lib/deplate/core.rb', line 3066

def format_particles(particles)
    return join_particles(particles.collect{|e| e.process; e.elt})
end

#format_string(text, sourcename = nil) ⇒ Object

Format text with the current formatter



2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
# File 'lib/deplate/core.rb', line 2192

def format_string(text, sourcename=nil)
    reset_output(false)
    maintain_current_source(sourcename) do
        accum_elements  = @accum_elements
        @accum_elements = Array.new
        include_each(text, @accum_elements, sourcename)
        process_document
        return body_string
    end
end

#format_string_with_formatter(formatter_class, text, sourcename = nil) ⇒ Object

Format text by means of formatter_class that is a child of Deplate::Formatter



2185
2186
2187
2188
2189
# File 'lib/deplate/core.rb', line 2185

def format_string_with_formatter(formatter_class, text, sourcename=nil)
    with_formatter(formatter_class, sourcename) do
        format_string(text, sourcename)
    end
end

#format_with_formatter(formatter_class, text, sourcename = nil) ⇒ Object

Format either text or, if text is nil, the file “sourcename”.

This is the method called by the Deplate::Formatter’s to_whatsoever methods.



2169
2170
2171
2172
2173
2174
2175
# File 'lib/deplate/core.rb', line 2169

def format_with_formatter(formatter_class, text, sourcename=nil)
    if text
        format_string_with_formatter(formatter_class, text, sourcename)
    elsif sourcename
        format_file_with_formatter(formatter_class, sourcename)
    end
end

#get_clip(id) ⇒ Object

Get a clip.

id

The clip’s name

FIXME: This check for @elt should not be necessary.



2511
2512
2513
2514
2515
2516
2517
# File 'lib/deplate/core.rb', line 2511

def get_clip(id)
    c = @clips[id]
    if c and !c.elt
        c = @clips[id] = c.process
    end
    c
end

#get_current_headingObject

Get the current section’s level as string.



2838
2839
2840
# File 'lib/deplate/core.rb', line 2838

def get_current_heading
    @options.counters.get_s('toc')
end

#get_current_topObject

Get the current top heading object.



2848
2849
2850
# File 'lib/deplate/core.rb', line 2848

def get_current_top
    top_heading_by_idx(top_heading_idx)
end

#get_dir_listing(dir) ⇒ Object

Get a directory listing while respecting the -p and -P command line options



2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
# File 'lib/deplate/core.rb', line 2113

def get_dir_listing(dir)
    pwd = Dir.pwd
    begin
        Dir.chdir(dir)
        files = Dir['*']
        match = Dir[@options.file_pattern || '*']
        files.delete_if {|f| File.stat(f).file? and !match.include?(f)}
        if @options.file_excl_pattern
            antilist = Dir[@options.file_excl_pattern]
            for anti in antilist
                files.delete(anti)
            end
        end
        log(['DIR', dir])
    ensure
        Dir.chdir(pwd)
    end
    unless dir == '.'
        files.collect! {|f| File.join(dir, f)}
    end
    return files
end

#get_filename_for_label(invoker, label) ⇒ Object

Get the filename of the object marked with label.



2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
# File 'lib/deplate/core.rb', line 2896

def get_filename_for_label(invoker, label)
    f = @label_aliases[label]
    if f
        f = f.top_heading.destination
        d = invoker.top_heading.destination
        if f == d
            return ''
        else
            return relative_path(f, File.dirname(d))
        end
    else
        # puts caller
        invoker.log(['Reference to unknown label', label], :error)
    end
end

#get_formatter_class(fmt) ⇒ Object



1779
1780
1781
1782
1783
1784
1785
1786
# File 'lib/deplate/core.rb', line 1779

def get_formatter_class(fmt)
    case fmt
    when String
        @@formatter_classes[fmt]
    else
        fmt
    end
end

#get_label_by_id(invoker, id) ⇒ Object

<TBD>This doesn’t work as intended. Elements still have to be labelled in order to be referred to by their ID



2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
# File 'lib/deplate/core.rb', line 2879

def get_label_by_id(invoker, id)
    o = @ids[id]
    if o
        l = o.label
        l &&= l.first
        if l
            return l
        else
            return id
            # invoker.log(["Object has no label", id], :error)
        end
    else
        invoker.log(['No object with that ID', id], :error)
    end
end

#get_metadata(source, metadata) ⇒ Object

Return the metadata as hash.



2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
# File 'lib/deplate/core.rb', line 2931

def (source, )
    if @options.
        if source
            ['source_file']  = source.file
            ['source_begin'] = source.begin
            ['source_end']   = source.end
            if (stats = source.stats)
                if (mtime = stats.mtime)
                    ['source_mtime'] = mtime
                end
            end
        end
        
    else
        nil
    end
end

#get_numbering_mode(entity, default = 1) ⇒ Object



2852
2853
2854
# File 'lib/deplate/core.rb', line 2852

def get_numbering_mode(entity, default=1)
    (@variables["#{entity}Numbering"] || default).to_i
end

#get_unprocessed_clipsObject

Get a hash on yet unprocessed clips. Obsolete?



2526
2527
2528
# File 'lib/deplate/core.rb', line 2526

def get_unprocessed_clips
    @clips
end

#go(writeFile = true) ⇒ Object

Read input file, process, write the output if writeFile is true.



2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
# File 'lib/deplate/core.rb', line 2022

def go(writeFile=true)
    process_prelude
    read_file
    process_document
    if writeFile
        body_write
        copy_resources
    end
    print_endmessages
end

#go_each(sources = @sources) ⇒ Object

Process each in sources.



1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
# File 'lib/deplate/core.rb', line 1992

def go_each(sources=@sources)
    rv = nil
    begin
        saved_sources = @sources
        for f in sources
            if File.stat(f).file?
                if to_be_included?(f)
                    @sources = [f]
                    @dest    = Deplate::Core.get_out_fullname(f, @options.suffix, @options)
                    reset(true)
                    reset_output(false)
                    if block_given?
                        yield
                    else
                        rv = go
                    end
                end
            elsif @options.recurse
                go_each(get_dir_listing(f))
            else
                log(["Is no file", f], :error)
            end
        end
    ensure
        @sources = saved_sources
    end
    rv
end

#go_nowObject

Do something at last.



1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
# File 'lib/deplate/core.rb', line 1976

def go_now
    if @options.each
        go_each
    elsif @options.loop
        loop do
            go
            reset(true)
            reset_output(false)
        end
    else
        @sources.uniq!
        go
    end
end

#guesslanguage(text) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/deplate/mod/guesslanguage.rb', line 26

def guesslanguage(text)
    if @variables['lang']
        log(['Guesslanguage', 'Variable already set', 'lang'])
        @options.guesslanguage_once = true
        return
    end
    unless text.empty? or @formatter.kind_of?(Deplate::Formatter::Template)
        text0 = text.gsub(/^\s*#.*$|^\s*%.*$|\{.*?\}/, '')
        if text0 =~ /\w/
            diff, lang = @options.guesslanguage.guess_with_diff(text0)
            if lang
                lang0 = @options.guesslanguage_collected[:best]
                diff0 = lang0 ? @options.guesslanguage_collected[lang0] : nil
                if !diff0 or diff < diff0
                    log(['Guesslanguage: Switch to', lang])
                    if lang0 and lang0 != lang
                        log(['Guesslanguage: Possible conflict', lang, '%1.2f' % diff, lang0, '%1.2f' % diff0], :anyway)
                    end
                    @options.guesslanguage_collected[:best] = lang
                    @options.guesslanguage_collected[lang] = diff
                    @options.guesslanguage_once = true
                    set_lang(lang)
                else
                    if lang != lang0
                        log(['Guesslanguage: Ignore switch', lang, '%1.2f' % diff, lang0, '%1.2f' % diff0])
                        log(text, :debug)
                        # p "DBG", text, text0
                    end
                end
            end
        end
    end
end

#guesslanguage_include_eachObject

Include each line in enum and accumulate parsed elements in array



60
61
62
63
64
65
66
# File 'lib/deplate/mod/guesslanguage.rb', line 60

def include_each(enum, array, sourcename=nil)
    case enum
    when Array
        enum = enum.join("\n")
    end
    @input.include_string(enum, array, 0)
end

#home_indexObject



3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
# File 'lib/deplate/core.rb', line 3114

def home_index
    hidx = @variables['homeIndex']
    if hidx
        return hidx
    else
        @collected_output.each_with_index do |o, i|
            unless o.body_empty?
                return i
            end
        end
        return 0
    end
end

#hook_late_require_linkmapObject



124
125
126
127
# File 'lib/deplate/mod/linkmap.rb', line 124

def hook_late_require_linkmap
    register_particle(Deplate::HyperLink::ExtendedLinkMap, :replace => Deplate::HyperLink::Extended)
    register_region(Deplate::Regions::LinkMap)
end

#hook_late_require_zh_cnObject



66
67
68
69
# File 'lib/deplate/mod/lang-zh_CN-autospace.rb', line 66

def hook_late_require_zh_cn
    module_initialize_zh_cn_autospace
    call_methods_matching(@formatter, /^hook_pre_setup_zh_cn/)
end

#hook_post_input_initialize_zh_cn_particlesObject



48
49
50
51
# File 'lib/deplate/mod/lang-zh_CN.rb', line 48

def hook_post_input_initialize_zh_cn_particles
    register_particle(Deplate::Particle::Space)
    register_particle(Deplate::Particle::SwallowedSpace)
end

#hook_pre_setup_zh_cn_particlesObject



61
62
63
64
# File 'lib/deplate/mod/lang-zh_CN-autospace.rb', line 61

def hook_pre_setup_zh_cn_particles
    register_particle(Deplate::Particle::Space)
    register_particle(Deplate::Particle::NonCJK)
end

#in_working_dir(cwd = nil, &block) ⇒ Object

Evaluate block in the working directory; take care of the auxiliaryDirSuffix variable



2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
# File 'lib/deplate/core.rb', line 2048

def in_working_dir(cwd=nil, &block)
    pwd = Dir.pwd
    cwd = auxiliary_dirname(true, true) if cwd.nil?
    if cwd.empty? or cwd == false or pwd == cwd
        block.call
    else
        log(['CHDIR ->', cwd], :debug)
        Dir.chdir(cwd)
        begin
            block.call
        ensure
            log(['CHDIR <-', pwd], :debug)
            Dir.chdir(pwd)
        end
    end
end

#include_each(enum, array, sourcename = nil) ⇒ Object

Include each line in enum and accumulate parsed elements in array



2257
2258
2259
2260
2261
2262
2263
# File 'lib/deplate/core.rb', line 2257

def include_each(enum, array, sourcename=nil)
    case enum
    when Array
        enum = enum.join("\n")
    end
    @input.include_string(enum, array, 0)
end

#include_file(array, filename, args = {}) ⇒ Object

Read a file and add the parsed elements to array



2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
# File 'lib/deplate/core.rb', line 2228

def include_file(array, filename, args={})
    maintain_current_source(filename) do
        log(['Including', filename])
        filename_abs    = File.expand_path(filename)
        unless @options.included
            filename_label  = file_label(filename_abs)
            @labels_floating << filename_label
        end
        File.open(filename, 'r') do |io|
            range = if (skip = args['skip'])
                        skip.to_i..-1
                    elsif (head = args['head'])
                        0..head.to_i
                    elsif (tail = args['tail'])
                        -tail.to_i..-1
                    else
                        nil
                    end
            if range
                text = io.readlines[range].join
            else
                text = io.read
            end
            include_each(text, array, filename)
        end
    end
end

#include_stdin(array) ⇒ Object

Read text from STDIN. End on EOF or due to a matching pair of #BEGIN, #END pseudo commands



2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
# File 'lib/deplate/core.rb', line 2205

def include_stdin(array)
    if $stdin.eof?
        log('No more input on STDIN', :anyway)
        exit 1
    end
    maintain_current_source('') do
        log('Including from STDIN')
        acc = []
        end_tag = nil
        $stdin.each_with_index do |l, i|
            if i == 0 and l =~ /^#BEGIN:/
                end_tag = '#END:' + l[7..-1]
            elsif end_tag and l == end_tag
                break
            else
                acc << l
            end
        end
        include_each(acc, array, 'STDIN')
    end
end

#include_stringarray(strings, array, linenumber = nil, src = '[array]') ⇒ Object

Include strings as if read from a file and push parsed elements onto array



2278
2279
2280
2281
2282
# File 'lib/deplate/core.rb', line 2278

def include_stringarray(strings, array, linenumber=nil, src='[array]')
    maintain_current_source(src) do
        include_each(strings, array, linenumber || 0)
    end
end

#increase_current_heading(container, level) ⇒ Object

Increase the heading level.



2843
2844
2845
# File 'lib/deplate/core.rb', line 2843

def increase_current_heading(container, level)
    @options.counters.increase('toc', :container => container, :level => level)
end

#initialize_input(args = @args) ⇒ Object

(Re-)set @input

args

A hash as passed to #initialize



1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
# File 'lib/deplate/core.rb', line 1730

def initialize_input(args=@args)
    @input = args[:input] || @options.input
    unless @input
        # @options.input_class is only considered when defined on 
        # startup (i.e. on the command-line), which is why we check 
        # for :now
        input_class = args[:input_class] ||
            (args[:now] && @options.input_class) ||
            Deplate::Input
        @input = input_class.new(self, args)
    end
end

#input_initialize_playObject



202
203
204
205
206
207
# File 'lib/deplate/input/play.rb', line 202

def input_initialize_play
    # unless @variables['inputFormat']
        @options.input_class = Deplate::Input::Play
    #     @variables['inputFormat'] = @options.input_class.myname
    # end
end

#is_allowed?(ids, args = {}) ⇒ Boolean

Returns:

  • (Boolean)


2446
2447
2448
2449
2450
# File 'lib/deplate/core.rb', line 2446

def is_allowed?(ids, args={})
    args = args.dup
    args[:logger] ||= self
    Deplate::Core.is_allowed?(@options, ids, args)
end

#join_particles(particles) ⇒ Object

Join an array of particles into a string.



3061
3062
3063
# File 'lib/deplate/core.rb', line 3061

def join_particles(particles)
    particles.join
end

#log(*args) ⇒ Object

See Deplate::Core.log



1952
1953
1954
# File 'lib/deplate/core.rb', line 1952

def log(*args)
    self.class.log(*args)
end

#matching_methods(obj, rx) ⇒ Object



1846
1847
1848
# File 'lib/deplate/core.rb', line 1846

def matching_methods(obj, rx)
    obj.methods.find_all {|m| m =~ rx }
end

#module_initialize_anywordObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/deplate/mod/anyword.rb', line 11

def module_initialize_anyword
    list = @variables["anyword_list"]
    acc  = list ? Deplate::Core.split_list(list, ',', ';') : []

    cat  = @variables["anyword_catalog"]
    if cat
        acc += File.open(cat) do |io|
            io.readlines.collect {|l| l.chomp}
        end
    end

    suffix  = @variables["anyword_suffix"] || ""

    pattern = @variables["anyword_pattern"]
    if pattern
        acc += Dir[pattern].collect {|f| File.basename(f, suffix)}
    end

    unless list or cat or pattern
        files = @options.files.collect do |src|
            Dir[File.join(File.dirname(src), "*" + suffix)]
        end
        acc += files.flatten.collect {|f| File.basename(f, suffix)}
    end
    
    rx  = acc.collect {|n| "(?i:\\b%s\\b)" % Regexp.escape(n)}.join("|")
    body = <<-EOR
        set_rx(/^#{rx}/)
        def setup_element
            @inter   = nil
            @literal = nil
            @anchor  = ""
            @dest    = @match[0]
            @name    = @dest
            idx      = [@deplate.add_index(self, @name)]
            @idx     = indexing(idx)
        end
        def process
            @name = @deplate.formatter.plain_text(Deplate::Core.remove_backslashes(@name))
            @elt = [@name, @dest, @anchor]
            super
        end
    EOR
    cls = Deplate::Cache.particle(deplate, body, :register => true)
end

#module_initialize_entities_encodeObject



11
12
13
# File 'lib/deplate/mod/entities-encode.rb', line 11

def module_initialize_entities_encode
    @formatter.setup_entities
end

#module_initialize_noindentObject



29
30
31
# File 'lib/deplate/mod/noindent.rb', line 29

def module_initialize_noindent
    Deplate::NoIndent.setup(@formatter)
end

#module_initialize_utf8Object



46
47
48
# File 'lib/deplate/mod/utf8.rb', line 46

def module_initialize_utf8
    @variables['encoding'] = 'UTF-8'
end

#module_initialize_zh_cn_autospaceObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/deplate/mod/lang-zh_CN-autospace.rb', line 35

def module_initialize_zh_cn_autospace
    class << self
        def join_particles(particles)
            acc  = []
            prev = ''
            prev_cjk = false
            particles.delete('')
            particles.each_with_index do |e, i|
                if e == ' '
                    enext = particles[i + 1]
                    if prev == ' ' or enext == ' '
                    elsif @formatter.cjk_smart_blanks and prev =~ Deplate::Core.cjk_rx_C and enext =~ Deplate::Core.cjk_rx_C
                        acc << @formatter.cjk_nospace
                    else
                        acc << @formatter.cjk_space
                    end
                else
                    acc << e
                    prev = e
                end
            end
            return acc.join
        end
    end
end

#msg(text) ⇒ Object

Return a localized version of text. (delegated)



3046
3047
3048
# File 'lib/deplate/core.rb', line 3046

def msg(text)
    @options.messages.msg(text)
end

#new_output(inherited_output = nil, args = {}) ⇒ Object

Create a new output and push it to @collected_output.



2650
2651
2652
2653
2654
2655
2656
2657
# File 'lib/deplate/core.rb', line 2650

def new_output(inherited_output=nil, args={})
    @output = Deplate::Output.new(self, inherited_output)
    @collected_output << @output
    @output.top_heading = top_heading_by_idx(@collected_output.size - 1)
    @output.index       = @output_maj_min.dup
    @output.reset
    increase_maj_min
end

#number_of_outputsObject

Return the number of output pages.



2404
2405
2406
# File 'lib/deplate/core.rb', line 2404

def number_of_outputs
    @output_headings.size
end

#object_by_id(id) ⇒ Object



3128
3129
3130
3131
3132
3133
3134
3135
# File 'lib/deplate/core.rb', line 3128

def object_by_id(id)
    o = @ids[id]
    if o
        return o
    else
        log(['Unknown ID', id], :error)
    end
end

#output_filename_by_idx(idx) ⇒ Object

Return the nth output filename.

idx

Top heading index (integer)



2419
2420
2421
2422
2423
2424
# File 'lib/deplate/core.rb', line 2419

def output_filename_by_idx(idx)
    if idx
        idx = idx.to_i if idx.kind_of?(String)
        @output_filename[idx]
    end
end

#output_index(top = nil) ⇒ Object

Return the index for a top heading.



2409
2410
2411
2412
2413
2414
2415
# File 'lib/deplate/core.rb', line 2409

def output_index(top=nil)
    if top
        top_heading_idx(top)
    else
        @collected_output.size - 1
    end
end

#parse_and_format(container, text, alt = true, args = {}) ⇒ Object

Parse text and return a formatted string.



3071
3072
3073
3074
# File 'lib/deplate/core.rb', line 3071

def parse_and_format(container, text, alt=true, args={})
    t = parse(container, text, alt, args)
    return format_particles(t)
end

#parse_and_format_without_wikinames(container, text, alt = true) ⇒ Object



3076
3077
3078
3079
3080
3081
3082
# File 'lib/deplate/core.rb', line 3076

def parse_and_format_without_wikinames(container, text, alt=true)
    excluded = [
        Deplate::HyperLink::Simple,
        Deplate::HyperLink::Extended,
    ]
    return parse_and_format(container, text, alt, :excluded => excluded)
end

#parsed_array_from_strings(strings, linenumber = nil, src = '[array]') ⇒ Object

Include strings as if read from a file and return the resulting array of parsed elements



2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
# File 'lib/deplate/core.rb', line 2266

def parsed_array_from_strings(strings, linenumber=nil, src='[array]')
    array = []
    erx   = @variables['embeddedTextRx']
    begin
        include_stringarray(strings, array, linenumber, src)
    ensure
        @variables['embeddedTextRx'] = erx if erx
    end
    return array
end

#pop_input_format(name = nil) ⇒ Object

Restore the previously used input format. If a name is given and the name matches the previous input format, do nothing.

name

The name of an input format.



1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
# File 'lib/deplate/core.rb', line 1767

def pop_input_format(name=nil)
    if @input_formats.empty?
        return false
    else
        if name and @input_formats.last.class.myname == name
            return false
        end
        @input = @input_formats.pop
        return true
    end
end

Print messages after having printed the current document.



1963
1964
1965
1966
1967
1968
# File 'lib/deplate/core.rb', line 1963

def print_endmessages
    @endmessages.each do |id, message|
        log([message], :anyway)
    end
    @endmessages = {}
end

#printable_strings(strings, linenumber = nil, src = "[array]") ⇒ Object

accum format elts in pre/body|matter/post



2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
# File 'lib/deplate/core.rb', line 2427

def printable_strings(strings, linenumber=nil, src="[array]")
    @formatter.pre_process
    output = []
    accum_elements = []
    include_stringarray(strings, accum_elements, linenumber, src)
    accum_elements.collect! do |e|
        e.doc_type = :array
        e.doc_slot = output
        e.process
    end
    accum_elements.compact!
    for e in accum_elements
        e.doc_type = :array
        e.doc_slot = output
        e.print
    end
    return output
end

#push_input_format(name) ⇒ Object

Change the input format to name.

name

The name of an input format.



1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
# File 'lib/deplate/core.rb', line 1745

def push_input_format(name)
    unless name
        return false
    end
    ic = @@input_classes[name]
    unless ic
        self.class.require_input(@options, name)
        ic = @@input_classes[name]
    end
    if ic
        @input_formats << @input
        @input = ic.new(self, @args)
        return true
    else
        log(['Unknown input format', name, @@input_classes.keys], :error)
        return false
    end
end

#push_metadata(data, array = @metadata) ⇒ Object

Actually save the metadata in some variable for later use.



2959
2960
2961
2962
2963
2964
2965
# File 'lib/deplate/core.rb', line 2959

def (data, array=@metadata)
    if @options.
        type = data["type"]
        @metadata[type] ||= []
        @metadata[type] << data
    end
end

#put_metadata(io, metadata) ⇒ Object

A dummy method to be overwritten by a metadata module.



2918
2919
2920
# File 'lib/deplate/core.rb', line 2918

def (io, )
    io.puts()
end

#register_id(hash, obj) ⇒ Object

Register an object’s ID. <TBD>Not systematically used yet.



2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
# File 'lib/deplate/core.rb', line 2969

def register_id(hash, obj)
    id  = hash["id"]
    xid = hash["xid"]
    if id and xid
        log(["Option clash: both id and xid provided", id, xid], :error, obj.source)
    else
        id ||= xid
    end
    if id and !id.empty?
        if @ids[id]
            # obj.log(["ID with the same name already exists", id, @ids[id].level_as_string], :error)
        else
            obj.log(["Register ID", id, obj.class], :debug)
            @ids[id] = obj
        end
    end
end

#register_metadata(source, metadata) ⇒ Object

Register a new metadata entry.

source

The related source filename

metadata

A hash



2952
2953
2954
2955
2956
# File 'lib/deplate/core.rb', line 2952

def (source, )
    if @options.
        ((source, ))
    end
end

#relative_path(file, dir) ⇒ Object

Make file a filename relative to dir.



2548
2549
2550
2551
2552
2553
# File 'lib/deplate/core.rb', line 2548

def relative_path(file, dir)
    fn1 = Pathname.new(File.expand_path(file))
    fn2 = Pathname.new(File.expand_path(dir))
    rv  = fn1.relative_path_from(fn2).to_s
    return rv == "." ? "" : rv
end

#relative_path_by_file(file, base_file) ⇒ Object



2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
# File 'lib/deplate/core.rb', line 2555

def relative_path_by_file(file, base_file)
    if file
        if base_file
            relative_path(file, File.dirname(base_file))
        else
            File.basename(file)
        end
    else
        ''
    end
end

#remove_index(containes, names) ⇒ Object

Remove a registered index entry.



3036
3037
3038
3039
3040
3041
3042
3043
# File 'lib/deplate/core.rb', line 3036

def remove_index(containes, names)
    lname  = Deplate::Core.remove_backslashes(names.split(/\s*\|\s*/)[0])
    i      = @index[lname]
    if i
        i.pop
        @index.delete(lname) if i.empty?
    end
end

#require_module(m) ⇒ Object

See Deplate::Core.require_module.



1971
1972
1973
# File 'lib/deplate/core.rb', line 1971

def require_module(m)
    Deplate::Core.require_module(@options, m)
end

#reset(all = false) ⇒ Object

Reset instance variables.

all

reset really all variables (bool)



1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
# File 'lib/deplate/core.rb', line 1852

def reset(all=false)
    @current_source   = nil
    @current_source_stats = nil
    @auto_numbered   = {}
   
    @variables = @options.variables.dup
    @variables.deplate = self

    @clips            = {}
    @index            = {}
    @index_last_idx   = 0
    @labels           = {}
    @label_aliases    = {}
    @labels_floating  = []
    @ids              = {}
    @preprocess       = []
    @postponed_print  = []

    @footnotes         = {}
    @footnote_last_idx = 0
    @footnotes_used    = []

    @headings          = {}

    @accum_elements    = []
    @switches          = []
    @metadata          = {}
    
    set_lang(@@messages_last)
    set_standard_clips

    if all
        @endmessages           = {}
        @allsources            = {}
        @input_formats         = []
        @options.citations     = []
        @options.bib           = []
        @options.dont_index    = []
        @options.author        = []
        @options.heading_names = []
        Deplate::Core.reset_listings_and_counters(@options)
    end
end

#reset_output(inherit_null_output = true) ⇒ Object

Reset output-related variables.

inherit_null_output

The new output obj inherits the settings from the

initial/anonymous output class (bool)



1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
# File 'lib/deplate/core.rb', line 1899

def reset_output(inherit_null_output=true)
    log('Reset output', :debug)
    @collected_output = []
    @output_filename  = []
    @output_headings  = []
    @output_maj_min   = [0, 0]
    @null_output      = @output.dup
    if @options.multi_file_output
        dest = @variables['docBasename'] || @dest
        dest &&= File.basename(dest)
        # Deplate::Core.canonic_file_name(dest, @options.suffix, 0, 0)
    else
        dest = nil
    end
    dest    = dest ? Deplate::Core.get_out_fullname(dest, nil, @options) : @dest
    heading = Deplate::NullTop.new(self, :destination => dest)
    @output_filename[0] = dest
    push_top_heading(heading)
    if inherit_null_output
        new_output(@null_output)
    else
        Deplate::Output.reset
        new_output(nil)
    end
end

#set_all_clips(clips) ⇒ Object

Set all clips.

clips

A hash



2521
2522
2523
# File 'lib/deplate/core.rb', line 2521

def set_all_clips(clips)
    @clips = clips
end

#set_clip(id, value) ⇒ Object

Set a clip.

id

The clip’s name

value

An instance of either Deplate::Element::Clip or

Deplate::Regions::Clip.


2504
2505
2506
# File 'lib/deplate/core.rb', line 2504

def set_clip(id, value)
    @clips[id] = value
end

#set_label_object(invoker, label, level_as_string, opts = {}) ⇒ Object



2869
2870
2871
2872
2873
2874
2875
# File 'lib/deplate/core.rb', line 2869

def set_label_object(invoker, label, level_as_string, opts={})
    if @label_aliases[label]
        @label_aliases[label] = opts[:container] || invoker
    else
        # add_label(invoker, label, level_as_string, opts
    end
end

#set_lang(lang) ⇒ Object

Set the localization object.

lang

The new language (string)



1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
# File 'lib/deplate/core.rb', line 1927

def set_lang(lang)
    case lang
    when String
        msg_class = @@messages[lang]
    else
        msg_class = lang
    end
    begin
        if msg_class
            @options.messages  = msg_class.new(self)
            @@message_object ||= @options.messages
        elsif is_allowed?('l') and require_module("lang-#{lang}")
            set_lang(lang)
        else
            log(["Bad language definition", lang, "(#{@@messages.keys.join(', ')})"],
                :error)
        end
    rescue LoadError => e
        log(["Unknown language", lang, "(#{@@messages.keys.join(', ')})",
            'Please consider contributing a message catalog for your language'],
                :error)
    end
end

#set_slot_name(key, val) ⇒ Object

Define a new slot or reset the position of an already known slot. <TBD>There is no information on whether the slot belongs to the prematter/postmatter/body.

key

The name (string)

val

The position (integer)



1793
1794
1795
# File 'lib/deplate/core.rb', line 1793

def set_slot_name(key, val)
    slot_names[key] = val
end

#set_top_heading(heading, text) ⇒ Object

Set the current top heading.

heading

Heading object

text

The output filename base



2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
# File 'lib/deplate/core.rb', line 2317

def set_top_heading(heading, text)
    if heading.level <= @options.split_level
        fname = nil
        sfx   = @options.suffix
        # dir   = @options.dir
        if @output_headings.include?(heading)
            maj = top_heading_idx(heading)
        else
            heading.top_heading = heading
            push_top_heading(heading)
            maj = @output_headings.size - 1
            unless text or !@options.multi_file_output
                afn = @variables['autoFileNames']
                if afn
                    fname = Deplate::Core.clean_filename(heading.get_text)[0..20]
                    c = auto_numbered(fname)
                    if c
                        fname = Deplate::Core.canonic_file_name(fname, sfx, :maj => c, :min => 0, :raw => true)
                        auto_numbered(fname, :inc => 1)
                    else
                        fname = Deplate::Core.canonic_file_name(fname, sfx, :raw => true)
                        auto_numbered(fname, :set => 0)
                    end
                else
                    # if @variables['autoBaseName']
                    #     fname = File.basename(@current_source, '.*')
                    #     fmaj  = if auto_numbered(fname)
                    #                 auto_numbered(fname, :inc => 1)
                    #             else
                    #                 auto_numbered(fname, :set => 0)
                    #             end
                    # else
                    #     fname = File.basename(@dest, '.*')
                    #     fmaj  = maj
                    # end
                    fname = @variables['autoBaseName'] ? @current_source : @dest
                    fname = File.basename(fname, '.*')
                    fmaj  = if auto_numbered(fname)
                                auto_numbered(fname, :inc => 1)
                            # <+TBD+>
                            elsif @accum_elements.size == 1 and 
                                @accum_elements[0].kind_of?(Deplate::Element::PotentialPageBreak)
                                auto_numbered(fname, :set => 0)
                            else
                                auto_numbered(fname, :set => 1)
                            end
                    fname = Deplate::Core.canonic_file_name(fname, sfx, :maj => fmaj, :min => 0, :raw => true)
                end
            end
        end
        if !@options.multi_file_output
            # fname = ""
            fname = @dest
        else
            if text
                fname = Deplate::Core.canonic_file_name(text, sfx)
            end
            if fname
                fname = Deplate::Core.get_out_fullname(fname, nil, @options)
            end
            @output.simulate_reset
        end
        # if fname and @options.multi_file_output
        if fname
            heading.destination = @output_filename[maj] = fname
        end
        log(["Set top heading", maj, (text||"nil"), fname], :debug)
    end
end

#slot_by_name(slot) ⇒ Object

Return a slot position by its name.



1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
# File 'lib/deplate/core.rb', line 1798

def slot_by_name(slot)
    if slot.kind_of?(Numeric)
        slotlist = slot_names.collect {|k,v| v == slot ? k : nil }.compact.join(", ")
        log(["Please refer to slots by their names", slot, slotlist], :error)
        log(caller[0..5].join("\n"), :error)
        slot
    elsif slot.is_a?(Symbol)
        slotstr = slot.to_s
        if slotstr =~ /^prepend_/
            modi = -1
            slot = slotstr[8..-1].to_sym
        else
            modi = 1
        end
        val = slot_names[slot]
        if val
            return val * modi
        else
            return nil
        end
    elsif slot.is_a?(String)
        pos = 0
        operator = "+"
        for i in slot.split(/([+-])/)
            case i
            when "-", "+"
                operator = i
            else
                j = slot_names[i.intern]
                unless j
                    j = i.to_i
                end
                pos = pos.send(operator, j)
            end
        end
        pos
    end
end

#symbolsObject

Class variable accessor.



3051
3052
3053
# File 'lib/deplate/core.rb', line 3051

def symbols
    @@symbols
end

#templatesObject

Class variable accessor.



3056
3057
3058
# File 'lib/deplate/core.rb', line 3056

def templates
    @@templates
end

#to_be_included?(file) ⇒ Boolean

Should the file be included or not, e.g., because of a -P command line option

Returns:

  • (Boolean)


2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
# File 'lib/deplate/core.rb', line 2035

def to_be_included?(file)
    rv = get_dir_listing(File.dirname(file))
    rv = rv.include?(file)
    if rv
        log(["Should be included", file])
    else
        log(["Should be excluded", file])
    end
    return rv
end

#top_heading_by_idx(idx) ⇒ Object

Get a top/page heading by its index.

idx

The index (integer)



2389
2390
2391
# File 'lib/deplate/core.rb', line 2389

def top_heading_by_idx(idx)
    @output_headings[idx || 0]
end

#top_heading_idx(top = nil) ⇒ Object

Get the top/page heading index (or get the current index if no top heading object is provided.



2395
2396
2397
2398
2399
2400
2401
# File 'lib/deplate/core.rb', line 2395

def top_heading_idx(top=nil)
    if top
        @output_headings.index(top)
    else
        @output_headings.size - 1
    end
end

#write_file(file, mode = 'w', &block) ⇒ Object

Actually write something to some file.



2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
# File 'lib/deplate/core.rb', line 2764

def write_file(file, mode='w', &block)
    if file
        # pwd = Dir.pwd
        begin
            case file
            when 1, 2, 3, '-'
                ok = true
                case file
                when String
                    file = mode =~ /r/ ? 1 : 2
                end
            else
                #     Dir.chdir(@options.dir)
                ensure_dir_exists(File.dirname(file))
                ok = if File.exist?(file)
                         Deplate::Core.query_user(@options, 
                                              "File '#{file}' already exists. Overwrite (y/N)? ", 
                                              'y')
                     else
                         true
                     end
            end
            if ok
                log(['Writing file', file], :debug)
                File.open(file, mode) do |io|
                    block.call(io)
                end
            end
            # ensure
            #     Dir.chdir(pwd)
        rescue Exception => e
            log(['Error when writing file', file, e], :error)
            exit 5
        end
    else
        log(['No output file', file], :error)
    end
end

#write_metadata(file, output, metadata = nil) ⇒ Object

A dummy method to be overwritten by a metadata module.



2923
2924
2925
2926
2927
2928
# File 'lib/deplate/core.rb', line 2923

def (file, output, =nil)
    write_file(file) do |io|
        md =  ? output.() : output.
        (io, md)
    end
end