Module: YARD::Templates::Helpers::HtmlHelper

Includes:
HtmlSyntaxHighlightHelper, MarkupHelper
Defined in:
lib/yard/templates/helpers/html_helper.rb

Overview

The helper module for HTML templates.

Constant Summary

Constants included from MarkupHelper

MarkupHelper::MARKUP_EXTENSIONS, MarkupHelper::MARKUP_FILE_SHEBANG, MarkupHelper::MARKUP_PROVIDERS

Escaping Template Data collapse

Converting Markup to HTML collapse

Syntax Highlighting Source Code collapse

Linking Objects and URLs collapse

URL Helpers collapse

Formatting Objects and Attributes collapse

Getting the Character Encoding collapse

Methods included from HtmlSyntaxHighlightHelper

#html_syntax_highlight_ruby

Methods included from MarkupHelper

clear_markup_cache, #load_markup_provider, #markup_class, #markup_file_contents, #markup_for_file, #markup_provider

Instance Method Details

#anchor_for(object) ⇒ String

Returns the anchor for a specific object.

Parameters:

Returns:

  • (String)

    the anchor for a specific object


250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/yard/templates/helpers/html_helper.rb', line 250

def anchor_for(object)
  case object
  when CodeObjects::MethodObject
    "#{object.name}-#{object.scope}_#{object.type}"
  when CodeObjects::ClassVariableObject
    "#{object.name.to_s.gsub('@@', '')}-#{object.type}"
  when CodeObjects::Base
    "#{object.name}-#{object.type}"
  when CodeObjects::Proxy
    object.path
  else
    object.to_s
  end
end

#charsetString

Returns the current character set. The default value can be overridden by setting the LANG environment variable or by overriding this method. In Ruby 1.9 you can also modify this value by setting Encoding.default_external.

Returns:

  • (String)

    the current character set

Since:

  • 0.5.4


432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/yard/templates/helpers/html_helper.rb', line 432

def charset
  return 'utf-8' unless RUBY19 || lang = ENV['LANG']
  if RUBY19
    lang = Encoding.default_external.name.downcase
  else
    lang = lang.downcase.split('.').last
  end
  case lang
  when "ascii-8bit", "us-ascii", "ascii-7bit"; 'iso-8859-1'
  else; lang
  end
end

#fix_dash_dash(text) ⇒ Object

TODO:

Refactor into own SimpleMarkup subclass

Don't allow – to turn into — element. The chances of this being some –option is far more likely than the typographical meaning.


129
130
131
# File 'lib/yard/templates/helpers/html_helper.rb', line 129

def fix_dash_dash(text)
  text.gsub(/—(?=\S)/, '--')
end

#fix_typewriter(text) ⇒ Object

TODO:

Refactor into own SimpleMarkup subclass

Fixes RDoc behaviour with ++ only supporting alphanumeric text.


113
114
115
116
117
118
119
120
121
122
123
# File 'lib/yard/templates/helpers/html_helper.rb', line 113

