HTMLUtils.frink

Download or view HTMLUtils.frink in plain text format


// Utilities for HTML manipulation.

/* This encodes strings safely for HTML (unless it's going in a tag parameter,
   in which case you should use HTMLEncodeQuoted below.)  */

HTMLEncode[line] :=
{
   if ! line
      return ""
   line = toString[line]
   line =~ %s/&/&/g;
   line =~ %s/</&lt;/g;
   line =~ %s/>/&gt;/g;
   return line
}

/* This encodes strings safely for HTML, including the case where it's going
   into a quoted tag parameter.  This is usually always safer and better.  */

HTMLEncodeQuoted[line] :=
{
   if ! line
      return ""
   line = toString[line]
   line = HTMLEncode[line];
   line =~ %s/"/&quot;/g;
//   line =~ %s/\\u/\\\\u/g;
   return line
}

// Make the <OPTIONS> tags for an HTML <SELECT> list, with the specified
// item selected.
// makeselect[list, selected]
makeSelect[list, selected] :=
{
   for [name, val] list
   {
      if (val != undef)         // Has value
      {
         vs = "$val"               // Coerce to string
         valStr = (val != undef) ? " VALUE=\"" + HTMLEncode[vs] + "\"" : ""
         sel = (vs == selected ? " SELECTED" : "")
      } else
         sel = (name == selected ? " SELECTED" : "")
      println["    <OPTION$valStr$sel>" + HTMLEncode["$name"]]
   }
}

// Format a Frink expression into a prettier HTML equivalent.
formatExpression[expr] :=
{
   expr =~ %s/\+(\s*)\-1\s+/-$1/g  // "+ -1"   goes to "-"
   expr =~ %s/\+(\s*)\-/-$1/g         // "+ -" goes to "-"
//   expr =~ %s/\((\s*)\-1\s+([^+])/(-$1$2/g         // "(-1 " goes to "(-"  unless followed by +
   expr =~ %s/\^([\/\d\w\.\-]+(?:\[[^\]]?\])?)/<SUP>$1<\/SUP>/g  // Draw superscripts for integers and floating-point numbers.
   return expr
}

// Format an expression using some symbolic rules.
formatExpressionSymbolic[expr] :=
{
   expr = formatExpression[expr]
   return removeApproximations[expr]
}

// Remove approximations
removeApproximations[expr] :=
{
   expr =~ %s/\s*\((approx\.|exactly).*?\)//g
   return expr
}


Download or view HTMLUtils.frink in plain text format


This is a program written in the programming language Frink.
For more information, view the Frink Documentation or see More Sample Frink Programs.

Alan Eliasen was born 19966 days, 2 hours, 7 minutes ago.