Forum How do I...?

Add leading space in prince-script generated content

arthurattwell
In a textbook we're producing, we refer to figures and insert their page number after the reference using generated content. E.g.

In Figure 4.6 (page 30), Alan has just won the lottery...


When the figure is on the same page as the reference, we must not show the page number:

In Figure 4.6, Alan has just won the lottery...


To do this, we're using prince-script.

Here is our CSS:

a.show-page-number:after {
    content: prince-script(pagereference, counter(page), target-counter(attr(href), page));
}


And the script:

function addPageReferenceFunc() {

    Prince.addScriptFunc("pagereference", function(currentPage, targetPage) {

        // if the target is on this page, return blank
        if (currentPage === targetPage) return '';

        // otherwise show the page number
        return '  (page ' + targetPage +')';
    });
}

addPageReferenceFunc();


The problem is that Prince (or something) is stripping the white space at the beginning of the return string. So we get this in output:

In Figure 4.6(page 30), Alan has just won the lottery...


We've tried inserting spaces with CSS glyphs but that doesn't seem to work,added to the return string literally or via a variable. And we can't add the space in the CSS (with a space character or margin) because then it will appear when we don't insert the page reference, too:

In Figure 4.6 , Alan has just won the lottery...


Is Prince stripping white space, and is there a workaround here?
arthurattwell
Solved for now: we've got this working with a non-breaking space (as \u00A0), which is not ideal but will do the trick. I'm still curious to know whether Prince is stripping normal spaces, or whether this is a CSS quirk I don't know about.

function addPageReferenceFunc() {

    Prince.addScriptFunc("pagereference", function(currentPage, targetPage) {

        // if the target is on this page, return blank
        if (currentPage === targetPage) return '';

        // otherwise show a space and the page number in pararentheses
        return '\u00A0' + '(page ' + targetPage +')';
    });
}

addPageReferenceFunc();

mikeday
It looks like a bug specific to delayed script execution, eg. when a script function takes a page number as an argument and gets called later because the page number hasn't been resolved yet. We will investigate.
mikeday
Another option might be to make the entire link element use generated content via the script function, like this:
a.show-page-number {
    content: prince-script(content(), pagereference, counter(page), target-counter(attr(href), page));
}

Now the script function takes the text of the element and can return that plus the optional page number, making that the whitespace collapses correctly.

The only downside is if the link element contains nested markup, which will not be captured in the text.