def fix_typewriter(text)
  text.gsub(/(\s|^|>)\+(?! )([^\n\+]{1,900})(?! )\+/) do
    first_text, type_text, pre_text, no_match = $1, $2, $`, $&
    pre_match = (pre_text+first_text).scan(%r(</?(?:(?:pre|tt|code).*?>|[^>]+)\Z))
    if pre_match.last.nil? || pre_match.last[1,1] == '/'
      first_text + '<tt>' + h(type_text) + '</tt>'
    else
      no_match
    end
  end
end

#format_object_name_list(objects) ⇒ String

Formats a list of objects and links them

Returns:

  • (String)

    a formatted list of objects


323
324
325
326
327
# File 'lib/yard/templates/helpers/html_helper.rb', line 323

def format_object_name_list(objects)
  objects.sort_by {|o| o.name.to_s.downcase }.map do |o| 
    "<span class='name'>" + linkify(o, o.name) + "</span>" 
  end.join(", ")
end

#format_types(typelist, brackets = true) ⇒ String

Formats a list of types from a tag.

Parameters:

  • typelist (Array<String>, FalseClass)

    the list of types to be formatted.

  • brackets (Boolean) (defaults to: true)

    omits the surrounding brackets if brackets is set to false.

Returns:

  • (String)

    the list of types formatted as [Type1, Type2, …] with the types linked to their respective descriptions.


341
342
343
344
345
346
347
348
349
# File 'lib/yard/templates/helpers/html_helper.rb', line 341

def format_types(typelist, brackets = true)
  return unless typelist.is_a?(Array)
  list = typelist.map do |type| 
    type = type.gsub(/([<>])/) { h($1) }
    type = type.gsub(/([\w:]+)/) { $1 == "lt" || $1 == "gt" ? $1 : linkify($1, $1) }
    "<tt>" + type + "</tt>"
  end
  list.empty? ? "" : (brackets ? "(#{list.join(", ")})" : list.join(", "))
end

#h(text) ⇒ String

Escapes HTML entities

Parameters:

  • text (String)

    the text to escape

Returns:

  • (String)

    the HTML with escaped entities


16
17
18
# File 'lib/yard/templates/helpers/html_helper.rb', line 16

def h(text)
  CGI.escapeHTML(text.to_s)
end

#html_markup_html(text) ⇒ String

Converts HTML to HTML

Parameters:

  • text (String)

    input html

Returns:

Since:

  • 0.6.0


101
102
103
# File 'lib/yard/templates/helpers/html_helper.rb', line 101

def html_markup_html(text)
  text
end

#html_markup_markdown(text) ⇒ String

Converts Markdown to HTML

Parameters:

  • text (String)

    input Markdown text

Returns:

Since:

  • 0.6.0


60
61
62
63
# File 'lib/yard/templates/helpers/html_helper.rb', line 60

def html_markup_markdown(text)
  # TODO: other libraries might be more complex
  markup_class(:markdown).new(text).to_html
end

#html_markup_rdoc(text) ⇒ String

Converts RDoc formatting (SimpleMarkup) to HTML

Parameters:

  • text (String)

    the input RDoc formatted text

Returns:

Since:

  • 0.6.0


79
80
81
82
83
84
85
86
87
# File 'lib/yard/templates/helpers/html_helper.rb', line 79

def html_markup_rdoc(text)
  begin
    simple_markup_html.instance_variable_set("@from_path", url_for(object))
    html = markup_class(:rdoc).new.convert(text, simple_markup_html)
  end

  html = fix_dash_dash(html)
  html = fix_typewriter(html)
end

#html_markup_text(text) ⇒ String

Converts plaintext to HTML

Parameters:

  • text (String)

    the input text

Returns:

  • (String)

    the output HTML

Since:

  • 0.6.0


93
94
95
# File 'lib/yard/templates/helpers/html_helper.rb', line 93

def html_markup_text(text)
  "<pre>" + text + "</pre>"
end

#html_markup_textile(text) ⇒ String

Converts Textile to HTML

Parameters:

  • text (String)

    the input Textile text

Returns:

Since:

  • 0.6.0


69
70
71
72
73
# File 'lib/yard/templates/helpers/html_helper.rb', line 69

def html_markup_textile(text)
  doc = markup_class(:textile).new(text)
  doc.hard_breaks = false if doc.respond_to?(:hard_breaks=)
  doc.to_html
end

#html_syntax_highlight(source, type = nil) ⇒ String

Note:

To support a specific language type, implement the method html_syntax_highlight_TYPE in this class.

Syntax highlights source in language type.

Parameters:

  • source (String)

    the source code to highlight

  • type (Symbol) (defaults to: nil)

    the language type (:ruby, :plain, etc). Use :plain for no syntax highlighting.

Returns:

  • (String)

    the highlighted source


144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/yard/templates/helpers/html_helper.rb', line 144

def html_syntax_highlight(source, type = nil)
  return "" unless source
  return h(source) if options[:no_highlight]

  type ||= object.source_type || :ruby

  # handle !!!LANG prefix to send to html_syntax_highlight_LANG
  if source =~ /\A(?:[ \t]*\r?\n)?[ \t]*!!!([\w.+-]+)[ \t]*\r?\n/
    type, source = $1, $'
    source = $'
  end
  
  meth = "html_syntax_highlight_#{type}"
  respond_to?(meth) ? send(meth, source) : h(source)
end

#html_syntax_highlight_plain(source) ⇒ String

Returns unhighlighted source.

Returns:

  • (String)

    unhighlighted source


161
162
163
# File 'lib/yard/templates/helpers/html_helper.rb', line 161

def html_syntax_highlight_plain(source)
  h(source)
end

#htmlify(text, markup = options[:markup]) ⇒ String

Turns text into HTML using markup style formatting.

Parameters:

  • text (String)

    the text to format

  • markup (Symbol) (defaults to: options[:markup])

    examples are :markdown, :textile, :rdoc. To add a custom markup type, see MarkupHelper

Returns:


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/yard/templates/helpers/html_helper.rb', line 36

def htmlify(text, markup = options[:markup])
  markup_meth = "html_markup_#{markup}"
  return text unless respond_to?(markup_meth)
  return "" unless text
  return text unless markup
  load_markup_provider(markup)
  html = send(markup_meth, text)
  if html.respond_to?(:encode)
    html = html.force_encoding(text.encoding) # for libs that mess with encoding
    html = html.encode(:invalid => :replace, :replace => '?')
  end
  html = resolve_links(html)
  html = html.gsub(/<pre>(?:\s*<code>)?(.+?)(?:<\/code>\s*)?<\/pre>/m) do
    str = $1
    str = html_syntax_highlight(CGI.unescapeHTML(str)) unless options[:no_highlight]
    %Q{<pre class="code">#{str}</pre>}
  end unless markup == :text
  html
end

#htmlify_line(*args) ⇒ String

Returns HTMLified text as a single line (paragraphs removed).

Returns:

  • (String)

    HTMLified text as a single line (paragraphs removed)


106
107
108
# File 'lib/yard/templates/helpers/html_helper.rb', line 106

def htmlify_line(*args)
  "<div class='inline'>" + htmlify(*args) + "</div>"
end

Links to an extra file

Parameters:

  • filename (String)

    the filename to link to

  • title (String) (defaults to: nil)

    the title of the link

  • anchor (String) (defaults to: nil)

    optional anchor

Returns:

  • (String)

    the link to the file

Since:

  • 0.5.5


205
206
207
# File 'lib/yard/templates/helpers/html_helper.rb', line 205

def link_file(filename, title = nil, anchor = nil)
  link_url(url_for_file(filename, anchor), title)
end

Includes an object's docstring into output.

Parameters:

Returns:

  • (String)

    the object's docstring (no tags)

Since:

  • 0.6.0


210
211
212
# File 'lib/yard/templates/helpers/html_helper.rb', line 210

def link_include_object(obj)
  htmlify(obj.docstring)
end

Links to an object with an optional title

Parameters:

Returns:

  • (String)

    the linked object


215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/yard/templates/helpers/html_helper.rb', line 215

def link_object(obj, otitle = nil, anchor = nil, relative = true)
  return otitle if obj.nil?
  obj = Registry.resolve(object, obj, true, true) if obj.is_a?(String)
  if !otitle && obj.root?
    title = "Top Level Namespace"
  elsif otitle
    title = otitle.to_s
  elsif object.is_a?(CodeObjects::Base)
    title = h(object.relative_path(obj))
  else
    title = h(obj.to_s)
  end
  return title unless serializer
  return title if obj.is_a?(CodeObjects::Proxy)
        
  link = url_for(obj, anchor, relative)
  link = link ? link_url(link, title, :title => "#{obj.path} (#{obj.type})") : title
  "<span class='object_link'>" + link + "</span>"
end

Links to a URL

Parameters:

  • url (String)

    the URL to link to

  • title (String) (defaults to: nil)

    the optional title to display the link as

  • params (Hash) (defaults to: {})

    optional parameters for the link

Returns:


236
237
238
239
240
241
242
243
244
# File 'lib/yard/templates/helpers/html_helper.rb', line 236

def link_url(url, title = nil, params = {})
  title ||= url
  params = SymbolHash.new(false).update(
    :href => url,
    :title  => h(title)
  ).update(params)
  params[:target] ||= '_parent' if url =~ /^(\w+):\/\//
  "<a #{tag_attrs(params)}>#{title}</a>"
end

Resolves any text in the form of {Name} to the object specified by Name. Also supports link titles in the form {Name title}.

Examples:

Linking to an instance method

resolve_links("{MyClass#method}") # => "<a href='...'>MyClass#method</a>"

Linking to a class with a title

resolve_links("{A::B::C the C class}") # => "<a href='...'>the c class</a>"

Parameters:

  • text (String)

    the text to resolve links in

Returns:

  • (String)

    HTML with linkified references


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
# File 'lib/yard/templates/helpers/html_helper.rb', line 176

def resolve_links(text)
  code_tags = 0
  text.gsub(/<(\/)?(pre|code|tt)|\{(\S+?)(?:\s(.*?\S))?\}(?=[\W<]|.+<\/|$)/) do |str|
    closed, tag, name, title, match = $1, $2, $3, $4, $&
    if tag
      code_tags += (closed ? -1 : 1)
      next str
    end
    next str unless code_tags == 0
    
    next(match) if name[0,1] == '|'
    if object.is_a?(String)
      object
    else
      link = linkify(name, title)
      if link == name || link == title
        match = /(.+)?(\{#{Regexp.quote name}(?:\s.*?)?\})(.+)?/.match(text)
        file = (@file ? @file : object.file) || '(unknown)'
        line = (@file ? 1 : (object.docstring.line_range ? object.docstring.line_range.first : 1)) + (match ? $`.count("\n") : 0)
        log.warn "In file `#{file}':#{line}: Cannot resolve link to #{name} from text" + (match ? ":" : ".")
        log.warn((match[1] ? '...' : '') + match[2].gsub("\n","") + (match[3] ? '...' : '')) if match
      end
      
      link
    end
  end
