What the correct algorithm to invert italics in a mixed text?

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 "nn$s";

8

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”.

XSLT attempt from https://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

1

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>

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật