Controlling tab space in a <pre> using CSS? - html

Is it possible to specify how many pixels, etc. the tab space occupies in a <pre> using CSS?
for example, say i have a piece of code appearing in a <pre> on a web page:
function Image()
{
this.Write = function()
{
document.write(this.ToString());
return this;
};
...
}
Image.prototype = new Properties();
...
is it possible to specify a different amount of space the tab indents the line using CSS?
If not, is there any workarounds?

While the above discussion provides some historical background, times have changed, and more relevant information and possible solutions can be found here: Specifying Tab-Width?
attn admin: possible duplicate of ref'ed question.

From CSS 2.1, § 16.6.1 The 'white-space' processing model:
All tabs (U+0009) are rendered as a horizontal shift that lines up the start edge of the next glyph with the next tab stop. Tab stops occur at points that are multiples of 8 times the width of a space (U+0020) rendered in the block's font from the block's starting content edge.
CSS3 Text says basically the same thing.
From HTML 4.01 § 9.3.4 Preformatted text: The PRE element
The horizontal tab character (decimal 9 in [ISO10646] and [ISO88591] ) is usually interpreted by visual user agents as the smallest non-zero number of spaces necessary to line characters up along tab stops that are every 8 characters. We strongly discourage using horizontal tabs in preformatted text since it is common practice, when editing, to set the tab-spacing to other values, leading to misaligned documents.
If you're concerned with leading tabs, it's a simple matter to replace them with spaces.
/* repeat implemented using Russian Peasant multiplication */
String.prototype.repeat = function (n) {
if (n<1) return '';
var accum = '', c=this;
for (; n; n >>=1) {
if (1&n) accum += c;
c += c;
}
return accum;
}
String.prototype.untabify = function(tabWidth) {
tabWidth = tabWidth || 4;
return this.replace(/^\t+/gm, function(tabs) { return ' '.repeat(tabWidth * tabs.length)} );
}

Related

How to set a certain number of spaces or indents before a Paragraph in Google Docs using Google Apps Script

I have a 20 line script, and I want to make sure that each paragraph is indented exactly once.
function myFunction() {
/*
This function turns the document's format into standard MLA.
*/
var body = DocumentApp.getActiveDocument().getBody();
body.setFontSize(12); // Set the font size of the contents of the documents to 9
body.setForegroundColor('#000000');
body.setFontFamily("Times New Roman");
// Loops through paragraphs in body and sets each to double spaced
var paragraphs = body.getParagraphs();
for (var i = 3; i < paragraphs.length; i++) { // Starts at 3 to exclude first 4 developer-made paragraphs
var paragraph = paragraphs[i];
paragraph.setLineSpacing(2);
// Left align the first cell.
paragraph.setAlignment(DocumentApp.HorizontalAlignment.LEFT);
// One indent
paragraph.editAsText().insertText(0, "\t"); // Adds one tab every time
}
var bodyText = body.editAsText();
bodyText.insertText(0, 'February 3, 1976\nMrs. Smith\nYour Name Here\nSocial Studies\n');
bodyText.setBold(false);
}
The code I have tried doesn't work. But my expected results are that for every paragraph in the for loop in myFunction(), there are exactly 4 spaces before the first word in each paragraph.
Here is a sample: https://docs.google.com/document/d/1sMztzhOehzheRdqumC6PLnvk4qJgUCSE0irjTZ0FjTQ/edit?usp=sharing
If the user uses Autoformat, but already has the paragraphs indented...
Update
I have investigated use of the Paragraph.setIndentFirstLine() method. When I set it to four, it sets it to 1 space. Now I realize this is because points and spaces are not the same thing. What number do I need to multiply by to get four spaces in points?
Let us consider a few basic identing operations: manual and by script.
The following image shows how to indent current paragraph (cursor stays inside this one).
Please note, the units are centimetres. Also note, that the paragraph does not include leading spaces or tabs, we have no need of them.
Suppose we would like to get the indent values in the script and apply them to the next paragraph. Look at the code below:
function myFunction() {
var ps = DocumentApp.getActiveDocument().getBody().getParagraphs();
// We work with the 5-th and 6-th paragraphs indeed
var iFirst = ps[5].getIndentFirstLine();
var iStart = ps[5].getIndentStart();
var iEnd = ps[5].getIndentEnd();
Logger.log([iFirst, iStart, iEnd]);
ps[6].setIndentFirstLine(iFirst);
ps[6].setIndentStart(iStart);
ps[6].setIndentEnd(iEnd);
}
If you run and look at the log, you will see something like this: [92.69291338582678, 64.34645669291339, 14.173228346456694]. No surprise, we have typographic points instead of centimetres. (1cm=28.3465pt) So we can measure and modify any paragraph indent values precisely.
Addition
For some reasons you might want to control spaces number at the beginning of the paragraph. It is also possible by scripting, but it has no effect on the paragraph's "left" or "right" indents.
Sample code below is for similar task: count leading spaces number of the 5-th paragraph and make the same number of spaces at the beginning of the next one.
function mySpaces() {
var ps = DocumentApp.getActiveDocument().getBody().getParagraphs();
// We work with the 5-th and 6-th paragraphs indeed
var spacesCount = getLeadingSpacesCount(ps[5]);
Logger.log(spacesCount);
var diff = getLeadingSpacesCount(ps[6]) - spacesCount;
if (diff > 0) {
ps[6].editAsText().deleteText(0, diff - 1);
} else if (diff < 0) {
var s = Array(1 - diff).join(' ');
ps[6].editAsText().insertText(0, s);
}
}
function getLeadingSpacesCount(p) {
var found = p.findText("^ +");
return found ? found.getEndOffsetInclusive() + 1 : 0;
}
We have used methods deleteText() and insertText() of the class Text for proper corrections and findText() to locate the spaces if any. Note, the last method argument is a string, representing a regular expression. It matches "all leading spaces", if they exist. See more details about regular expression syntax.

