Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

The question motivations was depicted in the section below. There are many ways to make text italic, so, perhaps, there are more than one good "swap italics algorithm". The problem reveals some aditional dificulties in a XHTML code, and using the <i> tag, that must to be balanced. Example:

 <!-- original text: -->
 <p id="p1"><i>Several more</i> Homo sapiens <i>fossils were discovered</i>.</p>
 <!-- same text, swapping italics: -->
 <p id="p2">Several more <i>Homo sapiens</i> fossils were discovered.</p>

So, looks like this,

  1. Several more Homo sapiens fossils were discovered.

  2. Several more Homo sapiens fossils were discovered.


Algoritms introduction and discussion

For "layout solution", the simplest algorithm is checking the font-style CSS-property of all text blocks, and invert them with jQuery:

$('#myFragment *').each(function(){
   if ($(this).css('font-style')=='italic')
       $(this).css('font-style','normal')
    else
       $(this).css('font-style','italic')        
}); 

But this algorithm not survive to a little more complex test,

 <p id="p3"><b><i>F</i>RAGMENT <big><i>with italics</i> and </big> withOUT.</b></p>

The second simplest algorithm is for a concrete solution, and was used in the "Examples" section. Have two steps:

  1. enclose the XHTML fragment into italics;
  2. invert open/close italic tags (ex. </i> to <i>).

That is, writing with Javascript,

var s = '... a fragment of XHTML content ...';
s = '<i>'+
   s.replace(/<(\/?)i>/mg, 
          function (m,p1){
              return p1? '<i>': '</i>';
          }
   ) +
   '</i>';  

But also not survive to the second test, losting balance of tags... The "corrected" algorithm runs (!), but is not portable, neither fast or elegant. It is demonstred here, and at the example section below.

The point!

So the question is,

there are a simple, good and generic (usable in any browser and portable to another languages) algorithm? You know another "swap italics algorithm"?

PS: "generic" in the sense that I even translate your algorithm to XSLT. The algorithm must produce directally balanced XHTML code (without a intermediary blackbox like Tidy).


Motivations

I need to port the "swap italics algorithm" to text editors, server parsers, etc. In all cases I can "normalize input" (and output) by standard XHTML and <i> tag.

I am parsing XHTML text of prose books and scientific articles, exported from different origins and styles... The most texts are exported as "normal text", but a lot of titles (ex. article title, chapter title), and, sometimes, a full chapter or a full text-box (ex. article abstract) are stylized with italics. All these "stylized with italics" must be inverted. Typical cases:

  • Transform the original "all chapter italics" into "all chapter normal text": see this case, where in a roughly 300-page book, 8 of the 25 chapters need to be inverted.

  • Italicized quotation marks, abstracts, etc. See this example. Need change back to normal, but without lost the emphasis words.

  • Writing binomial names of species, in Scientific texts, are usually typeset in italics (or inverted, in a font different from that used for "normal text"). Hundreds of italicized titles (of articles and of article-sections) of XHTML-exported articles must be inverted at my work place. PS: see the example of the beginning of the question ("Several more Homo sapiens ...").

I need also translate the generic algorithm (of your answer!) to a XSLT library, where no "tag balancing correction" not exists.

Examples

Implementing in Javascript and PHP a non-generic "Swap italics algorithm". A generic one need a general "XML interleaving algorithm"... Here I use browser's (DOM) and Tidy corrections, as an alternative to "interleaving".

Javascript

It runs with complex inputs (!). Illustrating, by an jQuery implementation:

 var s = $('#sample1').html(); // get original html text fragment

 // INVERSION ALGORITHM: add and remove italics.
 s = "<i>"+
     s.replace(/<(\/?)i>/mg, 
               function (m,p1){
                   return p1? '<i>': '</i>';
               }
     ) +
     "</i>";  // a not-well-formed-XHTML, but it is ok...
 $('#inverted').html(s); // ...the DOM do all rigth!
 // minor corrections, for clean empties:
 s = $('#inverted').html();
 s = s.replace(/<([a-z]+)>(\s*)<\/\1>/mg,'$2'); // clean
 s = s.replace(/<([a-z]+)>(\s*)<\/\1>/mg,'$2'); // clean remain
 $('#inverted').html(s);  
 // END ALGORITHM

 alert(s);

PHP, with Tidy