end

#signature(meth, link = true, show_extras = true, full_attr_name = true) ⇒ String

Formats the signature of method meth.

Parameters:

  • meth (CodeObjects::MethodObject)

    the method object to list the signature of

  • link (Boolean) (defaults to: true)

    whether to link the method signature to the details view

  • show_extras (Boolean) (defaults to: true)

    whether to show extra meta-data (visibility, attribute info)

  • full_attr_name (Boolean) (defaults to: true)

    whether to show the full attribute name (“name=” instead of “name”)

Returns:

  • (String)

    the formatted method signature


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
# File 'lib/yard/templates/helpers/html_helper.rb', line 391

def signature(meth, link = true, show_extras = true, full_attr_name = true)
  meth = convert_method_to_overload(meth)
  
  type = signature_types(meth, link)
  scope = meth.scope == :class ? "+" : "-"
  name = full_attr_name ? meth.name : meth.name.to_s.gsub(/^(\w+)=$/, '\1')
  blk = format_block(meth)
  args = !full_attr_name && meth.writer? ? "" : format_args(meth)
  extras = []
  extras_text = ''
  if show_extras
    if rw = meth.attr_info
      attname = [rw[:read] ? 'read' : nil, rw[:write] ? 'write' : nil].compact
      attname = attname.size == 1 ? attname.join('') + 'only' : nil
      extras << attname if attname
    end
    extras << meth.visibility if meth.visibility != :public
    extras_text = ' <span class="extras">(' + extras.join(", ") + ')</span>' unless extras.empty?
  end
  title = "%s %s<strong>%s</strong>%s %s" % [scope, type, h(name), args, blk]
  if link
    if meth.is_a?(YARD::CodeObjects::MethodObject)
      link_title = "#{h meth.name(true)} (#{meth.scope} #{meth.type})"
    else
      link_title = "#{h name} (#{meth.type})"
    end
    link_url(url_for(meth), title, :title => link_title) + extras_text
  else
    title + extras_text
  end