Break word at specific character

I realise that similar questions have been asked, but none quite like this.
I have a situation where I am using BEM to display some classes in code tags. Below is an example:
Obviously the default behaviour is to break words at a hyphen, as we can see is happening in the example. Is there a way that I can control what characters the line-break occurs at? I would like to be able to have class name integrity maintained so that the line break occurs before each period . if necessary.
I have another solution using jquery,
$('.mypara').each(function () {
var str = $(this).html();
var htmlfoo = str.split('.').join('</br>');
$(this).html(htmlfoo);
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<code class="mypara">
This is-the HTML if its - characters exceed 50. characters it should go-to next line
</code>
<code class="mypara">
This is the HTM-if its. characters exceed 50 - characters it should. go-to next-line
</code>
Unfortunately I don't think there is a way to do everything you want with pure CSS.
UPDATE: removed spaces before periods in JS solution.
If you are able to use JavaScript you could process the code tag's contents to disable wrapping for words with hyphens and you could wrap each block starting with a period in an inline-block span.
The following code breaks the contents of each code tag into a list of blocks that start with either space or period. Each block is wrapped with a span that prevents wrapping, and blocks that begin with a period are additionally marked as display: inline-block;. This should give the behaviour you are looking for, and additionally preserve all content when copy-pasting text.
CSS:
.no-wrap-hyphen {
white-space: nowrap;
}
.wrap-period {
display: inline-block;
}
JavaScript (run this function on window load and resize):
function wrapPeriodsNotHyphens() { // run on window load or resize
var codes = document.getElementsByTagName( "code" );
for ( var i = 0; i < codes.length; i++ ) {
currentCode = codes[ i ].innerHTML.split(/(?=[ .])/); // split by spaces and periods
for ( var c = 0; c < currentCode.length; c++ ) {
// surround each item with nowrap span
currentCode[ c ] = '<span class="no-wrap-hyphen">' + currentCode[ c ] + '</span>';
if ( currentCode[ c ].indexOf( '.' ) > -1 ) {
// add a zero size space at the start for periods
currentCode[ c ] = '<span class="wrap-period">' + currentCode[ c ] + '</span>';
}
}
codes[ i ].innerHTML = currentCode.join('');
}
}

Set cursor/selection for contenteditable div

Setting focus is simple enough: node.focus(). I've had limited success looking at other answers. I can set the cursor at either the beginning or end, or I can select the whole contents with this code in chrome:
// if start==0 means the beginning, start===1 means the end
function setSelection(node, start, length) {
var range = document.createRange();
range.setStart(node, start);
range.setEnd(node, length);
//range.collapse(true);
var selection = getSelection()
selection.removeAllRanges();
selection.addRange(range);
}
So the question is: how can I set the cursor more granularly, say at character 2. Also, how can I set the selection, for example from character 2 to character 5?
MDN tells me that Range.setStart has different behavior for Text, Comment, or CDATASection nodes than other nodes. If I could get setStart to treat a div like a Text node, I think my problem might be solved.
Anyone have any ideas?

highlight words in html using regex & javascript - almost there

I am writing a jquery plugin that will do a browser-style find-on-page search. I need to improve the search, but don't want to get into parsing the html quite yet.
At the moment my approach is to take an entire DOM element and all nested elements and simply run a regex find/replace for a given term. In the replace I will simply wrap a span around the matched term and use that span as my anchor to do highlighting, scrolling, etc. It is vital that no characters inside any html tags are matched.
This is as close as I have gotten:
(?<=^|>)([^><].*?)(?=<|$)
It does a very good job of capturing all characters that are not in an html tag, but I'm having trouble figuring out how to insert my search term.
Input: Any html element (this could be quite large, eg <body>)
Search Term: 1 or more characters
Replace Txt: <span class='highlight'>$1</span>
UPDATE
The following regex does what I want when I'm testing with http://gskinner.com/RegExr/...
Regex: (?<=^|>)(.*?)(SEARCH_STRING)(?=.*?<|$)
Replacement: $1<span class='highlight'>$2</span>
However I am having some trouble using it in my javascript. With the following code chrome is giving me the error "Invalid regular expression: /(?<=^|>)(.?)(Mary)(?=.?<|$)/: Invalid group".
var origText = $('#'+opt.targetElements).data('origText');
var regx = new RegExp("(?<=^|>)(.*?)(" + $this.val() + ")(?=.*?<|$)", 'gi');
$('#'+opt.targetElements).each(function() {
var text = origText.replace(regx, '$1<span class="' + opt.resultClass + '">$2</span>');
$(this).html(text);
});
It's breaking on the group (?<=^|>) - is this something clumsy or a difference in the Regex engines?
UPDATE
The reason this regex is breaking on that group is because Javascript does not support regex lookbehinds. For reference & possible solutions: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript.
Just use jQuerys built-in text() method. It will return all the characters in a selected DOM element.
For the DOM approach (docs for the Node interface): Run over all child nodes of an element. If the child is an element node, run recursively. If it's a text node, search in the text (node.data) and if you want to highlight/change something, shorten the text of the node until the found position, and insert a highligth-span with the matched text and another text node for the rest of the text.
Example code (adjusted, origin is here):
(function iterate_node(node) {
if (node.nodeType === 3) { // Node.TEXT_NODE
var text = node.data,
pos = text.search(/any regular expression/g), //indexOf also applicable
length = 5; // or whatever you found
if (pos > -1) {
node.data = text.substr(0, pos); // split into a part before...
var rest = document.createTextNode(text.substr(pos+length)); // a part after
var highlight = document.createElement("span"); // and a part between
highlight.className = "highlight";
highlight.appendChild(document.createTextNode(text.substr(pos, length)));
node.parentNode.insertBefore(rest, node.nextSibling); // insert after
node.parentNode.insertBefore(highlight, node.nextSibling);
iterate_node(rest); // maybe there are more matches
}
} else if (node.nodeType === 1) { // Node.ELEMENT_NODE
for (var i = 0; i < node.childNodes.length; i++) {
iterate_node(node.childNodes[i]); // run recursive on DOM
}
}
})(content); // any dom node
There's also highlight.js, which might be exactly what you want.

show tinymce contents in a div with flexible though maximum height

When using an editor like tinymce, how could i limit the height of the text a user enters so it doesn't use more space on the webpage than i want it to?
There are 2 things that i want some advise on:
In the editor:
The user enters text in a tinymce editor, he could set a text to font-size say 80px which would use up more space than a normal letter. So it's not the amount of text that i care about it's the height of the total.
In the webpage:
I don't want to give them more than say 200px worth of text on the page. But if they enter just 1 line of text with a small font-size i don't want to show a 200px space. So the height has to be flexible but with a maximum.
I know this isn't exact science but the goal here is to prevent the user from messing up the page.
To solve a similar issue i wrote the following function (placed inside an own tinymce plugin). You will need to add a variable for the maximum case and maybe tweak it a bit, but i hope this code will put you into the right direction
// this function will adjust the editors iframe height to fit in the editors content perfectly
resizeIframe: function(editor) {
var frameid = frameid ? frameid :editor.id+'_ifr';
var currentfr=document.getElementById(frameid);
if (currentfr && !window.opera){
currentfr.style.display="block";
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) { //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight + 26;
}
else if (currentfr.Document && currentfr.Document.body.scrollHeight) { //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
}
styles = currentfr.getAttribute('style').split(';');
for (var i=0; i<styles.length; i++) {
if ( styles[i].search('height:') ==1 ){
styles.splice(i,1);
break;
}
};
currentfr.setAttribute('style', styles.join(';'));
}
},