Class: Deplate::Formatter

Inherits:
CommonObject show all
Defined in:
lib/deplate/mod/utf8.rb,
lib/deplate/zh_CN.rb,
lib/deplate/zh_CN.rb,
lib/deplate/formatter.rb,
lib/deplate/mod/iconv.rb,
lib/deplate/mod/recode.rb,
lib/deplate/mod/numpara.rb,
lib/deplate/mod/endnotes.rb,
lib/deplate/mod/pstoedit.rb,
lib/deplate/mod/entities-encode.rb,
lib/deplate/mod/inlatex-compound.rb,
lib/deplate/mod/mark-external-urls.rb,
lib/deplate/mod/lang-zh_CN-autospace.rb,
lib/deplate/mod/html-highstep.rb

Overview

mark-urls.rb @Author: Thomas Link (micathom AT gmail com) @Website: deplate.sf.net/ @License: GPL (see www.gnu.org/licenses/gpl.txt) @Created: 16-Nov-2004. @Revision: 0.41

Description:

Usage:

TODO:

CHANGES:

Defined Under Namespace

Classes: DbkSlides, DbkSnippet, HTML, HTML_Site, HTML_Snippet, LaTeX, LaTeX_Dramatist, LaTeX_Snippet, XHTML10transitional, XHTML11m

Constant Summary collapse

INLATEX_RX =
Regexp.new(rx.join('|'))
@@custom_particles =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from CommonObject

class_attribute, class_attributes, class_attributes=, class_attributes_ensure, class_meta_attributes, inherited, method_missing, respond_to?

Constructor Details

#initialize(deplate, args = {}) ⇒ Formatter



141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/deplate/formatter.rb', line 141

def initialize(deplate, args={})
    @deplate         = deplate
    @variables       = deplate.variables
    @advices         = args[:advices]      || {}
    @doc_services    = args[:doc_services] || initialize_services
    @inlatex_idx     = 0
    @encodings       = {}
    @symbol_proxy    = nil
    @entities_table  = nil
    @format_advice_backlist = []
    reset!
end

Instance Attribute Details

#advicesObject (readonly)

Returns the value of attribute advices.



133
134
135
# File 'lib/deplate/formatter.rb', line 133

def advices
  @advices
end

#bibentriesObject

Returns the value of attribute bibentries.



136
137
138
# File 'lib/deplate/formatter.rb', line 136

def bibentries
  @bibentries
end

#cjk_nospaceObject (readonly)

Returns the value of attribute cjk_nospace.



12
13
14
# File 'lib/deplate/mod/lang-zh_CN-autospace.rb', line 12

def cjk_nospace
  @cjk_nospace
end

#cjk_smart_blanksObject (readonly)

Returns the value of attribute cjk_smart_blanks.



12
13
14
# File 'lib/deplate/zh_CN.rb', line 12

def cjk_smart_blanks
  @cjk_smart_blanks
end

#cjk_spaceObject (readonly)

Returns the value of attribute cjk_space.



12
13
14
# File 'lib/deplate/mod/lang-zh_CN-autospace.rb', line 12

def cjk_space
  @cjk_space
end

#deplateObject (readonly)

Returns the value of attribute deplate.



132
133
134
# File 'lib/deplate/formatter.rb', line 132

def deplate
  @deplate
end

#doc_servicesObject

A hash holding all known document services (names => method).



138
139
140
# File 'lib/deplate/formatter.rb', line 138

def doc_services
  @doc_services
end

#entities_tableObject (readonly)

Returns the value of attribute entities_table.



139
140
141
# File 'lib/deplate/formatter.rb', line 139

def entities_table
  @entities_table
end

#expanderObject (readonly)

Returns the value of attribute expander.



134
135
136
# File 'lib/deplate/formatter.rb', line 134

def expander
  @expander
end

#special_symbolsObject

Returns the value of attribute special_symbols.



135
136
137
# File 'lib/deplate/formatter.rb', line 135

def special_symbols
  @special_symbols
end

Class Method Details

.def_service(name, &block) ⇒ Object

<TBD>Shouldn’t services belong to the formatter?



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/deplate/formatter.rb', line 64

def def_service(name, &block)
    # prefix = @formatter.class.myname.gsub('\W', '__')
    # method = ['svc', prefix, name].join('_')
    method = ['svc', name].join('_')
    self.class_eval do
        define_method(method, &block)
    end
    init  = ['formatter_initialize', method].join('_')
    sname = name.gsub(/_(.)/) {$1.capitalize}
    self.class_eval do
        define_method(init) do
            @doc_services[name]  = method
            @doc_services[sname] = method
        end
    end
end

.formatter_family_members(args = {}) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/deplate/formatter.rb', line 107

def formatter_family_members(args={})
    acc = []
    formatter_names = args[:names] || []
    formatter_class = fmt = self
    myname = fmt.myname
    while myname
        acc << myname
        yield(myname) if block_given?
        fmt = fmt.superclass
        myname = fmt.myname
    end
    (formatter_class.related + formatter_names).each do |myname|
        acc << myname
        yield(myname) if block_given?
    end
    acc
end

.formatter_related?(name) ⇒ Boolean



125
126
127
# File 'lib/deplate/formatter.rb', line 125

def formatter_related?(name)
    formatter_family_members.include?(name)
end

.hook_post_myname=(name) ⇒ Object



58
59
60
61
# File 'lib/deplate/formatter.rb', line 58

def hook_post_myname=(name)
    klass = self
    Deplate::Core.class_eval {declare_formatter(klass)}
end

.noop(context, name) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/deplate/formatter.rb', line 50

def noop(context, name)
    context.module_eval %{
        def #{name}(*args)
            return ""
        end
    }
end

.set_options_for_file(options, file = nil) ⇒ Object



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
# File 'lib/deplate/formatter.rb', line 81

def set_options_for_file(options, file=nil)
    case file
    when '-'
        options.ext      = ''
        options.srcdir ||= Dir.pwd
        options.out    ||= '-'
    else
        options.suffix ||= self.suffix
        unless file.nil?
            options.ext      = File.extname(file)
            options.srcdir ||= File.dirname(file)
        end
        if options.out
            options.out = Deplate::Core.file_join(options.dir, options.out)
            # if options.out != '-'
            #     options.out = options.dir ? Deplate::Core.file_join(options.dir, options.out) : options.out
            # end
        elsif file.nil?
            options.out = '-'
        else
            options.out = Deplate::Core.get_out_fullname(file, options.suffix, options)
        end
    end
    options
end

Instance Method Details

#bare_latex_formula(text) ⇒ Object



927
928
929
930
931
932
933
934
935
# File 'lib/deplate/formatter.rb', line 927

def bare_latex_formula(text)
    m = /^(\\\[|\$)(.*?)(\\\]|\$)$/.match(text)
    if m
        return [m[1] == '\\[', m[2]]
    else
        log(['Internal error', text], :error)
        return nil
    end
end

#bib_entry(key) ⇒ Object



688
689
690
691
692
693
694
695
696
# File 'lib/deplate/formatter.rb', line 688

def bib_entry(key)
    b = @bibentries[key] || {}
    crossref = b['crossref']
    if crossref
        cb = @bibentries[crossref]
        b.update(cb) {|k, o, n| o} if cb
    end
    return b
end

#canonic_enc_name(enc, table = @encodings) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/deplate/formatter.rb', line 256