end

#signature_types(meth, link = true) ⇒ String

Get the return types for a method signature.

Parameters:

Returns:

  • (String)

    the signature types

Since:

  • 0.5.3


357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/yard/templates/helpers/html_helper.rb', line 357

def signature_types(meth, link = true)
  meth = convert_method_to_overload(meth)

  type = options[:default_return] || ""
  if meth.tag(:return) && meth.tag(:return).types
    types = meth.tags(:return).map {|t| t.types ? t.types : [] }.flatten.uniq
    first = link ? h(types.first) : format_types([types.first], false)
    if types.size == 2 && types.last == 'nil'
      type = first + '<sup>?</sup>'
    elsif types.size == 2 && types.last =~ /^(Array)?<#{Regexp.quote types.first}>$/
      type = first + '<sup>+</sup>'
    elsif types.size > 2
      type = [first, '...'].join(', ')
    elsif types == ['void'] && options[:hide_void_return]
      type = ""
    else
      type = link ? h(types.join(", ")) : format_types(types, false)
    end
  elsif !type.empty?
    type = link ? h(type) : format_types([type], false)
  end
  type = "(#{type}) " unless type.empty?
  type
end

#url_for(obj, anchor = nil, relative = true) ⇒ String

Returns the URL for an object.

Parameters:

  • obj (String, CodeObjects::Base)

    the object (or object path) to link to

  • anchor (String) (defaults to: nil)

    the anchor to link to

  • relative (Boolean) (defaults to: true)

    use a relative or absolute link