The same of Javascript, "translated" to PHP — the natural translation is using DOMDocument() class and loadHTML/saveXML methodos, but what have the same behaviour than browser's correspondents is the tidy class. Shows the same results (!)

 $sample1='<b><i>O</i>RIGINAL <big><i>with italics</i> and </big> withOUT</b>';
 $inverted = '... inverted will be here ...';
 echo $sample1;
 // Tidy correction
 $s = $sample1; // get original html text fragment
  // INVERSION ALGORITHM: add and remove italics.
  $s = "<i>".
      preg_replace_callback('/<(\/?)i>/s', function ($m){
       return $m[1]? '<i>': '</i>';}, $s) .
      "</i>";  // a not-well-formed-XHTML, but it is ok...
  $config = array('show-body-only'=>true,'output-xhtml'=>true);
  $tidy = new tidy;
  $tidy->parseString($s, $config, 'utf8');
  $s = $tidy;  // ... because Tidy corrects!     
  // minor corrections, for clean empties:
  $s = preg_replace('/<([a-z]+)>(\s*)<\/\1>/s', '$2', $s); // clean
  $s = preg_replace('/<([a-z]+)>(\s*)<\/\1>/s', '$2', $s); // clean remain
  // END ALGORITHM
  echo "\n\n$s";
share|improve this question
    
I can't make heads or tails of this question. Can you clarify it? Maybe shorten it to the essential point? –  Bobson Jun 12 '13 at 5:44
    
The essential points are with bulets and bolds... Can you edit to put it in the question-begin or with more emphasis? –  Peter Krauss Jun 12 '13 at 11:57
    
I rewrote the entire question text, putting more focus in a concrete problem. –  Peter Krauss Jun 17 '13 at 1:04
    
If this is just for display(?), have you considered modifying the CSS for the page so that the default is italicized, and the portion within the tags is not? –  MichaelT Jun 17 '13 at 1:13
    
Hum... Not "just for display", the final output is a final database, like the PMC. I edited "motivations" section. –  Peter Krauss Jun 17 '13 at 1:27
show 3 more comments

3 Answers 3

up vote 2 down vote accepted