def canonic_enc_name(enc, table=@encodings)
    case enc.downcase
    when 'latin-1', 'latin1', 'l1', 'isolat1', 'iso-8859-1'
        cen = 'latin1'
    when 'latin-9', 'latin9', 'l9', 'isolat9', 'iso-8859-15'
        cen = 'latin9'
    when 'gb2312', 'gbk'
        cen = 'gb2312'
    when 'koi8-r'
        cen = 'koi8-r'
    when 'utf8', 'utf-8'
        cen = 'utf-8'
    else
        log(['Unsupported encoding', enc], :anyway)
        cen = enc
    end
    return table[cen] || cen
end

#canonic_encoding(default = nil, table = {}) ⇒ Object

def canonic_encoding(default=nil, table=@encodings)



248
249
250
# File 'lib/deplate/formatter.rb', line 248

def canonic_encoding(default=nil, table={})
    canonic_enc_name(@variables['encoding'] || default || 'latin1', table)
end

#char_by_name(name) ⇒ Object



492
493
494
495
496
497
498
499
# File 'lib/deplate/formatter.rb', line 492

def char_by_name(name)
    @entities_table.each do |char, named, numbered|
        if named == name
            return char
        end
    end
    return name
end

#char_by_number(number) ⇒ Object



483
484
485
486
487
488
489
490
# File 'lib/deplate/formatter.rb', line 483

def char_by_number(number)
    @entities_table.each do |char, named, numbered|
        if numbered == number
            return char
        end
    end
    return number
end

#check_symbol_proxyObject



501
502
503
504
505
# File 'lib/deplate/formatter.rb', line 501

def check_symbol_proxy
    unless @symbol_proxy
        pre_process
    end
end

#consumed_idsObject



172
173
174
# File 'lib/deplate/formatter.rb', line 172

def consumed_ids
    @deplate.output.attributes[:consumed_ids]
end

#consumed_ids=(arg) ⇒ Object



175
176
177
# File 'lib/deplate/formatter.rb', line 175

def consumed_ids=(arg)
    @deplate.output.attributes[:consumed_ids] = arg
end

#consumed_labelsObject



165
166
167
# File 'lib/deplate/formatter.rb', line 165

def consumed_labels
    @deplate.output.attributes[:consumed_labels]
end

#consumed_labels=(arg) ⇒ Object



168
169
170
# File 'lib/deplate/formatter.rb', line 168

def consumed_labels=(arg)
    @deplate.output.attributes[:consumed_labels] = arg
end

#def_advice(applicant, agent, args) ⇒ Object



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
# File 'lib/deplate/formatter.rb', line 197

def def_advice(applicant, agent, args)
    this = @advices[agent] ||= {}
    for type in [:wrap]
        thistype = []
        prc = args[type]
        if prc
            if prc.kind_of?(Proc)
                thistype << {:applicant => applicant, :prc => prc}
            else
                raise "Not a Proc: %s" % prc
            end
        end
        unless thistype.empty?
            if this[type]
                this[type] += thistype
            else
                this[type] = thistype
            end
        end
    end
    for type in [:before, :around, :after]
        prc = args[type]
        if prc
            log(["Unsupported advice type", type, applicant, prc], :error)
        end
    end
end

#document_encoding(table = @encodings) ⇒ Object



252
253
254
# File 'lib/deplate/formatter.rb', line 252

def document_encoding(table=@encodings)
    canonic_enc_name(@variables['encoding'] || 'latin1', table)
end

#doublequote_close(invoker) ⇒ Object



532
533
534
535
# File 'lib/deplate/formatter.rb', line 532

def doublequote_close(invoker)
    check_symbol_proxy
    @symbol_proxy.doublequote_close(invoker)
end

#doublequote_open(invoker) ⇒ Object



527
528
529
530
# File 'lib/deplate/formatter.rb', line 527

def doublequote_open(invoker)
    check_symbol_proxy
    @symbol_proxy.doublequote_open(invoker)
end

#dummy(invoker, *args) ⇒ Object



389
390
391
# File 'lib/deplate/formatter.rb', line 389

def dummy(invoker, *args)
    args
end

#dvi2png(invoker, fdvi, fout, other_options = nil) ⇒ Object



1113
1114
1115
1116
1117
1118
# File 'lib/deplate/formatter.rb', line 1113

def dvi2png(invoker, fdvi, fout, other_options=nil)
    if Deplate::External.dvi2png(invoker, fdvi, fout, other_options) and @deplate.options.clean
        File.delete(fdvi) if @deplate.options.clean
        invoker.log(["Deleting", fdvi])
    end
end

#dvi2ps(invoker, fdvi, fps, other_options = nil) ⇒ Object



1105
1106
1107
1108
1109
1110
1111
# File 'lib/deplate/formatter.rb', line 1105

def dvi2ps(invoker, fdvi, fps, other_options=nil)
    # -Pwww 
    if Deplate::External.dvi2ps(invoker, fdvi, fps, other_options) and @deplate.options.clean
        File.delete(fdvi) if @deplate.options.clean
        invoker.log(["Deleting", fdvi])
    end
end

#encode_id(id) ⇒ Object



577
578
579
# File 'lib/deplate/formatter.rb', line 577

def encode_id(id)
    id ? Deplate::Core.clean_name(id) : id
end

#entities_encode_plain_textObject

Properly format text as formatter-valid plain text.

If escaped is true, text appears in a special context and was escaped by a backslash or similar.

If a block is given, convert normal text using this block.

Special characters are translated on the basis of @special_symbols.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/deplate/mod/entities-encode.rb', line 16

def plain_text(text, escaped=false)
    if defined?(@plain_text_rx)
        acc = []
        text.split(@plain_text_rx).each_with_index do |e, i|
            if i.modulo(2) == 0
                acc << plain_text_recode(e) unless e.empty?
            else
                r = @special_symbols[e]
                case r
                when String
                    acc << r
                when Proc
                    acc << r.call(escaped)
                else
                    raise "Internal error: Strange symbol replacement for '#{e}'"
                end
            end
        end
        acc.join
    else
        plain_text_recode(text)
    end
end

#fill_in_template(invoker) ⇒ Object



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

def fill_in_template(invoker)
    invoker.elt
end

#format_ACT(invoker) ⇒ Object



671
672
673
# File 'lib/deplate/formatter.rb', line 671

def format_ACT(invoker)
    return ''
end

#format_CAST(invoker) ⇒ Object



667
668
669
# File 'lib/deplate/formatter.rb', line 667

def format_CAST(invoker)
    return ''
end

#format_cite(invoker) ⇒ Object



749
750
751
# File 'lib/deplate/formatter.rb', line 749

def format_cite(invoker)
    bib_styler.bib_cite(invoker)
end

#format_direct(invoker, text = nil) ⇒ Object



675
676
677
678
679
# File 'lib/deplate/formatter.rb', line 675

def format_direct(invoker, text=nil)
    # invoker.push_styles(['emphasized'])
    invoker.push_styles(['play-direct'])
    "(%s)" % (text || invoker.elt || invoker.text)
end

#format_element(agent, invoker, *args) ⇒ Object



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/deplate/formatter.rb', line 308

