class PlainText::Part

Class to represent a Chapter-like entity like an Array

An instance of this class contains always an even number of elements, either another {Part} instance or {Paragraph}-type String-like instance, followed by a {Boundary}-type String-like instance. The first element is always a former and the last element is always a latter.

Essentially, the instance of this class holds the order information between sub-{Part}-s (< Array) and/or {Paragraph}-s (< String) and {Boundary}-s (< String).

An example instance looks like this:

Part (
  (0) Paragraph::Empty,
  (1) Boundary::General,
  (2) Part::ArticleHeader(
        (0) Paragraph::Title,
        (1) Boundary::Empty
      ),
  (3) Boundary::TitleMain,
  (4) Part::ArticleMain(
        (0) Part::ArticleSection(
              (0) Paragraph::Title,
              (1) Boundary::General,
              (2) Paragraph::General,
              (3) Boundary::General,
              (4) Part::ArticleSubSection(...),
              (5) Boundary::General,
              (6) Paragraph::General,
              (7) Boundary::Empty
            ),
        (1) Boundary::General,
        (2) Paragraph::General,
        (3) Boundary::Empty
      ),
  (5) Boundary::General
)

A Section (Part) always has an even number of elements: pairs of a Para ({Part}|{Paragraph}) and {Boundary} in this order.

Note some standard destructive Array operations, most notably #delete, #delete_if, #reject!, #select!, #filter!, #keep_if, #flatten!, #uniq! may alter the content in a way it breaks the self-inconsistency of the object. Use it at your own risk, if you wish (or don't).

An instance of this class is always non-equal to that of the standard Array class. To compare it at the Array level, convert a {Part} class instance into Array with to_a first and compare them.

For CRUD of elements (contents) of an instance, the following methods are most basic:

@author Masa Sakano (Wise Babel Ltd)

@todo methods

* flatten
* SAFE level  for command-line tools?

Constants

ERR_MSGS

Error messages

Public Class Methods

new(arin, boundaries=nil, recursive: true, compact: true, compacter: true) click to toggle source

@param arin [Array] of [Paragraph1, Boundary1, Para2, Bd2, …] or just Paragraphs if boundaries is given as the second arguments @param boundaries [Array] of Boundary @option recursive: [Boolean] if true (Default), normalize recursively. @option compact: [Boolean] if true (Default), pairs of nil paragraph and boundary are removed. Otherwise, nil is converted to an empty string. @option compacter: [Boolean] if true (Default), pairs of nil or empty paragraph and boundary are removed. @return [self]

Calls superclass method
# File lib/plain_text/part.rb, line 91
def initialize(arin, boundaries=nil, recursive: true, compact: true, compacter: true)
  if !boundaries
    super(arin)
  else

    armain = []
    arin.each_with_index do |ea_e, i|
      armain << ea_e
      armain << (boundaries[i] || Boundary.new(''))
    end
    super armain
  end
  normalize!(recursive: recursive, compact: compact, compacter: compacter)
end
parse(inprm, rule: PlainText::ParseRule::RuleConsecutiveLbs) click to toggle source

Parses a given string (or {Part}) and returns this class of instance.

@param inprm [String, Array, Part] @option rule: [PlainText::ParseRule] @return [PlainText::Part]

# File lib/plain_text/part.rb, line 111
def self.parse(inprm, rule: PlainText::ParseRule::RuleConsecutiveLbs)
  arin = rule.apply(inprm)
  self.new(arin)
end

Public Instance Methods

+(other) click to toggle source

Plus operator

@param other [Object] @return as self

Calls superclass method
# File lib/plain_text/part.rb, line 603
def +(other)
  # ## The following is strict, but a bit redundant.
  # # is_para = true  # Whether "other" is a Part class instance.
  # # %i(to_ary paras boundaries).each do |ea_m|  # %i(...) defined in Ruby 2.0 and later
  # #   is_para &&= other.class.method_defined?(ea_m)
  # # end

  # begin
  #   other_even_odd =
  #     ([other.paras, other.boundaries] rescue even_odd_arrays(self, size_even: true, filler: ""))
  # rescue NoMethodError
  #   raise TypeError, sprintf("no implicit conversion of %s into %s", other.class.name, self.class.name)
  # end

  # # eg., if self is PlainText::Part::Section, the returned object is the same.
  # ret = self.class.new(self.paras+other_even_odd[0], self.boundaries+other_even_odd[1])
  ret = self.class.new super
  ret.normalize!
end
-(other) click to toggle source

Minus operator

@param other [Object] @return as self

Calls superclass method
# File lib/plain_text/part.rb, line 628
def -(other)
  ret = self.class.new super
  ret.normalize!
end
==(other) click to toggle source

Equal operator