Updating (Jun 18 '13): using this answer to explain algorithms and summarize conclusions.


About jQuery traversing and "layout solution" workarounds.

After @Wilbert comment I adapted the "simplest algorithm", to avoid the dynamic behaviour of the check .prop(), that changes with .each() iteration, removing the else. After all iteration, a "parent italicizer" resolves. See here or the code below.

$('#myFragment *').each(function(){
   if ($(this).css('font-style')=='italic')
       $(this).css('font-style','normal');
});
$('#myFragment').parent().css('font-style','italic');

Another way to deal with the dynamic behaviour, is checking a static property, by prop('tagName'), that not changes. See here or the code below.

$('#myFragment').parent().css('font-style','italic');
$('#myFragment *').each(function(){
   if ($(this).prop('tagName')=='I')  // not changes with parent
       $(this).css('font-style','normal');
});

It need more tests, and needs a final parsing to change style properties to concrete <i> tags. For apply the algorithm twice, we need some care.


Layout solution

This is not a solution for the present question, but produce some good clues, and is the best (at least the smallest!) solution for the "layout problem"!

The toggleClass() method can be used to swap from a "italicized class" to a "normal-text class". See here or the code below.

 $('#myFragment *').each(function(){
     $(this).toggleClass( "original change");
 });

And we can apply this little algorithm twice, and so many times as we want... It is a good solution! But it is not an "rewrite XML algorithm", the CSS is a key here:

 .original { font-style:normal; } /* use class="original" in your XHTML fragment */
i.original { font-style:italic; }

 .change { font-style:italic; }
i.change{ font-style:normal; }

... So, for an algorithm that transforms <i> tags, the problem is still open...

Concrete solution

A "100% solution, in pure XSLT1" (tested with many cases!) based on an adaptation of @DanielHaley's. It is an effective <i> tags transform.

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:preserve-space elements="p"/>

<xsl:template match="@*|node()"> <!-- copy all -->
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="i"> <!-- remove tag i -->
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="text()[not(ancestor::i)]"> <!-- inlcude tag i -->
    <i><xsl:copy-of select="."/></i>
</xsl:template>
 </xsl:stylesheet>

Outlining as an "drive by event algorithm" in a copy process:

  • remove i tags: copy any thing of "<i> thing </i>" as " thing ".

  • include i tags: copy any text as "<i> text </i>", when the text is not into a context of italic parents. PS: text is a terminal node of the DOM tree.

Conclusions

"Layout solutions" are good for text editors, but they use some tricks and non-rigorous solutions (no matter about overlaps, performance, etc.). For XML process we need to deal with <i> tags transform... So de natural languages to express the algorithm are XSLT or xQuery.

The algorithm implemented with XSLT is shows the framework necessities:

  1. the ancestor (parent, grandparent, etc.) selector, for check if it is or not a "italic context";

  2. the text-node (DOM text()) access;

  3. remove and include the i tag.

So, we can see the problems with each framework.

  • DOM (the W3C standard framework): the DOMDocument::renameNode(), for item 3, is not yet implemented (see PHP, Javascript, etc.).

  • jQuery: doesn't have a convenient function for item 2, see this answer.

  • XSLT: the best for express the algorithm, but not is available in any context like Javascript.

I (or you plase!) will try to express the XSLT algorithm with "pure DOM2" methods. That DOM version will be the "generic algorithm"... Well: if the translation is valid only for DOM3 (using renameNode and other tricks) the conclusion for now, is that "there are NO generic/translatable algorithm".

share|improve this answer
add comment

XSLT attempt from http://stackoverflow.com/a/17156452/317052 ...

I'm not sure if this would cover all cases, but you could do this:

XML Input

<html>
    <!-- original text: -->
    <p id="p1"><i>Several more</i> Homo sapiens <i>fossils were discovered</i>.</p>
    <!-- same text, swapping italics: -->
    <p id="p2">Several more <i>Homo sapiens</i> fossils were discovered.</p>
    <p>Leave me alone!</p>
    <p><b><i>O</i>RIGINAL <big><i>with italics</i> and </big> withOUT</b></p>
</html>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[i]">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="node()" mode="swapItal"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text()" mode="swapItal" priority="1">
        <i><xsl:value-of select="."/></i>
    </xsl:template>

    <xsl:template match="i" mode="swapItal">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="@*|node()" mode="swapItal">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" mode="swapItal"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

XML Output

<html>
   <!-- original text: -->
   <p id="p1">Several more<i> Homo sapiens </i>fossils were discovered<i>.</i></p>
   <!-- same text, swapping italics: -->
   <p id="p2"><i>Several more </i>Homo sapiens<i> fossils were discovered.</i></p>
   <p>Leave me alone!</p>
   <p><b>O<i>RIGINAL </i><big>with italics<i> and </i></big><i> withOUT</i></b></p>
</html>

Input Rendered

Several more Homo sapiens fossils were discovered.

Several more Homo sapiens fossils were discovered.

Leave me alone!

ORIGINAL with italics and withOUT


Output Rendered

Several more Homo sapiens fossils were discovered.

Several more Homo sapiens fossils were discovered.

Leave me alone!

ORIGINAL with italics and withOUT

share|improve this answer
    
Hello, thanks a lot! We have already discussed, at Stackoverflow, the need of some little corrections to a "perfect XSLT", so I add my XSLT adaptation at my answer. Here also the XSLT is not the "final answer" without an "algorithm depiction" or clues to general translation (see "The point" section)... So, you will not recive all the bounty. I add 1 vote to you, understanding that, by the bounty rules of this site, you will recive 50% of the bounty... Please check if I am wrong about this rule. –  Peter Krauss Jun 19 '13 at 3:44
add comment

I would Simply:

  1. Convert all <i> to </i>s
  2. Convert all </i> to <i>s
  3. add an <i> to the beginning
  4. add an </i> to the end

So

 <p id="p1"><i>Several more</i> Homo sapiens <i>fossils were discovered</i>.</p>
 <!-- converts to: -->
 <i><p id="p2">Several more </i>Homo sapiens<i> fossils were discovered.</p></i>
share|improve this answer
1  
Yes, is exactly what the examples (see section "Examples") are doing with Javascript and PHP, with "regular expression replace" functions. There are also a link, jsfiddle.net/rdfJ5 ... But, unfortunately, it is not a general solution: test your step-by-step with this case, <b><i>O</i>RIGINAL <big><i>with italics</i> and </big> withOUT</b>... it producess umbalanced (forbidden!) code and empty blocks. –  Peter Krauss Jun 17 '13 at 16:13
    
@PeterKrauss so this ins't goo enough for you? Whats the problem? –  Morons Jun 17 '13 at 16:18
1  
(I edited the comment, see example where your step-by-step fails!). See "The point" section: is not general, and can't be used with XSLT and/or reused by libraries. –  Peter Krauss Jun 17 '13 at 16:22
    
<i><b></i>O<i>RIGINAL <big></i>with italics<i> and </big> withOUT</b></i> may not be Pretty but it works in every browser –  Morons Jun 17 '13 at 16:28
1  
Please, check if you understand what is "balanced" or "well-formed". Some links: wikipedia, W3C... Synthesizing the rule: "All tags must be balanced". <i><b></i> is not, and ALL DISCUSSION HERE is about "an algorithm that produces balanced results". –  Peter Krauss Jun 17 '13 at 16:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.