def format_element(agent, invoker, *args)
    if @format_advice_backlist.include?(agent)
        send(agent, invoker, *args)
    else
        # rv = with_agent(agent, Array, invoker, *args)
        # rv.empty? ? format_unknown(invoker) : join_blocks(rv)
        rv = with_agent(agent, Array, invoker, *args)
        if rv and !rv.empty? and !self.class.naked_agents.include?(agent)
            wa = {}
            wa[:styles] = invoker.styles if invoker.respond_to?(:styles)
            rv = methods.find_all {|m| m =~ /^wrap_formatted_element_/ }.
                inject(rv) {|rv, m| send(m, invoker, rv, wa)}
        end
        rv    
    end
end

#format_element_as_string(agent, invoker, *args) ⇒ Object



325
326
327
# File 'lib/deplate/formatter.rb', line 325

def format_element_as_string(agent, invoker, *args)
    format_element(agent, invoker, *args)
end

#format_GET(invoker) ⇒ Object



626
627
628
629
630
631
632
633
# File 'lib/deplate/formatter.rb', line 626

def format_GET(invoker)
    elt = invoker.elt
    if elt
        elt.format_clip(invoker, Deplate::Element)
    else
        invoker.log("Dropped!", :error)
    end
end

#format_highstep(invoker, txt = nil) ⇒ Object



24
25
26
# File 'lib/deplate/mod/html-highstep.rb', line 24

def format_highstep(invoker, txt=nil)
    format_emphasize(invoker, txt)
end

#format_inlatex(invoker) ⇒ Object

Format the Inlatex region



889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
# File 'lib/deplate/formatter.rb', line 889

def format_inlatex(invoker)
    args   = invoker.args
    inline = args['inline']
    args['h'] ||= (args['inlineLatexHeight'] || args['inlatexHeight']) if inline
    acc    = []
    elt    = invoker.elt
    if elt
        elt.each do |i|
            acc << format_element(:format_figure, invoker, inline, i)
        end
    else
        invoker.log(['Empty element', 'inlatex'], :error)
    end
    join_blocks(acc)
end

#format_LIST(invoker) ⇒ Object



635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# File 'lib/deplate/formatter.rb', line 635

def format_LIST(invoker)
    acc  = []
    elt  = invoker.elt
    case elt
    when 'contents'
        elt = 'toc'
    when 'tables'
        elt = 'lot'
    when 'figures'
        elt = 'lof'
    end
    meth = "format_list_of_" + elt
    args = invoker.args
    begin
        if respond_to?(meth)
            acc << send(meth, invoker)
        elsif @deplate.options.listings.is_defined?(elt)
            acc << format_custom_list(invoker, elt)
        else
            log(["Unknown list type", elt.inspect], :error)
        end
        acc << format_pagebreak(invoker) if args["page"]
    rescue StandardError => e
        log(["Formatting on LIST failed", elt.inspect, e, e.backtrace[0..10]], :error)
    end
    join_blocks(acc)
end

#format_ltx(invoker, other_args = {}) ⇒ Object Also known as: format_math

Format the ltx macro



906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
# File 'lib/deplate/formatter.rb', line 906

def format_ltx(invoker, other_args={})
    args = invoker.args
    acc  = []
    args['h']   ||= (args['inlineLatexHeight'] || other_args['h'])
    args['alt'] ||= invoker.text
    args['style'] = 'latex'
    inlatex = invoker.elt
    if !inlatex or inlatex.empty?
        acc << invoker.text
    else
        for i in inlatex
            # acc << @deplate.formatter.include_image(invoker, i, args, true)
            acc << format_element(:format_figure, invoker, true, i)
        end
    end
    return acc.flatten.join("\n")
end

#format_PAGEBREAK(invoker) ⇒ Object



663
664
665
# File 'lib/deplate/formatter.rb', line 663

def format_PAGEBREAK(invoker)
    format_pagebreak(invoker, nil, true)
end

#format_particle(agent, invoker, *args) ⇒ Object



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/deplate/formatter.rb', line 287

def format_particle(agent, invoker, *args)
    if @format_advice_backlist.include?(agent)
        send(agent, invoker, *args)
    else
        # rv = with_agent(agent, Array, invoker, *args)
        # rv.empty? ? format_unknown_particle(invoker) : rv.join
        rv = with_agent(agent, Array, invoker, *args)
        if rv and !rv.empty? and !self.class.naked_agents.include?(agent)
            wa = {}
            wa[:styles] = invoker.styles if invoker.respond_to?(:styles)
            rv = methods.find_all {|m| m =~ /^wrap_formatted_particle_/ }.
                inject(rv) {|rv, m| send(m, invoker, rv, wa)}
        end
        rv
    end
end

#format_particle_as_string(agent, invoker, *args) ⇒ Object



304
305
306
# File 'lib/deplate/formatter.rb', line 304

def format_particle_as_string(agent, invoker, *args)
    join_inline(format_particle(agent, invoker, *args))
end

#format_plain_text(invoker, text = nil, escaped = false) ⇒ Object



562
563
564
565
566
# File 'lib/deplate/formatter.rb', line 562

def format_plain_text(invoker, text=nil, escaped=false)
    text ||= invoker.match
    # <+TBD+> escaped
    plain_text(text, escaped)
end

#format_region(invoker) ⇒ Object



745
746
747
# File 'lib/deplate/formatter.rb', line 745

def format_region(invoker)
    invoker.elt.strip
end

#format_symbol(invoker, sym) ⇒ Object



557
558
559
560
# File 'lib/deplate/formatter.rb', line 557

def format_symbol(invoker, sym)
    check_symbol_proxy
    @symbol_proxy.format_symbol(invoker, sym)
end

#format_unknown(invoker) ⇒ Object



702
703
704
705
706
707
708
709
# File 'lib/deplate/formatter.rb', line 702

def format_unknown(invoker)
    log(["Unknown element", invoker.class], :error, invoker.source)
    elt = invoker.elt
    if elt.kind_of?(Array)
        elt = elt.join("\n")
    end
    format_verbatim(invoker, elt)
end

#format_unknown_macro(invoker) ⇒ Object



715
716
717
# File 'lib/deplate/formatter.rb', line 715