Unless both are kind of Part instances, false is returned. If you want to make comparison in the Array level, do

p1.to_a == a1.to_a

@param other [Object]

Calls superclass method Array#==
# File lib/plain_text/part.rb, line 581
def ==(other)
  return false if !other.class.method_defined?(:to_ary)
  %i(paras boundaries).each do |ea_m|  # %i(...) defined in Ruby 2.0 and later
    return false if !other.class.method_defined?(ea_m) || (self.public_send(ea_m) != other.public_send(ea_m))  # public_send() defined in Ruby 2.0 (1.9?) and later
  end
  super
end
[](arg1, *rest) click to toggle source

Returns a partial Part-Array (or Object, if a single Integer is specified)

Because the returned object is this class of instance (when a pair of Integer or Range is specified), only an even number of elements, starting from an even number of index, is allowed.

@param arg1 [Integer, Range] @option arg2 [Integer, NilClass] @return [Object]

Calls superclass method
# File lib/plain_text/part.rb, line 650
def [](arg1, *rest)
  arg2 = rest[0]
  return super(arg1) if !arg2 && !arg1.class.method_defined?(:exclude_end?)

  check_bracket_args_type_error(arg1, arg2)  # Args are now either (Int, Int) or (Range)

  if arg2
    size2ret = size2extract(arg1, arg2, ignore_error: true)  # maybe nil (if the index is too small).
    raise ArgumentError, ERR_MSGS[:even_num]+" "+ERR_MSGS[:use_to_a] if size2ret.odd?
    begin
      raise ArgumentError, "odd index is not allowed as the starting index for #{self.class.name}.  It must be even. "+ERR_MSGS[:use_to_a] if positive_array_index_checked(arg1, self).odd?
    rescue TypeError, IndexError
      # handled by super
    end
    return super
  end

  begin
    rang = normalize_index_range(arg1)
  rescue IndexError #=> err
    return nil
    # raise RangeError, err.message
  end

  raise RangeError if rang.begin < 0 || rang.end < 0

  # The end is smaller than the begin in the positive index.  Empty instance of this class is returned.
  if rang.end < rang.begin
    return super
  end

  raise RangeError, "odd index is not allowed as the starting Range for #{sefl.class.name}.  It must be even. "+ERR_MSGS[:use_to_a] if rang.begin.odd?
  size2ret = size2extract(rang, skip_renormalize: true)
  raise ArgumentError, ERR_MSGS[:even_num]+" "+ERR_MSGS[:use_to_a] if size2ret.odd?
  super
end
Also aliased as: slice
[]=(arg1, *rest) click to toggle source

Replaces some of the Array content.

@param arg1 [Integer, Range] @option arg2 [Integer, NilClass] @return [Object]

Calls superclass method
# File lib/plain_text/part.rb, line 693
def []=(arg1, *rest)
  if rest.size == 1
    arg2, val = [nil, rest[-1]]
  else
    arg2, val = rest
  end

  # Simple substitution to a single element
  return super(arg1, val) if !arg2 && !arg1.class.method_defined?(:exclude_end?)

  check_bracket_args_type_error(arg1, arg2)  # Args are now either (Int, Int) or (Range)

  # raise TypeError, "object to replace must be Array type with an even number of elements." if !val.class.method_defined?(:to_ary) || val.size.odd?

  vals = (val.to_ary rescue [val])
  if arg2
    size2delete = size2extract(arg1, arg2, ignore_error: true)  # maybe nil (if the index is too small).
    raise ArgumentError, "odd-even parity of size of array to replace must be identical to that to slice." if size2delete && ((size2delete % 2) != (vals.size % 2))
    return super
  end

  begin
    rang = normalize_index_range(arg1)
  rescue IndexError => err
    raise RangeError, err.message
  end

  raise RangeError if rang.begin < 0 || rang.end < 0

  # The end is smaller than the begin in the positive index.  It is the same as insert (default in Ruby), except it returns the replaced Object (which may not be an Array).
  if rang.end < rang.begin
    insert(arg1, *vals)
    return val
  end

  size2delete = size2extract(rang, skip_renormalize: true)
  raise ArgumentError, "odd-even parity of size of array to replace must be identical to that to slice." if size2delete && ((size2delete % 2) != (vals.size % 2))
  ret = super

  # The result may not be in an even number anymore.  Correct it.
  Boundary.insert_original_b4_part(size, "") if size.odd?

  # Original method may fill some elements of the array with String or even nil.
  normalize!
  ret
end
append(*rest)

