Maruku's string_utils.rb

Wow! Totally un-Ruby-like.
This is more Ruby-like and
(hopefully) faster.
This commit is contained in:
Jacques Distler 2010-06-02 00:15:58 -05:00
parent b7a3b8aa94
commit c25b608f3d

View file

@ -81,18 +81,7 @@ module MaRuKu; module Strings
# Returns the number of leading spaces, considering that # Returns the number of leading spaces, considering that
# a tab counts as `TabSize` spaces. # a tab counts as `TabSize` spaces.
def number_of_leading_spaces(s) def number_of_leading_spaces(s)
n=0; i=0; s[/^[ \t]*/].gsub("\t", ' '*TabSize).length
while i < s.size
c = s[i,1]
if c == ' '
i+=1; n+=1;
elsif c == "\t"
i+=1; n+=TabSize;
else
break
end
end
n
end end
# This returns the position of the first real char in a list item # This returns the position of the first real char in a list item
@ -108,54 +97,31 @@ module MaRuKu; module Strings
def spaces_before_first_char(s) def spaces_before_first_char(s)
case s.md_type case s.md_type
when :ulist when :ulist
i=0; # whitespace, followed by ('*'|'+'|'-') followed by
# skip whitespace if present # more whitespace, followed by an optional IAL, followed
while s[i,1] =~ /\s/; i+=1 end # by yet more whitespace
# skip indicator (+, -, *) h=s[/^\s*(\*|\+|\-)\s*(\{.*?\})?\s*/]
i+=1
# skip whitespace
while s[i,1] =~ /\s/; i+=1 end
# find an IAL
ial = s[i,s.length - i][/^\{(.*?)\}/]
i+= ial.length if ial
# skip optional whitespace
while s[i,1] =~ /\s/; i+=1 end
return [i, ial]
when :olist when :olist
i=0; # whitespace, followed by a number, followed by a period,
# skip whitespace # more whitespace, an optional IAL, and more whitespace
while s[i,1] =~ /\s/; i+=1 end h=s[/^\s*\d+\.\s*(\{.*?\})?\s*/]
# skip digits
while s[i,1] =~ /\d/; i+=1 end
# skip dot
i+=1
# skip optional whitespace
while s[i,1] =~ /\s/; i+=1 end
# find an IAL
ial = s[i,s.length - i][/^\{(.*?)\}/]
i+= ial.length if ial
# skip whitespace
while s[i,1] =~ /\s/; i+=1 end
return [i, ial]
else else
tell_user "BUG (my bad): '#{s}' is not a list" tell_user "BUG (my bad): '#{s}' is not a list"
[0, nil] h=''
end end
ial = h[/\{.*\}/]
return [h.length, ial]
end end
# Counts the number of leading '#' in the string # Counts the number of leading '#' in the string
def num_leading_hashes(s) def num_leading_hashes(s)
i=0; h = s[/^#*/]
while i<(s.size-1) && (s[i,1]=='#'); i+=1 end h ? h.length : 0
i
end end
# Strips initial and final hashes # Strips initial and final hashes
def strip_hashes(s) def strip_hashes(s)
s = s[num_leading_hashes(s), s.size] s.sub(/^#*(.*?)(#|\s)*$/, '\1').strip
i = s.size-1
while i > 0 && (s[i,1] =~ /(#|\s)/); i-=1; end
s[0, i+1].strip
end end
# change space to "_" and remove any non-word character # change space to "_" and remove any non-word character