def format_unknown_macro(invoker)
    return %{#{plain_text("{")}#{invoker.elt}#{plain_text("}")}}
end

#format_unknown_particle(invoker) ⇒ Object



711
712
713
# File 'lib/deplate/formatter.rb', line 711

def format_unknown_particle(invoker)
    return plain_text(invoker.args[:match][0])
end

#format_void(invoker, text = nil) ⇒ Object



568
569
570
# File 'lib/deplate/formatter.rb', line 568

def format_void(invoker, text=nil)
    text || invoker.elt
end

#formatted_block(env, text, opts = nil, args = nil, no_id = false, no_indent = false) ⇒ Object



1127
1128
1129
1130
# File 'lib/deplate/formatter.rb', line 1127

def formatted_block(env, text, opts=nil, args=nil, no_id=false, no_indent=false)
    text = indent_text(text) unless no_indent
    return join_blocks([get_open(env, opts, args, :no_id => no_id), text, get_close(env, args)])
end

#formatted_inline(env, text, opts = nil, args = nil, no_id = false) ⇒ Object



1134
1135
1136
# File 'lib/deplate/formatter.rb', line 1134

def formatted_inline(env, text, opts=nil, args=nil, no_id=false)
    return join_inline([get_open(env, opts, args, :no_id => no_id), text, get_close(env, args)])
end

#formatted_single(env, opts = nil, args = nil, no_id = false) ⇒ Object



1138
1139
1140
# File 'lib/deplate/formatter.rb', line 1138

def formatted_single(env, opts=nil, args=nil, no_id=false)
    return get_open(env, opts, args, :single => true, :no_id => no_id)
end

#formatter_initialize_mark_urlsObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/deplate/mod/mark-external-urls.rb', line 19

def formatter_initialize_mark_urls
    def_advice('mark-external-urls', :format_url,
              :wrap => Proc.new do |agent, rv, invoker, name, dest, *args|
                if dest =~ Deplate::HyperLink::Url.rx
                    if dest =~ /^mailto:/
                        icon = @variables['mailtoIcon'] || 'mailto.png'
                        invoker.args['alt'] ||= 'e-mail'
                    else
                        icon = @variables['urlIcon'] || 'url.png'
                        # invoker.args['alt'] ||= 'url'
                    end
                    args = {'style' => 'remote'}
                    img  = format_particle(:include_image, invoker, icon, args, true)
                    if @variables['markerInFrontOfURL']
                        img + rv
                    else
                        rv + img
                    end
                else
                    rv
                end
              end
             )
end

#formatter_nameObject



597
598
599
# File 'lib/deplate/formatter.rb', line 597

def formatter_name
    self.class.myname
end

#formatter_related?(name) ⇒ Boolean



154
155
156
# File 'lib/deplate/formatter.rb', line 154

def formatter_related?(name)
    self.class.formatter_related?(name)
end

#formatter_rxObject



601
602
603
# File 'lib/deplate/formatter.rb', line 601

def formatter_rx
    self.class.rx
end

#get_first_char(string, upcase = false) ⇒ Object

Return the first character of string while taking care whether string starts with a multi-byte sequence. Return the character in upper case if upcase is true (this usually doesn’t work for multi-byte characters.



762
763
764
765
766
767
768
# File 'lib/deplate/formatter.rb', line 762

def get_first_char(string, upcase=false)
    if multibyte_leader?(string[0])
        string[0..1]
    else
        get_first_char_re_zh_cn(string, upcase)
    end
end

#get_first_char_re_utf8Object



17
18
19
20
21
22
23
# File 'lib/deplate/mod/utf8.rb', line 17

def get_first_char(string, upcase=false)
    if multibyte_leader?(string[0])
        string[0..1]
    else
        get_first_char_re_zh_cn(string, upcase)
    end
end

#get_first_char_re_zh_cnObject



41
# File 'lib/deplate/zh_CN.rb', line 41

alias :get_first_char_re_zh_cn :get_first_char

#hook_post_go_recodeObject

def hook_pre_go_recode

recode_start

end



23
24
25
# File 'lib/deplate/mod/recode.rb', line 23

def hook_post_go_recode
    recode_stop
end

#hook_pre_go_iconvObject



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/deplate/mod/iconv.rb', line 17

def hook_pre_go_iconv
    @iconv_encodings = {}
    unless defined?(@iconv_enc_source)
        source            = @deplate.variables['encoding'] || "latin1"
        @iconv_enc_source = canonic_enc_name(source, @iconv_encodings)
        target            = @deplate.variables['recodeEncoding'] || "utf-8"
        @iconv_enc_target = canonic_enc_name(target, @iconv_encodings)
        @deplate.variables['encoding'] = target
    end
    unless defined?(@iconv_converter) and @iconv_converter
        @iconv_converter = Iconv.new(@iconv_enc_target, @iconv_enc_source)
    end
end

#hook_pre_process_inlatexObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/deplate/mod/inlatex-compound.rb', line 34

def hook_pre_process_inlatex
    pseudo = Deplate::PseudoContainer.new(@deplate,
                                          :accum => @inlatex_body,
                                          :args => {'sfx' => @inlatex_suffix}
                                         )
    inlatex_compound(pseudo)
    fnames = pseudo.elt
    if fnames.size != @inlatex_container.size
        log(['Unexpected number of output files',
            "#{fnames.size} (#{@inlatex_container.size})"], :error)
    end
    if @inlatex_container.kind_of?(Array) and fnames.kind_of?(Array)
        @inlatex_container.each_with_index {|o, i| o.elt = [fnames[i]]}
    end
end

#hook_pre_setup_zh_cnObject



14
15
16
17
# File 'lib/deplate/zh_CN.rb', line 14

def hook_pre_setup_zh_cn
    # @deplate.variables['encoding'] = 'GB2312'
    @cjk_smart_blanks = !(@deplate.variables['noSmartBlanks'] || false)
end

#hook_pre_setup_zh_cn_autospaceObject



13
14
15
16
# File 'lib/deplate/mod/lang-zh_CN-autospace.rb', line 13

def hook_pre_setup_zh_cn_autospace
    @cjk_space   = ' '
    @cjk_nospace = ''
end

#indent_text(text, args = {}) ⇒ Object



1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
# File 'lib/deplate/formatter.rb', line 1142

def indent_text(text, args={})
    if text
        mult    = args[:mult] || 1
        shift   = args[:shift]
        hanging = args[:hanging]
        indent  = args[:indent] || format_indent(mult, shift)
        return text.collect do |l|
            rv = '%s%s' % [indent, l.chomp]
            if hanging
                indent = args[:indenttail] || \
                    if args[:indent]
                        args[:indent] + 
                            case hanging
                            when Integer
                            ' ' * hanging
                            else
                            '    '
                            end
                    else
                        format_indent(mult + 1, shift)
                    end
                hanging = false
            end
            rv
        end.join("\n")
    end
end

#inlatex(invoker) ⇒ Object

Process inline latex



939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
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
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
# File 'lib/deplate/formatter.rb', line 939

def inlatex(invoker)
    pkgs, body = inlatex_split(invoker.accum)
    id      = inlatex_id(invoker)
    sfx     = invoker.args['sfx'] || @deplate.variables['ltxSfx'] || inlatex_sfx
    currDir = Dir.pwd
    @deplate.in_working_dir do
        ftex    = id + '.tex'
        flog    = id + '.log'
        faux    = id + '.aux'
        fdvi    = id + '.dvi'
        fps     = id + '.ps'
        checkOW = true

        case sfx
        when 'ps'
            device  = nil
            fout    = fps
            checkOW = false
        when 'pdf'
            device  = 'pdfwrite'
            fout    = id + '.*.pdf'
        when 'jpeg', 'jpg'
            device  = 'jpeg'
            fout    = id + '.*.jpeg'
        when "png"
            device  = "png"
            fout    = id + ".png"
        else
            raise "Unknown device/suffix: #{sfx}"
        end

        pointsize = invoker.args['pointsize'] || 
            @deplate.variables['latexPointsize'] || '10'
        acc = [
            "\\documentclass[#{pointsize}pt,a4paper,notitlepage]{article}",
            "\\usepackage{amsmath}",
            "\\usepackage{amsfonts}",
            "\\usepackage{amssymb}",
            # "\\usepackage{mathabx}",
        ]
        acc += pkgs
        acc << "\\begin{document}" << "\\pagestyle{empty}"
        acc += body
        acc << "\\end{document}"

        if Deplate::Region.check_file(invoker, fout, ftex, acc)
            invoker.log(['Files exist! Using', fout], :anyway)
        else
            if checkOW and !@deplate.options.force
                for f in [ftex, flog, faux, fdvi, fout]
                    if !Dir[f].empty?
                        raise "Please delete '#{f}' or change the id before proceeding:\n#{invoker.accum.join("\n")}"
                    end
                end
            end

            acc = acc.join("\n")

            Deplate::External.write_file(invoker, ftex) {|io| io.puts(acc)}
            inlatex_process_latex(invoker, ftex, faux, flog)
            if block_given?
                yield(invoker, device, fdvi, fps, fout)
            else
                case device
                when "png"
                    inlatex_process_dvi_png(invoker, fdvi, fout) if File.exist?(fdvi)
                else
                    inlatex_process_dvi(invoker, fdvi, fps) if File.exist?(fdvi)
                    if device
                        inlatex_process_ps(invoker, device, fps, fout, invoker.args)
                    elsif fps != fout
                        File.rename(fps, fout)
                    end
                end
            end
        end

        invoker.elt = Dir[fout]
        if invoker.elt.empty?
            code = invoker.accum.join("\n")
            invoker.log(["Conversion if Inline LaTeX failed", code], :error)
        end
    end
end

#inlatex_clean(line) ⇒ Object



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

def inlatex_clean(line)
    line = line.chomp
    unless @deplate.is_allowed?('t')
        line.gsub!(INLATEX_RX, '+++disabled+++')
    end
    line
end

#inlatex_compoundObject

Process inline latex. The file names of the output are saved as an array in invoker.elt.



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
# File 'lib/deplate/mod/inlatex-compound.rb', line 16

def inlatex(invoker)
    pkgs, body = inlatex_split(invoker.accum)
    id      = inlatex_id(invoker)
    sfx     = invoker.args['sfx'] || @deplate.variables['ltxSfx'] || inlatex_sfx
    currDir = Dir.pwd
    @deplate.in_working_dir do
        ftex    = id + '.tex'
        flog    = id + '.log'
        faux    = id + '.aux'
        fdvi    = id + '.dvi'
        fps     = id + '.ps'
        checkOW = true

        case sfx
        when 'ps'
            device  = nil
            fout    = fps
            checkOW = false
        when 'pdf'
            device  = 'pdfwrite'
            fout    = id + '.*.pdf'
        when 'jpeg', 'jpg'
            device  = 'jpeg'
            fout    = id + '.*.jpeg'
        when "png"
            device  = "png"
            fout    = id + ".png"
        else
            raise "Unknown device/suffix: #{sfx}"
        end

        pointsize = invoker.args['pointsize'] || 
            @deplate.variables['latexPointsize'] || '10'
        acc = [
            "\\documentclass[#{pointsize}pt,a4paper,notitlepage]{article}",
            "\\usepackage{amsmath}",
            "\\usepackage{amsfonts}",
            "\\usepackage{amssymb}",
            # "\\usepackage{mathabx}",
        ]
        acc += pkgs
        acc << "\\begin{document}" << "\\pagestyle{empty}"
        acc += body
        acc << "\\end{document}"

        if Deplate::Region.check_file(invoker, fout, ftex, acc)
            invoker.log(['Files exist! Using', fout], :anyway)
        else
            if checkOW and !@deplate.options.force
                for f in [ftex, flog, faux, fdvi, fout]
                    if !Dir[f].empty?
                        raise "Please delete '#{f}' or change the id before proceeding:\n#{invoker.accum.join("\n")}"
                    end
                end
            end

            acc = acc.join("\n")

            Deplate::External.write_file(invoker, ftex) {|io| io.puts(acc)}
            inlatex_process_latex(invoker, ftex, faux, flog)
            if block_given?
                yield(invoker, device, fdvi, fps, fout)
            else
                case device
                when "png"
                    inlatex_process_dvi_png(invoker, fdvi, fout) if File.exist?(fdvi)
                else
                    inlatex_process_dvi(invoker, fdvi, fps) if File.exist?(fdvi)
                    if device
                        inlatex_process_ps(invoker, device, fps, fout, invoker.args)
                    elsif fps != fout
                        File.rename(fps, fout)
                    end
                end
            end
        end

        invoker.elt = Dir[fout]
        if invoker.elt.empty?
            code = invoker.accum.join("\n")
            invoker.log(["Conversion if Inline LaTeX failed", code], :error)
        end
    end
end

#inlatex_id(invoker, last = false) ⇒ Object



1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
# File 'lib/deplate/formatter.rb', line 1024

def inlatex_id(invoker, last=false)
    id = invoker.args["id"]
    unless id
        unless last
            @inlatex_idx += 1
        end
        id = @deplate.auxiliary_auto_filename('ltx', @inlatex_idx, invoker.accum)
        invoker.log(["No ID given", invoker.accum])
    end
    id
end

#inlatex_process_dvi(invoker, fdvi, fps) ⇒ Object



1040
1041
1042
# File 'lib/deplate/formatter.rb', line 1040

def inlatex_process_dvi(invoker, fdvi, fps)
    dvi2ps(invoker, fdvi, fps)
end

#inlatex_process_dvi_png(invoker, fdvi, fout) ⇒ Object



1044
1045
1046
# File 'lib/deplate/formatter.rb', line 1044

def inlatex_process_dvi_png(invoker, fdvi, fout)
    dvi2png(invoker, fdvi, fout)
end

#inlatex_process_latex(invoker, ftex, faux, flog) ⇒ Object



1036
1037
1038
# File 'lib/deplate/formatter.rb', line 1036

def inlatex_process_latex(invoker, ftex, faux, flog)
    latex2dvi(invoker, ftex, faux, flog)
end

#inlatex_process_ps(invoker, device, fps, fout, args) ⇒ Object



1048
1049
1050
# File 'lib/deplate/formatter.rb', line 1048

def inlatex_process_ps(invoker, device, fps, fout, args)
    ps2img(invoker, device, fps, fout, args) if File.exist?(fps)
end

#inlatex_sfxObject

The default suffix/device to be used for inlatex output.



1090
1091
1092
# File 'lib/deplate/formatter.rb', line 1090

def inlatex_sfx
    'jpeg'
end

#inlatex_split(accum) ⇒ Object

Divert lines in invoker#accum to the preamble or the body.



1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
# File 'lib/deplate/formatter.rb', line 1053

def inlatex_split(accum)
    pkgs = []
    body = []
    for l in accum.join("\n")
        l = inlatex_clean(l)
        if l =~ /^\s*\\(usepackage|input)\s*(\[.*?\])?\s*\{.+?\}\s*$/
            pkgs << l.chomp
        elsif l =~ /%%%\s*$/
            pkgs << l.chomp
        else
            body << l.chomp
        end
    end
    return pkgs.uniq, body
end

#invoke_service(name, args = {}, text = '') ⇒ Object

Run a “service”, i.e., a small, mostly autonomous function/method that usually yields some formatted output.



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/deplate/formatter.rb', line 227

def invoke_service(name, args={}, text='')
    method = @doc_services[name]
    if method
        begin
            return send(method, args || {}, text || '')
        rescue Exception => e
            puts e.backtrace[0..10].join("\n")
            log(['Calling service failed', name, e], :error)
        end
    else
        # p "DBG"
        # puts @doc_services.keys.sort.join("\n")
        log(['Unknown service', name], :error)
    end
end

#join_blocks(blocks) ⇒ Object



279
280
281
# File 'lib/deplate/formatter.rb', line 279

def join_blocks(blocks)
    blocks.flatten.compact.join("\n")
end

#join_inline(strings) ⇒ Object



283
284
285
# File 'lib/deplate/formatter.rb', line 283

def join_inline(strings)
    strings.flatten.compact.join
end

#label_delegateObject



589
590
591
# File 'lib/deplate/formatter.rb', line 589

def label_delegate
    self.class.label_delegate
end

#label_modeObject



581
582
583
# File 'lib/deplate/formatter.rb', line 581

def label_mode
    self.class.label_mode
end

#label_onceObject



585
586
587
# File 'lib/deplate/formatter.rb', line 585

def label_once
    self.class.label_once
end

#latex2dvi(invoker, ftex, faux, flog) ⇒ Object



1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
# File 'lib/deplate/formatter.rb', line 1094

def latex2dvi(invoker, ftex, faux, flog)
    if Deplate::External.latex(invoker, ftex) and @deplate.options.clean
        for i in [faux, flog]
            if File.exist?(i)
                File.delete(i)
                invoker.log(["Deleting", i])
            end
        end
    end
end

#log(*args) ⇒ Object



243
244
245
# File 'lib/deplate/formatter.rb', line 243

def log(*args)
    Deplate::Core.log(*args)
end

#matches?(text) ⇒ Boolean



614
615
616
617
618
619
620
621
622
623
624
# File 'lib/deplate/formatter.rb', line 614

def matches?(text)
    self.class.formatter_family_members.any? do |fmtname|
        fmt = @deplate.get_formatter_class(fmtname)
        if text[0..0] == '~'
            rv = (fmt.myname =~ Regexp.new(text[1..-1]))
        else
            rv = (text =~ fmt.rx)
        end
        return rv ? true : false
    end
end

#module_initialize_numparaObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/deplate/mod/numpara.rb', line 19

def module_initialize_numpara
    @numpara_done = []
    def_advice("numpara", :format_paragraph,
              :wrap => Proc.new do |agent, rv, invoker, *rest|
                unless invoker.args["noNum"] or @numpara_done.include?(invoker)
                    if defined?(@paragraph_number)
                        @paragraph_number += 1
                    else
                        @paragraph_number = 1
                    end
                    invoker.elt = numbered_paragraph(invoker.elt, @paragraph_number)
                    @numpara_done << invoker
                end
              end
             )
end

#multibyte_leader?(ch) ⇒ Boolean

Check if ch (a number representing a character) is a multi-byte leader. This method always returns false unless it is overwritten by some module.



755
756
757
# File 'lib/deplate/formatter.rb', line 755

def multibyte_leader?(ch)
    ch && ch >= 0xA1 && ch <= 0xFE
end

#nonbreakingspace(invoker) ⇒ Object



547
548
549
550
# File 'lib/deplate/formatter.rb', line 547

def nonbreakingspace(invoker)
    check_symbol_proxy
    @symbol_proxy.nonbreakingspace(invoker)
end

#numbered_paragraph(text, number) ⇒ Object



36
37
38
# File 'lib/deplate/mod/numpara.rb', line 36

def numbered_paragraph(text, number)
    return [text, plain_text("[%d]" % number)].join(" ")
end

#output(invoker, *body) ⇒ Object



393
394
395
# File 'lib/deplate/formatter.rb', line 393

def output(invoker, *body)
    output_at(invoker.doc_type, invoker.doc_slot, *body)
end

#output_at(type, slot, *body) ⇒ Object

def_delegator(:@deplate, :add_at, :output_at)



408
409
410
411
# File 'lib/deplate/formatter.rb', line 408

def output_at(type, slot, *body)
    log(["Output at", "#{type}@#{slot}", body], :debug)
    @deplate.output.add_at(type, slot, *body)
end

#output_destinationObject



275
276
277
# File 'lib/deplate/formatter.rb', line 275

def output_destination
    @deplate.output.top_heading.destination || @deplate.options.out
end

#output_empty_at?(type, slot) ⇒ Boolean



403
404
405
# File 'lib/deplate/formatter.rb', line 403

def output_empty_at?(type, slot)
    @deplate.output.empty_at?(type, slot)
end

#output_preferably_at(invoker, type, slot, *body) ⇒ Object



397
398
399
400
401
# File 'lib/deplate/formatter.rb', line 397

def output_preferably_at(invoker, type, slot, *body)
    type = defined?(invoker.doc_type) ? invoker.doc_type(type) : type
    slot = defined?(invoker.doc_slot) ? invoker.doc_slot(slot) : slot
    output_at(type, slot, *body)
end

#plain_text(text, escaped = false) ⇒ Object

Properly format text as formatter-valid plain text.

If escaped is true, text appears in a special context and was escaped by a backslash or similar.

If a block is given, convert normal text using this block.

Special characters are translated on the basis of @special_symbols.



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/deplate/formatter.rb', line 439

def plain_text(text, escaped=false)
    if defined?(@plain_text_rx)
        acc = []
        text.split(@plain_text_rx).each_with_index do |e, i|
            if i.modulo(2) == 0
                acc << plain_text_recode(e) unless e.empty?
            else
                r = @special_symbols[e]
                case r
                when String
                    acc << r
                when Proc
                    acc << r.call(escaped)
                else
                    raise "Internal error: Strange symbol replacement for '#{e}'"
                end
            end
        end
        acc.join
    else
        plain_text_recode(text)
    end
end

#plain_text_recode(text) ⇒ Object

Recode normal text for #plain_text



573
574
575
# File 'lib/deplate/formatter.rb', line 573

def plain_text_recode(text)
    text
end

#pre_processObject



608
609
# File 'lib/deplate/formatter.rb', line 608

def pre_process
end

#prelude(name) ⇒ Object



884
885
886
# File 'lib/deplate/formatter.rb', line 884

def prelude(name)
    @deplate.variables[name]
end

#prepareObject



611
612
# File 'lib/deplate/formatter.rb', line 611

def prepare
end

#ps2img(invoker, device, fps, fout, args) ⇒ Object



1120
1121
1122
1123
1124
1125
# File 'lib/deplate/formatter.rb', line 1120

def ps2img(invoker, device, fps, fout, args)
    if Deplate::External.ps2img(invoker, device, fps, fout, args) and @deplate.options.clean
        File.delete(fps)
        invoker.log(["Deleting", fps])
    end
end

#pstoedit_inlatexObject

Process inline latex. The file names of the output are saved as an array in invoker.elt.



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
# File 'lib/deplate/mod/pstoedit.rb', line 52

def inlatex(invoker)
    pkgs, body = inlatex_split(invoker.accum)
    id      = inlatex_id(invoker)
    sfx     = invoker.args['sfx'] || @deplate.variables['ltxSfx'] || inlatex_sfx
    currDir = Dir.pwd
    @deplate.in_working_dir do
        ftex    = id + '.tex'
        flog    = id + '.log'
        faux    = id + '.aux'
        fdvi    = id + '.dvi'
        fps     = id + '.ps'
        checkOW = true

        case sfx
        when 'ps'
            device  = nil
            fout    = fps
            checkOW = false
        when 'pdf'
            device  = 'pdfwrite'
            fout    = id + '.*.pdf'
        when 'jpeg', 'jpg'
            device  = 'jpeg'
            fout    = id + '.*.jpeg'
        when "png"
            device  = "png"
            fout    = id + ".png"
        else
            raise "Unknown device/suffix: #{sfx}"
        end

        pointsize = invoker.args['pointsize'] || 
            @deplate.variables['latexPointsize'] || '10'
        acc = [
            "\\documentclass[#{pointsize}pt,a4paper,notitlepage]{article}",
            "\\usepackage{amsmath}",
            "\\usepackage{amsfonts}",
            "\\usepackage{amssymb}",
            # "\\usepackage{mathabx}",
        ]
        acc += pkgs
        acc << "\\begin{document}" << "\\pagestyle{empty}"
        acc += body
        acc << "\\end{document}"

        if Deplate::Region.check_file(invoker, fout, ftex, acc)
            invoker.log(['Files exist! Using', fout], :anyway)
        else
            if checkOW and !@deplate.options.force
                for f in [ftex, flog, faux, fdvi, fout]
                    if !Dir[f].empty?
                        raise "Please delete '#{f}' or change the id before proceeding:\n#{invoker.accum.join("\n")}"
                    end
                end
            end

            acc = acc.join("\n")

            Deplate::External.write_file(invoker, ftex) {|io| io.puts(acc)}
            inlatex_process_latex(invoker, ftex, faux, flog)
            if block_given?
                yield(invoker, device, fdvi, fps, fout)
            else
                case device
                when "png"
                    inlatex_process_dvi_png(invoker, fdvi, fout) if File.exist?(fdvi)
                else
                    inlatex_process_dvi(invoker, fdvi, fps) if File.exist?(fdvi)
                    if device
                        inlatex_process_ps(invoker, device, fps, fout, invoker.args)
                    elsif fps != fout
                        File.rename(fps, fout)
                    end
                end
            end
        end

        invoker.elt = Dir[fout]
        if invoker.elt.empty?
            code = invoker.accum.join("\n")
            invoker.log(["Conversion if Inline LaTeX failed", code], :error)
        end
    end
end

#pstoedit_wrap(invoker, sfx, &block) ⇒ Object



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
# File 'lib/deplate/mod/pstoedit.rb', line 25

def pstoedit_wrap(invoker, sfx, &block)
    case sfx
    when 'sfx'
        sfx = nil
    when 'jpeg'
        sfx = 'jpg'
    else
        log(["Unhandled suffix, let's see how it works", sfx], :anyway)
    end
    if sfx
        begin
            invoker.args['sfx'] = 'ps'
            block.call(invoker)
            id   = inlatex_id(invoker, true)
            fps  = id + '.ps'
            fout = [id, '.', sfx].join
            args = @deplate.variables['pstoeditArgs']
            @deplate.in_working_dir do
                Deplate::External.pstoedit(invoker, fps, fout, args)
            end
            return fout
        ensure
            invoker.args['sfx'] = sfx
        end
    end
end

#push_class_option(*options) ⇒ Object

push *options to variables



424
425
426
427
428
429
# File 'lib/deplate/formatter.rb', line 424

def push_class_option(*options)
    acc = [@deplate.variables["classOptions"]]
    acc += options
    acc.compact!
    @deplate.variables["classOptions"] = acc.join(' ')
end

#push_linebreak(accum, part, add_blank = true) ⇒ Object



877
878
879
880
881
882
# File 'lib/deplate/formatter.rb', line 877

def push_linebreak(accum, part, add_blank=true)
    if part
        accum << ' ' if add_blank and /\s$/ !~ part
        accum << "\n"
    end
end

#read_bib(bibfiles) ⇒ Object



685
686
# File 'lib/deplate/formatter.rb', line 685

def read_bib(bibfiles)
end

#recode_startObject



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/deplate/mod/recode.rb', line 27

def recode_start
    unless defined?(@recode_encoding_source)
        @recode_encoding_source = @deplate.variables['encoding'] || "latin-1"
        @recode_encoding_target = @deplate.variables['recodeEncoding'] || "utf-8"
        @deplate.variables['encoding'] = @recode_encoding_target
    end
    unless @recode_io
        @recode_io = IO.popen("#{Deplate::External.get_app('recode')} -d #@recode_encoding_source..#@recode_encoding_target", "w+")
        @recode_io.sync = true
    end
end

#recode_stopObject



39
40
41
42
43
44
# File 'lib/deplate/mod/recode.rb', line 39

def recode_stop
    if @recode_io
        @recode_io.close
        @recode_io = nil
    end
end

#referenced_bib_entry(invoker, key, text) ⇒ Object



698
699
700
# File 'lib/deplate/formatter.rb', line 698

def referenced_bib_entry(invoker, key, text)
    text
end

#reset!Object



158
159
160
161
162
163
# File 'lib/deplate/formatter.rb', line 158

def reset!
    @bibentries      = {}
    @open_labels     = []
    # @consumed_labels = []
    # @consumed_ids    = []
end

#retrieve_particle(id, body = nil, specific = false) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
# File 'lib/deplate/formatter.rb', line 179

def retrieve_particle(id, body=nil, specific=false)
    fmt       = specific ? formatter_name : '_'
    particles = @@custom_particles[fmt] ||= {}
    particle  = particles[id]
    if particle
        if body.nil? or particle[:body] == body
            return particle[:class]
        end
    end
    return nil
end

#set_at(type, slot, *body) ⇒ Object

def_delegator(:@deplate, :set_at)



419
420
421
# File 'lib/deplate/formatter.rb', line 419

def set_at(type, slot, *body)
    @deplate.output.set_at(type, slot, *body)
end

#setupObject



605
606
# File 'lib/deplate/formatter.rb', line 605

def setup
end

#setup_endnotesObject



11
12
13
# File 'lib/deplate/mod/endnotes.rb', line 11

def setup_endnotes
    @deplate.set_slot_name(:footnotes, false)
end

#setup_entitiesObject



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/deplate/formatter.rb', line 463

def setup_entities
    unless @entities_table
        @entities_table = []
        enc  = canonic_encoding()
        ents = Deplate::Core.split_list(@deplate.variables['entities'] || 'general')
        for d in Deplate::Core.library_directories(@deplate.vanilla, true, ['ents'])
            for pre in self.class.formatter_family_members << nil
                for ent in ents
                    f = File.join(d, '%s-%s.entities' % [ent, [pre, enc].compact.join('_')])
                    if File.readable?(f)
                        @entities_table = File.readlines(f).map do |line|
                            line.chomp.split(/\t/)
                        end
                    end
                end
            end
        end
    end
end

#singlequote_close(invoker) ⇒ Object



542
543
544
545
# File 'lib/deplate/formatter.rb', line 542

def singlequote_close(invoker)
    check_symbol_proxy
    @symbol_proxy.singlequote_close(invoker)
end

#singlequote_open(invoker) ⇒ Object



537
538
539
540
# File 'lib/deplate/formatter.rb', line 537

def singlequote_open(invoker)
    check_symbol_proxy
    @symbol_proxy.singlequote_open(invoker)
end

#sort_index_entries(data) ⇒ Object

Return the alphabethically sorted index data. def sort_index_entries(data)

return data.sort do |a,b|
    aa = get_first_char(a, true)
    bb = get_first_char(b, true)
    aa <=> bb
end

end



775
776
777
# File 'lib/deplate/formatter.rb', line 775

def sort_index_entries(data)
    return data.sort {|a,b| a[0].upcase <=> b[0].upcase}
end

#stepwise_nextObject



1217
1218
1219
1220
# File 'lib/deplate/formatter.rb', line 1217

def stepwise_next
    stepwise_prepare
    @deplate.output.attributes[:stepwiseIdx] += 1
end

#stepwise_prepareObject

<TBD> def_service(‘format’) do |args, text|

id = args['id'] || text
# o  = @variables[id]
o  = object_by_id(id)
if o
    o.format_as_string
end

end



1213
1214
1215
# File 'lib/deplate/formatter.rb', line 1213

def stepwise_prepare
    # @deplate.output.attributes[:stepwiseIdx] ||= 0
end

#store_particle(id, body, particle, specific = false) ⇒ Object



191
192
193
194
195
# File 'lib/deplate/formatter.rb', line 191

def store_particle(id, body, particle, specific=false)
    fmt           = specific ? formatter_name : '_'
    particles     = @@custom_particles[fmt] ||= {}
    particles[id] = {:body => body, :class => particle}
end

#suffixObject



593
594
595
# File 'lib/deplate/formatter.rb', line 593

def suffix
    self.class.suffix
end

#symbol_amp(invoker) ⇒ Object



522
523
524
525
# File 'lib/deplate/formatter.rb', line 522

def symbol_amp(invoker)
    check_symbol_proxy
    @symbol_proxy.symbol_amp(invoker)
end

#symbol_gt(invoker) ⇒ Object



512
513
514
515
# File 'lib/deplate/formatter.rb', line 512

def symbol_gt(invoker)
    check_symbol_proxy
    @symbol_proxy.symbol_gt(invoker)
end

#symbol_lt(invoker) ⇒ Object



517
518
519
520
# File 'lib/deplate/formatter.rb', line 517

def symbol_lt(invoker)
    check_symbol_proxy
    @symbol_proxy.symbol_lt(invoker)
end

#symbol_paragraph(invoker) ⇒ Object



552
553
554
555
# File 'lib/deplate/formatter.rb', line 552

def symbol_paragraph(invoker)
    check_symbol_proxy
    @symbol_proxy.symbol_paragraph(invoker)
end

#symbol_quote(invoker) ⇒ Object



507
508
509
510
# File 'lib/deplate/formatter.rb', line 507

def symbol_quote(invoker)
    check_symbol_proxy
    @symbol_proxy.symbol_quote(invoker)
end

#table_empty_cellObject



791
792
793
# File 'lib/deplate/formatter.rb', line 791

def table_empty_cell
    ''
end

#table_row_size(elt) ⇒ Object

Return the maximum row size for the table data in elt.



780
781
782
783
784
785
786
787
788
789
# File 'lib/deplate/formatter.rb', line 780

def table_row_size(elt)
    max = 0
    for row in elt
        i = row.cols.size
        if i > max
            max = i
        end
    end
    max
end

#union_at(type, slot, *body) ⇒ Object

def_delegator(:@deplate, :union_at)



414
415
416
# File 'lib/deplate/formatter.rb', line 414

def union_at(type, slot, *body)
    @deplate.output.union_at(type, slot, *body)
end

#with_agent(agent, prototype, invoker, *args) ⇒ Object



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
# File 'lib/deplate/formatter.rb', line 329

def with_agent(agent, prototype, invoker, *args)
    log(["Call with agent", agent, invoker.class, args], :debug)
    if respond_to?(agent)
        before  = []
        inner   = nil
        after   = []
        stylish = @advices[agent]
        if stylish
            # pre = stylish[:before]
            # if pre
                # for advice in pre
                    # before << advice[:prc].call(invoker, *args)
                # end
            # end
            
            inner = self.send(agent, invoker, *args)
            prototype ||= inner.class
            around = stylish[:wrap]
            if around
                inner = around.inject(inner) do |acc, advice|
                    advice[:prc].call(agent, acc, invoker, *args)
                end
            end
            
            # post  = stylish[:after]
            # if post
                # for advice in post
                    # after << advice[:prc].call(invoker, *args)
                # end
            # end
        else
            args  = args.unshift(invoker)
            begin
                inner = self.send(agent, *args)
            rescue Exception => e
                log("We shouldn't be here. If you can track down when this happens, please send an example to the author.", :error)
                puts "DBG: #{agent}: #{e}"
                puts e.backtrace[0..10].join("\n")
                # raise e
                return nil
            end
            prototype ||= inner.class
        end
        # if prototype == String
            # rv = [before, inner, after].join
        # elsif prototype == Integer
            # rv = [before, inner, after].join.to_i
        # elsif inner.kind_of?(Array)
            # rv = before + inner + after
        # else
            # rv = before + [inner] + after
        # end
        # return rv
        return inner
    else
        invoker.log(['Unknown formatting agent', agent], :error)
        return nil
    end
end

#wrap_text(text, args = {}) ⇒ Object

Takes an optional block that takes a string as argument and returns true if we shouldn’t wrap the text at this position



797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
# File 'lib/deplate/formatter.rb', line 797

def wrap_text(text, args={})
    margin = args[:margin] || (wm = @deplate.variables['wrapMargin'] and wm.to_i) || 72
    return text if margin == 0
    moreIndent = args[:indent]  || ''
    hanging    = args[:hanging] || 0
    hang_idt   = ' ' * hanging
    block      = args[:check]
    break_at   = args[:break_at]
    acc = []
    rx = /(\n|[[:space:]#{break_at}]+)/
    text.each do |text|
        # if text.kind_of?(Array)
        #     log("We shouldn't be here. If you can track down when this happens, please send an example to the author.", :error)
        #     puts caller[0..10].join("\n")
        #     return ''
        # elsif /^\s+$/ =~ text
        if /^\s*$/ =~ text
            acc << nil
            next
        else
            m     = /^(\s*)(.*)$/.match(text.chomp)
            accum = [m[1]]
            idt   = m[1] + moreIndent + hang_idt
            marg  = margin - idt.size
            lmar  = 0
            pos0  = 0
            col0  = 0
            line  = m[2]
            scanner = StringScanner.new(line)
            mpos = scanner.skip_until(rx)
            while mpos
                pos = scanner.pos
                col = pos - lmar
                part = line[lmar, col - scanner.matched_size]
                good = !(block and block.call(part))
                if col - scanner.matched_size > marg and good
                    accum << idt unless lmar == 0
                    if pos0 == lmar
                        part = line[lmar, col]
                        accum << part
                        push_linebreak(accum, part)
                        lmar = pos
                        mpos = scanner.skip_until(rx)
                    else
                        part = line[lmar, col0]
                        accum << part
                        push_linebreak(accum, part)
                        lmar = pos0
                        next
                    end
                else
                    mpos = scanner.skip_until(rx)
                end
                if good
                    pos0 = pos
                    col0 = col
                end
            end
            part = line[lmar, col0]
            # if /\S/ =~ part
                accum << idt unless lmar == 0
                # p "DBG wrap_text", line
                # p !(block and block.call(part))
                if line.size - lmar - 1 > marg and pos0 != lmar and !(block and block.call(part))
                    # p "DBG1", part
                    accum << part
                    push_linebreak(accum, part)
                    accum << idt << line[pos0, line.size - pos0]
                else
                    part = line[lmar, line.size - lmar]
                    # p "DBG2", part
                    accum << part
                end
            # end
            acc << accum.join
        end
        end
    return acc.join("\n")
end