Returns:

  • (String)

    the URL location of the object


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
# File 'lib/yard/templates/helpers/html_helper.rb', line 271

def url_for(obj, anchor = nil, relative = true)
  link = nil
  return link unless serializer
  
  if obj.is_a?(CodeObjects::Base) && !obj.is_a?(CodeObjects::NamespaceObject)
    # If the obj is not a namespace obj make it the anchor.
    anchor, obj = obj, obj.namespace
  end
  
  objpath = serializer.serialized_path(obj)
  return link unless objpath

  if relative
    fromobj = object
    if object.is_a?(CodeObjects::Base) && 
        !object.is_a?(CodeObjects::NamespaceObject)
      fromobj = fromobj.namespace
    end

    from = serializer.serialized_path(fromobj)
    link = File.relative_path(from, objpath)
  else
    link = objpath
  end

  link + (anchor ? '#' + urlencode(anchor_for(anchor)) : '')
end

#url_for_file(filename, anchor = nil) ⇒ String

Returns the URL for a specific file

Parameters:

  • filename (String)

    the filename to link to

  • anchor (String) (defaults to: nil)

    optional anchor

Returns:

  • (String)

    the URL pointing to the file


304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/yard/templates/helpers/html_helper.rb', line 304

def url_for_file(filename, anchor = nil)
  fromobj = object
  if CodeObjects::Base === fromobj && !fromobj.is_a?(CodeObjects::NamespaceObject)
    fromobj = fromobj.namespace
  end
  from = serializer.serialized_path(fromobj)
  if filename == options[:readme]
    filename = 'index'
  else
    filename = 'file.' + File.basename(filename).gsub(/\.[^.]+$/, '')
  end
  link = File.relative_path(from, filename)
  link + '.html' + (anchor ? '#' + urlencode(anchor) : '')
end

#urlencode(text) ⇒ String

Escapes a URL

Parameters:

Returns:

  • (String)

    the escaped URL


24
25
26
# File 'lib/yard/templates/helpers/html_helper.rb', line 24

def urlencode(text)
  CGI.escape(text.to_s)
end