{#append} is an alias to {#push}

Alias for: push
boundaries() click to toggle source

Returns an array of boundaries (odd-number-index elements), consisting of Boundaries

@return [Array<Boundary>] @see paras

# File lib/plain_text/part.rb, line 128
def boundaries
  select.with_index { |_, i| i.odd? } rescue select.each_with_index { |_, i| i.odd? } # Rescue for Ruby 2.1 or earlier
end
boundary_extended_at(index) click to toggle source

returns all the Boundaries immediately before the index and at it as an Array

See {#squash_boundary_at!} to squash them.

@param index [Integer] @return [Array, nil] nil if a too large index is specified.

# File lib/plain_text/part.rb, line 138
def boundary_extended_at(index)
  (i_pos = get_valid_ipos_for_boundary(index)) || return
  arret = []
  prt = self[i_pos-1]
  arret = prt.public_send(__method__, -1) if prt.class.method_defined? __method__
  arret << self[index]
end
compact!() click to toggle source

Array#compact!

If changed, re-{#normalize!} it.

@return [self, NilClass]

Calls superclass method
# File lib/plain_text/part.rb, line 818
def compact!
  ret = super
  ret ? ret.normalize!(recursive: false) : ret
end
concat(*rest) click to toggle source

Array#concat

@see insert

@param *rest [Array<Array>] @return [self]

# File lib/plain_text/part.rb, line 829
def concat(*rest)
  insert(size, *(rest.sum([])))
end
deepcopy() click to toggle source

Returns a dup-ped instance with all the Arrays and Strings dup-ped.

@return [Part]

# File lib/plain_text/part.rb, line 149
def deepcopy
  dup.map!{ |i| i.class.method_defined?(:deepcopy) ? i.deepcopy : i.dup }
end
each_boundary_with_index(**kwd, &bl) click to toggle source

each method for boundaries only, providing also the index (always an odd number) to the block.

For just looping over the elements of {#boundaries}, do simply

boundaries.each do |ec|
end

The indices provided in this method are for the main Array, and hence different from {#boundaries}.each_with_index

@param (see map_boundary_with_index) @return as self

# File lib/plain_text/part.rb, line 165
def each_boundary_with_index(**kwd, &bl)
  map_boundary_core(map: false, with_index: true, **kwd, &bl)
end
each_para_with_index(**kwd, &bl) click to toggle source

each method for Paras only, providing also the index (always an even number) to the block.

For just looping over the elements of {#paras}, do simply

paras.each do |ec|
end

The indices provided in this method are for the main Array, and hence different from {#paras}.each_with_index

@param (see map_para_with_index) @return as self

# File lib/plain_text/part.rb, line 181
def each_para_with_index(**kwd, &bl)
  map_para_core(map: false, with_index: false, **kwd, &bl)
end
first_significant_element() click to toggle source

The first significant (=non-empty) element.

If the returned value is non-nil and destructively altered, self changes.

@return [Integer, nil] if self.empty? nil is returned.

# File lib/plain_text/part.rb, line 190
def first_significant_element
  (i = first_significant_index) || return
  self[i]
end
first_significant_index() click to toggle source

Index of the first significant (=non-empty) element.

If every element is empty, the last index is returned.

@return [Integer, nil] if self.empty? nil is returned.

# File lib/plain_text/part.rb, line 200
def first_significant_index
  return nil if empty?
  each_index do |i|
    return i if self[i] && !self[i].empty?  # self for sanity
  end
  return size-1
end
index_para?(i, skip_check: false) click to toggle source

True if the index should be semantically for Paragraph?

@param i [Integer] index for the array of self @option skip_check: [Boolean] if true (Default: false), skip conversion of the negative index to positive. @see paras

# File lib/plain_text/part.rb, line 213
def index_para?(i, skip_check: false)
  skip_check ? i.even? : positive_array_index_checked(i, self).even?
end
insert(ind, *rest, primitive: false) click to toggle source

Array#insert

The most basic method to add/insert elements to self. Called from {#[]=} and {#push}, for example.

If ind is greater than size, a number of “”, as opposed to nil, are inserted.

@param ind [Index] @param rest [Array] This must have an even number of arguments, unless ind is larger than the array size and an odd number. @option primitive: [String] if true (Def: false), the original {#insert_original_b4_part} is called. @return [self]

Calls superclass method
# File lib/plain_text/part.rb, line 750
def insert(ind, *rest, primitive: false)
  return insert_original_b4_part(ind, *rest) if primitive
  ipos = positive_array_index_checked(ind, self)
  if    rest.size.even? && (ipos > size - 1) && ipos.even?  # ipos.even? is equivalent to index_para?(ipos), i.e., "is the index for Paragraph?"
    raise ArgumentError, sprintf("number of arguments (%d) must be odd for index %s.", rest.size, ind)
  elsif rest.size.odd?  && (ipos <= size - 1)
    raise ArgumentError, sprintf("number of arguments (%d) must be even.", rest.size)
  end

  if ipos >= size
    rest = Array.new(ipos - size).map{|i| ""} + rest
    ipos = size
  end

  super(ipos, rest)
end
inspect() click to toggle source

@return [String]

Calls superclass method
# File lib/plain_text/part.rb, line 558
def inspect
  self.class.name + super
end
last_significant_element() click to toggle source

The last significant (=non-empty) element.

If the returned value is non-nil and destructively altered, self changes.

@return [Integer, nil] if self.empty? nil is returned.

# File lib/plain_text/part.rb, line 222
def last_significant_element
  (i = last_significant_index) || return
  self[i]
end
last_significant_index() click to toggle source

Index of the last significant (=non-empty) element.

If every element is empty, 0 is returned.

@return [Integer, nil] if self.empty? nil is returned.

# File lib/plain_text/part.rb, line 232
def last_significant_index
  return nil if empty?
  (0..(size-1)).to_a.reverse.each do |i|
    return i if self[i] && !self[i].empty?  # self for sanity
  end
  return 0
end
map_boundary(**kwd, &bl) click to toggle source

map method for boundaries only, returning a copied self.

If recursive is true (Default), any Boundaries in the descendant Parts are also handled.

If a Boundary is set nil or empty, along with the preceding Paragraph, the pair is removed from the returned instance in Default (:compact and :compacter options

  • see {#initialize} for detail)

@option recursive: [Boolean] if true (Default), map is performed recursively. @return as self @see initialize for the other options (:compact and :compacter)

# File lib/plain_text/part.rb, line 251
def map_boundary(**kwd, &bl)
  map_boundary_core(with_index: false, **kwd, &bl)
end
map_boundary_with_index(**kwd, &bl) click to toggle source

map method for boundaries only, providing also the index (always an odd number) to the block, returning a copied self.

@param (see map_boundary) @return as self

# File lib/plain_text/part.rb, line 259
def map_boundary_with_index(**kwd, &bl)
  map_boundary_core(with_index: true, **kwd, &bl)
end
map_para(**kwd, &bl) click to toggle source

map method for Paras only, returning a copied self.

If recursive is true (Default), any Paras in the descendant Parts are also handled.

If a Paragraph is set nil or empty, along with the following Boundary, the pair is removed from the returned instance in Default (:compact and :compacter options

  • see {#initialize} for detail)

@option recursive: [Boolean] if true (Default), map is performed recursively. @return as self @see initialize for the other options (:compact and :compacter)

# File lib/plain_text/part.rb, line 274
def map_para(**kwd, &bl)
  map_para_core(with_index: false, **kwd, &bl)
end
map_para_with_index(**kwd, &bl) click to toggle source

map method for paras only, providing also the index (always an even number) to the block, returning a copied self.

@param (see map_para) @return as self

# File lib/plain_text/part.rb, line 282
def map_para_with_index(**kwd, &bl)
  map_para_core(with_index: false, **kwd, &bl)
end
merge_para!(*rest, use_para_index: false) click to toggle source

merge multiple paragraphs

The boundaries between them are simply joined as String as they are.

@overload set(index1, index2, *rest)

With a list of indices.  Unless use_para_index is true, this means the main Array index. Namely, if Part is [P0, B0, P1, B1, P2, B2, B3] and if you want to merge P1 and P2, you specify as (2,3,4) or (2,4).  If use_para_index is true, specify as (1,2).
@param index1 [Integer] the first index to merge
@param index2 [Integer] the second index to merge, and so on...

@overload set(range)

With a range of the indices to merge. Unless use_para_index is true, this means the main Array index. See the first overload set about it.
@param range [Range] describe value param

@param use_para_index: [Boolean] If false (Default), the indices are for the main indices (alternative between Paras and Boundaries, starting from Para). If true, the indices are as obtained with {#paras}, namely the array containing only Paras. @return [self, nil] nil if nothing is merged (because of wrong indices).

# File lib/plain_text/part.rb, line 332
    def merge_para!(*rest, use_para_index: false)
$myd = true
#warn "DEBUG:m00: #{rest}\n"
      (ranchk = build_index_range_for_merge_para!(*rest, use_para_index: use_para_index)) || (return self)  # Do nothing.
      # ranchk is guaranteed to have a size of 2 or greater.
#warn "DEBUG:m0: #{ranchk}\n"
      self[ranchk] = [self[ranchk].to_a[0..-2].join, self[ranchk.end]]  # 2-elements (Para, Boundary)
      self
    end
merge_para_if() { |ar1st, ar2nd, self, ei| ... } click to toggle source

merge Paras if they satisfy the conditions.

A group of two Paras and the Boundaries in between and before and after is passed to the block consecutively.

@yield [ary, b1, b2, i] Returns true if the two paragraphs should be merged. @yieldparam [Array] ary of [Para1st, BoundaryBetween, Para2nd] @yieldparam [Boundary] b1 Boundary-String before the first Para (nil for the first one) @yieldparam [Boundary] b2 Boundary-String after the second Para @yieldparam [Integer] i Index of the first Para @yieldreturn [Boolean, Symbol] True if they should be merged. :abort if cancel it. @return [self, false] false if no pairs of Paras are merged, else self.

# File lib/plain_text/part.rb, line 298
def merge_para_if()
  arind2del = []  # Indices to delete (both paras and boundaries)
  each_index do |ei|
    break if ei >= size - 3  # 2nd last paragraph or later.
    next if !index_para?(ei, skip_check: true)
    ar1st = self.to_a[ei..ei+2]
    ar2nd = ((ei==0) ? nil : self[ei-1])
    do_merge = yield(ar1st, ar2nd, self[ei+3], ei)
    return false                 if do_merge == :abort
    arind2del.push ei, ei+1, ei+2 if do_merge 
  end

  return false if arind2del.empty? 
  arind2del.uniq!

  (arind2ranges arind2del).reverse.each do |er|
    merge_para!(er)
  end
  return self
end
normalize(recursive: true, ignore_array_boundary: true, compact: true, compacter: true) click to toggle source

Non-destructive version of {#normalize!}

@option recursive: [Boolean] if true (Default), normalize recursively. @option ignore_array_boundary: [Boolean] if true (Default), even if a Boundary element (odd-numbered index) is an Array, ignore it. @option compact: [Boolean] if true (Default), pairs of nil paragraph and boundary are removed. Otherwise, nil is converted to an empty string. @option compacter: [Boolean] if true (Default), pairs of nil or empty paragraph and boundary are removed. @return as self @see normalize!

# File lib/plain_text/part.rb, line 428
def normalize(recursive: true, ignore_array_boundary: true, compact: true, compacter: true)
  # Trims pairs of consecutive Paragraph and Boundary of nil
  arall = to_a
  size_parity = (size.even? ? 0 : 1)
  if (compact || compacter) && (size > 0+size_parity)
    ((size-2-size_parity)..0).each do |i| 
      # Loop over every Paragraph
      next if i.odd?
      arall.slice! i, 2 if compact   &&  !self[i] && !self[i+1]
      arall.slice! i, 2 if compacter && (!self[i] || self[i].empty?) && (!self[i+1] || self[i+1].empty?)
    end
  end

  i = -1
  self.class.new(
    arall.map{ |ea|
      i += 1
      normalize_core(ea, i, recursive: recursive)
    } + (arall.size.odd? ? [Boundary.new('')] : [])
  )
end
normalize!(recursive: true, ignore_array_boundary: true, compact: true, compacter: true) click to toggle source

Normalize the content, making sure it has an even number of elements

The even and odd number elements are, if bare Strings or Array, converted into Paeagraph and Boundary, or Part, respectively. If not, Exception is raised. Note nil is conveted into either an empty Paragraph or Boundary.

@option recursive: [Boolean] if true (Default), normalize recursively. @option ignore_array_boundary: [Boolean] if true (Default), even if a Boundary element (odd-numbered index) is an Array, ignore it. @option compact: [Boolean] if true (Default), pairs of nil paragraph and boundary are removed. Otherwise, nil is converted to an empty string. @option compacter: [Boolean] if true (Default), pairs of nil or empty paragraph and boundary are removed. @return [self]

# File lib/plain_text/part.rb, line 399
def normalize!(recursive: true, ignore_array_boundary: true, compact: true, compacter: true)
  # Trim pairs of consecutive Paragraph and Boundary of nil
  size_parity = (size.even? ? 0 : 1)
  if (compact || compacter) && (size > 0+size_parity)
    ((size-2-size_parity)..0).each do |i| 
      # Loop over every Paragraph
      next if i.odd?
      slice! i, 2 if compact   &&  !self[i] && !self[i+1]
      slice! i, 2 if compacter && (!self[i] || self[i].empty?) && (!self[i+1] || self[i+1].empty?)
    end
  end

  i = -1
  map!{ |ea|
    i += 1
    normalize_core(ea, i, recursive: recursive)
  }
  insert_original_b4_part(size, Boundary.new('')) if size.odd?
  self
end
paras() click to toggle source

Returns an array of Paras (even-number-index elements), consisting of Part and/or Paragraph

@return [Array<Part, Paragraph>] @see boundaries

# File lib/plain_text/part.rb, line 455
def paras
  select.with_index { |_, i| i.even? } rescue select.each_with_index { |_, i| i.even? } # Rescue for Ruby 2.1 or earlier
  # ret.freeze
end
push(*rest) click to toggle source

Array#push

@see concat

@param ary [Array] @return [self]

# File lib/plain_text/part.rb, line 839
def push(*rest)
  concat(rest)
end
Also aliased as: append
reparse(**kwd) click to toggle source

Non-destructive version of {reparse!}

@param (see reparse!) @return [PlainText::Part]

# File lib/plain_text/part.rb, line 476
def reparse(**kwd)
  ret = self.dup
  ret.reparse!(**kwd)
  ret
end
reparse!(rule: PlainText::ParseRule::RuleConsecutiveLbs, name: nil, range: (0..-1)) click to toggle source

Reparses self or a part of it.

@param str [String] @option rule: [PlainText::ParseRule] (PlainText::ParseRule::RuleConsecutiveLbs) @option name: [String, Symbol, Integer, nil] Identifier of rule, if need to specify. @option range: [Range, nil] Range of indices of self to reparse. In Default, the entire self. @return [self]

# File lib/plain_text/part.rb, line 467
def reparse!(rule: PlainText::ParseRule::RuleConsecutiveLbs, name: nil, range: (0..-1))
  insert range.begin, self.class.parse((range ? self[range] : self), rule: rule, name: name)
  self
end
slice(arg1, *rest)

{#slice} is an alias to {#[]}

Alias for: []
slice!(arg1, *rest, primitive: false) click to toggle source

Delete elements and return the deleted content or nil if nothing is deleted.

The number of elements to be deleted must be even.

@param arg1 [Integer, Range] @option arg2 [Integer, NilClass] @option primitive: [Boolean] if true (Def: false), the original {#insert_original_b4_part} is called. @return as self or NilClass

Calls superclass method
# File lib/plain_text/part.rb, line 776
def slice!(arg1, *rest, primitive: false)
  return slice_original_b4_part!(arg1, *rest) if primitive

  arg2 = rest[0]

  # Simple substitution to a single element
  raise ArgumentError, ERR_MSGS[:even_num] if !arg2 && !arg1.class.method_defined?(:exclude_end?)

  check_bracket_args_type_error(arg1, arg2)  # Args are now either (Int, Int) or (Range)

  if arg2
    size2delete = size2extract(arg1, arg2, ignore_error: true)  # maybe nil (if the index is too small).
    # raise ArgumentError, ERR_MSGS[:even_num] if arg2.to_int.odd?
    raise ArgumentError, ERR_MSGS[:even_num] if size2delete && size2delete.odd?
    raise ArgumentError, "odd index is not allowed as the starting Range for #{self.class.name}.  It must be even." if arg1.odd?  # Because the returned value is this class of instance.
    return super(arg1, *rest)
  end

  begin
    rang = normalize_index_range(arg1)
  rescue IndexError => err
    raise RangeError, err.message
  end

  raise RangeError if rang.begin < 0 || rang.end < 0

  return super(arg1, *rest) if (rang.begin > rang.end)  # nil or [] is returned

  size2delete = size2extract(rang, skip_renormalize: true)
  raise ArgumentError, ERR_MSGS[:even_num] if size2delete && size2delete.odd? 
  raise ArgumentError, "odd index is not allowed as the starting Range for #{self.class.name}.  It must be even." if rang.begin.odd?  # Because the returned value is this class of instance.
  super(arg1, *rest)
end
squash_boundary_at!(index) click to toggle source

Emptifies all the Boundaries immediately before the Boundary at the index and squashes it to the one at it.

See {#boundary_extended_at} to view them.

@param index [Integer] @return [Boundary, nil] nil if a too large index is specified.

# File lib/plain_text/part.rb, line 489
def squash_boundary_at!(index)
  (i_pos = get_valid_ipos_for_boundary(index)) || return
  prt = self[i_pos-1]
  m = :emptify_last_boundary!
  self[i_pos] << prt.public_send(m) if prt.class.method_defined? m
  self[i_pos]
end
squash_boundaryies!() click to toggle source

Wrapper of {#squash_boundary_at!} to loop over the whole {Part}

@return [self]

# File lib/plain_text/part.rb, line 501
def squash_boundaryies!
  each_boundary_with_index do |ec, i|
    squash_boundary_at!(i)
  end
  self
end
subclass_name() click to toggle source

Boundary sub-class name only

Make sure your class is a child class of Part Otherwise this method would not be inherited, obviously.

@example

class PlainText::Part
  class Section < self
    class Subsection < self; end  # It must be a child class!
  end
end
ss = PlainText::Part::Section::Subsection.new ["abc"]
ss.subclass_name  # => "Section::Subsection"

@return [String] @see PlainText::Part#subclass_name

# File lib/plain_text/part.rb, line 525
def subclass_name
  printf "__method__=(%s)\n", __method__
  self.class.name.split(/\A#{Regexp.quote method(__method__).owner.name}::/)[1] || ''
end

Private Instance Methods

build_index_range_for_merge_para!(*rest, use_para_index: false) click to toggle source

Building a proper array for the indices to merge

Returns always an even number of Range, starting from para, like (2..5), the last of which is a Boundary which is not merged. In this example, Para(i=2)/Boundary(3)/Para(4) is merged, while Boundary(5) stays as it is.

@param (see merge_para!) @param use_para_index: [Boolean] false @return [Range, nil] nil if no range is selected.

# File lib/plain_text/part.rb, line 352
    def build_index_range_for_merge_para!(*rest, use_para_index: false)
#warn "DEBUG:b0: #{rest.inspect} to_a=#{to_a}\n"
      inary = rest.flatten
      return nil if inary.empty?
      # inary = inary[0] if like_range?(inary[0])
#warn "DEBUG:b1: #{inary.inspect}\n"
      (ary = to_ary_positive_index(inary, to_a)) || return  # Guaranteed to be an array of positive indices (sorted and uniq-ed).
#warn "DEBUG:b3: #{ary}\n"
      return nil if ary.empty?

      # Normalize so the array contains both Paragraph and Boundaries in between.
      # After this, ary must be [Para1-index, Boundary1-index, P2, B2, ..., Pn-index, Bn-index]
      # Note: In the input, the index is probably for Paragraph.  But,
      #   for the sake of later processing, make the array contain an even number
      #   of elements, ending with Boundary.
      if use_para_index
        ary = ary.map{|i| [i*2, i*2+1]}.flatten
      elsif index_para?(ary[-1], skip_check: true)
        # The last index in the given Array or Range was for Paragraph (Likely case).
        ary.push(ary[-1]+1)
      end

      # Exception if they are not consecutive.
      ary.inject{|memo, val| (val == memo+1) ? val : raise(ArgumentError, "Given (Paragraph) indices are not consecutive.")}

$myd = false
      # Exception if the first index is for Boundary and no Paragraph.
      raise ArgumentError, "The first index (#{ary[0]}) is not for Paragraph." if !index_para?(ary[0], skip_check: true)

      i_end = [ary[-1], size-1].min
      return if i_end - ary[0] < 3  # No more than 1 para selected.

      (ary[0]..ary[-1])
    end
check_bracket_args_type_error(arg1, arg2=nil) click to toggle source

Checking whether index-type arguments conform

After this, it is guaranteed the arguments are either (Integer, Integer) or (Range, nil).

@param arg1 [Integer, Range] Starting index or Range. Maybe including negative values. @option arg2 [Integer, NilClass] Size. @return [NilClass] @raise [TypeError] if not conforms.

# File lib/plain_text/part.rb, line 864
def check_bracket_args_type_error(arg1, arg2=nil)
  if arg2
    raise TypeError, sprintf("no implicit conversion of #{arg2.class} into Integer") if !arg2.class.method_defined?(:to_int)
  else
    raise TypeError if !arg1.class.method_defined?(:exclude_end?)
  end
end
emptify_last_boundary!() click to toggle source

Emptifies all the Boundaries immediately before the index and squashes it to the one at it.

@return [Boundary] all the descendants' last Boundaries merged.

# File lib/plain_text/part.rb, line 877
def emptify_last_boundary!
  return Boundary::Empty.dup if size == 0
  ret = ""
  ret << prt.public_send(__method__) if prt.class.method_defined? __method__
  ret << self[-1]
  self[-1] = Boundary::Empty.dup
  ret
end
get_valid_ipos_for_boundary(index) click to toggle source

Returns a positive Integer index guaranteed to be 1 or greater and smaller than the size.

@param index [Integer] @return [Integer, nil] nil if a too large index is specified.

# File lib/plain_text/part.rb, line 892
def get_valid_ipos_for_boundary(index)
  i_pos = positive_array_index_checked(index, self)
  raise ArgumentError, "Index #{index} specified was for Para, which should be for Boundary." if index_para?(i_pos, skip_check: true)
  (i_pos > size - 1) ? nil : i_pos
end
map_boundary_core(map: true, with_index: false, recursive: true, **kwd) { |ec, ind| ... } click to toggle source

Core routine for {#map_boundary} and similar.

@option map opts: [Boolean] if true (Default), map is performed. Else just each. @option with_index: [Boolean] if true (Default: false), yield with also index @option recursive: [Boolean] if true (Default), map is performed recursively. @return as self if map: is true, else void

# File lib/plain_text/part.rb, line 906
def map_boundary_core(map: true, with_index: false, recursive: true, **kwd, &bl)
  ind = -1
  arnew = map{ |ec|
    ind += 1
    if recursive && index_para?(ind, skip_check: true) && ec.class.method_defined?(__method__)
      ec.public_send(__method__, recursive: true, **kwd, &bl)
    elsif !index_para?(ind, skip_check: true)
      with_index ? yield(ec, ind) : yield(ec)
    else
      ec
    end
  }
  self.class.new arnew, recursive: recursive, **kwd if map
end
map_para_core(map: true, with_index: false, recursive: true, **kwd) { |ec, ind| ... } click to toggle source

Core routine for {#map_para}

@option map: [Boolean] if true (Default), map is performed. Else just each. @option with_index: [Boolean] if true (Default: false), yield with also index @option recursive: [Boolean] if true (Default), map is performed recursively. @return as self @see initialize for the other options (:compact and :compacter)

# File lib/plain_text/part.rb, line 929
def map_para_core(map: true, with_index: false, recursive: true, **kwd, &bl)
  ind = -1
  new_paras = paras.map{ |ec|
    ind += 1
    if recursive && ec.class.method_defined?(__method__)
      ec.public_send(__method__, recursive: true, **kwd, &bl)
    else
      with_index ? yield(ec, ind) : yield(ec)
    end
  }
  self.class.new new_paras, boundaries, recursive: recursive, **kwd if map
end
normalize_core(ea, i, recursive: true, ignore_array_boundary: true) click to toggle source

Core routine for {#normalize!} and {#normalize}

@param ea [Array, String, NilClass] the element to evaluate @param i [Integer] Main array index @option recursive: [Boolean] if true (Default), normalize recursively. @option ignore_array_boundary: [Boolean] if true (Default), even if a Boundary element (odd-numbered index) is an Array, ignore it. @return [Part, Paragraph, Boundary]

# File lib/plain_text/part.rb, line 950
def normalize_core(ea, i, recursive: true, ignore_array_boundary: true)
  if    ea.class.method_defined?(:to_ary)
    if index_para?(i, skip_check: true) || ignore_array_boundary
      (/\APlainText::/ =~ ea.class.name && defined?(ea.normalize)) ? (recursive ? ea.normalize : ea) : self.class.new(ea, recursive: recursive)
    else
      raise "Index ({#i}) is an Array or its child, but it should be Boundary or String."
    end
  elsif ea.class.method_defined?(:to_str)
    if /\APlainText::/ =~ ea.class.name
      # Paragraph or Boundary
      ea.unicode_normalize
    else
      if index_para?(i, skip_check: true)
        Paragraph.new(ea.unicode_normalize || "")
      else
        Boundary.new( ea.unicode_normalize || "")
      end
    end
  else
    raise ArgumentError, "Unrecognised elements for #{self.class}: "+ea.inspect
  end
end
normalize_index_range(rng, **kwd) click to toggle source

Returns (inclusive, i.e., not “…”) Range of non-negative indices

@param rng [Range] It has to be a Range @return [Range] @raise [IndexError] if too negative index is specified.

# File lib/plain_text/part.rb, line 980
def normalize_index_range(rng, **kwd)
  # NOTE to developers: (0..-1).to_a returns [] (!)
  arpair = [rng.begin, rng.end].to_a.map{ |i| positive_array_index_checked(i, self, **kwd) }
  arpair[1] -= 1 if rng.exclude_end?
  (arpair[0]..arpair[1])
end
size2extract(arg1, arg2=nil, ignore_error: false, skip_renormalize: false, **kwd) click to toggle source

Returns the size (the number of elements) to extract

taking into account the size of self

  1. if (3, 2) is specified when self.size==4, this returns 1.

  2. if (3..2) is specified, this returns 0.

Make sure to call {#check_bracket_args_type_error} beforehand.

@param arg1 [Integer, Range] Starting index or Range. Maybe including negative values. @option arg2 [Integer, NilClass] Size. @option ignore_error: [Boolean] if true (Def: false), nil is returned instead of raising IndexError (when a negative index is too small) @option skip_renormalize: [Boolean] if true (Def: false), the given Range is assumed to be already normalized by {#normalize_index_range} @return [Integer, NilClass] nil if an Error is raised with ignore_error being true

# File lib/plain_text/part.rb, line 1003
def size2extract(arg1, arg2=nil, ignore_error: false, skip_renormalize: false, **kwd)
  begin
    if arg1.class.method_defined? :exclude_end?
      rng = arg1
      rng = normalize_index_range(rng, **kwd) if !skip_renormalize
    else
      ipos = positive_array_index_checked(arg1, self)
      rng = (ipos..(ipos+arg2.to_int-1))
    end
    return 0 if rng.begin > size-1
    return 0 if rng.begin > rng.end
    return [rng.end, size-1].min-rng.begin+1
  rescue IndexError
    return nil if ignore_error
    raise
  end
end