code: public String spanWrap(@Nullable Dir dir, String str, boolean isHtml) {
      BidiWrappingText wrappingText = spanWrappingText(dir, str, isHtml);
      if (!isHtml) {
        str = HtmlEscapers.htmlEscaper().escape(str);
      }
      return wrappingText.beforeText() + str + wrappingText.afterText();
    }
docs: Formats a string of given directionality for use in HTML output of the context directionality,
  so an opposite-directionality string is neither garbled nor garbles its surroundings.
  
  <p>The algorithm: In case the given directionality doesn't match the context directionality,
  wraps the string with a 'span' element and adds a 'dir' attribute (either 'dir=\"rtl\"' or
  'dir=\"ltr\"').
  
  <p>Directionally isolates the string so that it does not garble its surroundings. Currently,
  this is done by "resetting" the directionality after the string by appending a trailing Unicode
  bidi mark matching the context directionality (LRM or RLM) when either the overall
  directionality or the exit directionality of the string is opposite to that of the context.
  Note that as opposed to the overall directionality, the entry and exit directionalities are
  determined from the string itself.
  
  <p>If !{@code isHtml}, HTML-escapes the string regardless of wrapping.
  
  @param dir {@code str}'s directionality. If null, i.e. unknown, it is estimated.
  @param str The input string
  @param isHtml Whether {@code str} is HTML / HTML-escaped
  @return Input string after applying the above processing.