I use Extendscript to help me review students' work in InDesign. I run a script that goes through a document and creates a report. One of the things I need to list on that report is wether or nor unused paragraph styles exist, preferably also listing their names.
I tried:
Searching the documentation for a property that might indicate if the
paragraph style is being used or not.
Invoking (.invoke() method) the Select All Unused action from the
Paragraph Styles panel. I explored adding event listeners and looking for any results, and also exploring the Panel documentation to check for a selection. According to an older topic here - InDesign scripting, get the items selected in a panel -, this is not possible.
I also considered looping through all stories and paragraphs, checking for the styles in use, and accounting for styles used inside other styles. However, I feel there should be a simpler alternative.
EDIT: The point is to avoid manual, tedious and error-prone work for about 5 exercises x 60 students per semester. The report already includes many other things, like page size, bleed, margins, parent page columns and application, text style options, baseline grid, etc. This script saves me a HUGE amount of time and makes it less likely that I'll forget to check for anything in particular. That's why I'm trying to integrate as many features as possible into it, so the individual manual work is reduced to the absolute minimum.
After choosing "Select All Unused" from the Paragraph Styles panel, you should be able to click the trash can icon to delete those styles. The same should work for the Character Styles panel.
I wondered if ChatGPT was smart enough to figure this out. It helped, but couldn't deliver a full solution. We went through 10 different versions before getting close to the working version of the script below.
Here's my final version:
var myDocument = app.activeDocument;
// Get all the character styles in the document
var allCharacterStyles = myDocument.allCharacterStyles;
// Loop through each character style
for (var i = 0; i < allCharacterStyles.length; i++) {
var style = allCharacterStyles[i];
// Set the search criteria for the findText() method
app.findTextPreferences = NothingEnum.nothing;
app.findTextPreferences.appliedCharacterStyle = style;
// Search entire document for instances of the character style
var found = myDocument.findText();
// If the style is not found in the document, delete it
if (found.length == 0) {
try {
style.remove();
} catch (e) {
// Ignore the error
}
}
// Reset the findTextPreferences object
app.findTextPreferences = NothingEnum.nothing;
}
// Repeat the above for Paragraph Styles
// Get all the paragraph styles in the document
var allParagraphStyles = myDocument.allParagraphStyles;
// Loop through each paragraph style
for (var i = 0; i < allParagraphStyles.length; i++) {
var style = allParagraphStyles[i];
// Set the search criteria for the findText() method
app.findTextPreferences = NothingEnum.nothing;
app.findTextPreferences.appliedParagraphStyle = style;
// Search entire document for instances of the style
var found = myDocument.findText();
// If the style is not found in the document, delete it
if (found.length == 0) {
try {
style.remove();
} catch (e) {
// Ignore the errors
}
}
// Reset the findTextPreferences object
app.findTextPreferences = NothingEnum.nothing;
}
And here's a version that generates a report showing a list of unused paragraph styles. Again, ChatGPT can help with some, but it couldn't produce a final version. My edited and tested script appears below.
var myDocument = app.activeDocument;
// Create an array to store the names of unused styles
var unusedStyles = [];
// Get all the paragraph styles in the document
var allParagraphStyles = myDocument.allParagraphStyles;
// Loop through each paragraph style
for (var i = 0; i < allParagraphStyles.length; i++) {
var style = allParagraphStyles[i];
// Set the search criteria for the findText() method
app.findTextPreferences = NothingEnum.nothing;
app.findTextPreferences.appliedParagraphStyle = style;
// Search for instances of the style in the document
var found = myDocument.findText();
// If the style is not found in the document, add it to the list of unused styles
if (found.length == 0) {
unusedStyles.push("Paragraph style: " + style.name);
}
// Reset the findTextPreferences object
app.findTextPreferences = NothingEnum.nothing;
}
// Create a new text frame to hold the report text
var textFrame = myDocument.pages[0].textFrames.add();
textFrame.geometricBounds = [3, 18, 36, 3];
// Insert the list of unused styles into the text frame
for (var i = 0; i < unusedStyles.length; i++) {
textFrame.contents += unusedStyles[i] + "\n";
}
Related
I've created a very basic script that allows the user to replace a specific font in all the document (even LayerSets) by another one.
A practice example: I want to substitute all Arial-Bold by Arial-Italic, but some of the TextLayers have Arial-Bold and Arial-Regular inside the same Layer, how can make that the script only changes the Arial-Bold part of the TextLayer and not the whole layer?
Code I'm currently using:
var inFont = prompt("write inFont","Write inFont");
var outFont = prompt("write outFont","Write outFont");
app.preferences.typeUnits = TypeUnits.PIXELS;
var doc = app.activeDocument;
function changeFonts(target){
var layers = target.layers;
for(var i=0;i<layers.length;i++){
if(layers[i].typename == "LayerSet"){
changeFonts(layers[i]);
} else {
if((layers[i].kind == LayerKind.TEXT) && (layers[i].textItem.font == inFont)) {
layers[i].textItem.font = outFont;
};
};
};
};
changeFonts(doc);
I would assume you would have to crawl through the text and look at each individual character. Here is an article that that talks about formatting specific character ranges. Formatting text ranges.
You could use something like this to loop through the text one character at a time, check the formatting and change it if needed. I can't think of any other way to approach this.
I am trying to implement a rudimentary site search for a page of images. The search function should go through each element in a specific class looking for a word match in the image's alt text.
I think my issue is with binding the function to a form submit but I can't seem to figure out where I went wrong.
I have tried this with jQuery (fiddle:http://jsfiddle.net/u2oewez4/)
$(document).ready(function(){
$("#search-form").click(function() {
var searchQuery = "Text";
$.each('.single-image', function(){
$(this).children("img").attr("alt"):contains(searchQuery).hide("slow");
});
});
});
As well as with JavaScript (fiddle:http://jsfiddle.net/m3LkxL1c/)
function submitSearch(){
// create regex with query
var searchQuery = new RegExp(document.getElementById('search-input').value);
// create array of content to look for query in
var content = document.getElementsByClassName("single-image");
// create an array to put the results to hide in
var hideResults = [];
var imagesToHide = document.getElementsByClassName("single-image-hide");
// get the current display value
var displaySetting = imagesToHide.style.display;
for (i=0; i<content.length; i++) {
if (! searchQuery.test(content[i].firstChild.firstChild.nodeValue)) {
// if the query not found for this result in query
hideResults.push(content[i]);
// push to the hideResults array
content[i].className = "single-image-hide";
// change class name so CSS can take care of hiding element
document.getElementById("form-success").style.display = 'inline-block';
alert(searchQuery); // for debugging
return false; // results will not stick without this?
}
}
// set display to hidden
if(displaySetting == 'inline-block'){
imagesToHide.style.display = 'none'; // map is visible, so hide it
}
else{
imagesToHide.style.display = 'inline-block'; // map is hidden so show it
}
}
FYI I have built the JQuery off a few StackOverflow threads, so I've definitely tried my best to find a similar example. (Similar functions: here, and here)
Okay, various bug fixes, most of which I noted in the comments already because I wanted to make sure not to miss any. You need to read the details for in the jQuery documentation much more closely. That'll fix a lot of the problems you're having, like using the wrong each function. Other things will come with time. Keep studying, and READ THE DOCUMENTATION.
$("#search-form").click(function() {
//this gets the val for the search box, then puts the Imgs in a variable so we don't have to use the selector multiple times. Selectors are expensive time-wise, stored variables are not.
var searchQuery = $("#search-text").val(),
singleImgs = $('.single-image');
//you have to show the images for each new iteration, or they'll remain hidden
singleImgs.show();
singleImgs.each(function(){
//get alt attribute
var thisAlt = $(this).find("img").attr("alt");
//if thisAlt does not contains searchQuery (use > instead of === for does)
if(thisAlt.indexOf(searchQuery) === -1){
$(this).hide();
}
});
});
working fiddle
Similar to my earlier problems with finding a textFrame on a page based on its geometricBounds or by part of its name, I now am running into the problem of finding textFrames if they are inside groups. If I use an array of all textFrames, such as:
var textFramesArray = document.textFrames.everyItem().getElements();
it will not find any textFrames that are inside of a group. How can I figure out how to reference a textFrame if it's inside a group? Even if the group has to be un-grouped, that's fine, but I cannot even figure out how to find groups on the page!
Groups on a page are page.groups ... but you don't need this anyway. Fabian's answer is good, but it doesn't take groups-in-groups into account -- nor clipping masks, nor text frames inside tables and footnotes (etc.).
Here is an alternative approach: allPageItems is pretty much guaranteed to return all page items, of all kinds and persuasion, inside groups or other frames or whatnot. You can inspect, then process, each of them in turn, or build an array of text frames to work with at leisure:
allframes = app.activeDocument.allPageItems;
textframes = [];
for (i=0; i<allframes.length; i++)
{
if (allframes[i] instanceof TextFrame)
textframes.push(allframes[i]);
}
alert (textframes.length);
Try this:
// this script needs:
// - a document with one page
// - some groups with textframes in it on the first page
var pg = app.activeDocument.pages[0];
var groups = pg.groups;
var tf_ingroup_counter = 0;
for(var g = 0; g < groups.length;g++){
var grp = groups[g];
for(var t = 0; t < grp.textFrames.length;t++){
var tf = grp.textFrames[t];
if(tf instanceof TextFrame){
tf_ingroup_counter++;
}
}
}
alert("I found on page " + pg.name +"\n" + pg.textFrames.length
+" textframes\nOh and there are also "
+tf_ingroup_counter+ " hidden in groups");
Your task to get all the text frames in the layer or the document. Whether those text frames are in a group or not. This is done through the property of allPageItems. For instance use this:-
var items=app.activeDocument.allPageItems;
this will give you all the text frames in the item and within group also. Now you can do any manupulations. You can check the items on the debug console which will give all the types of the objects.And then you can check for the textframe
items[i].constructor.name =='TextFrame'
and now you can store each object in type array.
Is it possible to use Javascript in Safari/Firefox/Chrome to search a particular div container for a given text string. I know you can use window.find(str) to search the entire page but is it possible to limit the search area to the div only?
Thanks!
Once you look up your div (which you might do via document.getElementById or any of the other DOM functions, various specs here), you can use either textContent or innerText to find the text of that div. Then you can use indexOf to find the string in that.
Alternately, at a lower level, you can use a recursive function to search through all text nodes in the window, which sounds a lot more complicated than it is. Basically, starting from your target div (which is an Element), you can loop through its childNodes and search their nodeValue string (if they're Texts) or recurse into them (if they're Elements).
The trick is that a naive version would fail to find "foo" in this markup:
<p><span>fo</span>o</p>
...since neither of the two Text nodes there has a nodeValue with "foo" in it (one of them has "fo", the other "o").
Depending on what you are trying to do, there is an interesting way of doing this that does work (does require some work).
First, searching starts at the location where the user last clicked. So to get to the correct context, you can force a click on the div. This will place the internal pointer at the beginning of the div.
Then, you can use window.find as usual to find the element. It will highlight and move toward the next item found. You could create your own dialog and handle the true or false returned by find, as well as check the position. So for example, you could save the current scroll position, and if the next returned result is outside of the div, you restore the scroll. Also, if it returns false, then you can say there were no results found.
You could also show the default search box. In that case, you would be able to specify the starting position, but not the ending position because you lose control.
Some example code to help you get started. I could also try putting up a jsfiddle if there is enough interest.
Syntax:
window.find(aStringToFind, bCaseSensitive, bBackwards, bWrapAround, bWholeWord, bSearchInFrames, bShowDialog);
For example, to start searching inside of myDiv, try
document.getElementById("myDiv").click(); //Place cursor at the beginning
window.find("t", 0, 0, 0, 0, 0, 0); //Go to the next location, no wrap around
You could set a blur (lose focus) event handler to let you know when you leave the div so you can stop the search.
To save the current scroll position, use document.body.scrollTop. You can then set it back if it trys to jump outside of the div.
Hope this helps!
~techdude
As per the other answer you won't be able to use the window.find functionality for this. The good news is, you won't have to program this entirely yourself, as there nowadays is a library called rangy which helps a lot with this. So, as the code itself is a bit too much to copy paste into this answer I will just refer to a code example of the rangy library that can be found here. Looking in the code you will find
searchScopeRange.selectNodeContents(document.body);
which you can replace with
searchScopeRange.selectNodeContents(document.getElementById("content"));
To search only specifically in the content div.
If you are still looking for someting I think I found a pretty nice solution;
Here it is : https://www.aspforums.net/Threads/211834/How-to-search-text-on-web-page-similar-to-CTRL-F-using-jQuery/
And I'm working on removing jQuery (wip) : codepen.io/eloiletagant/pen/MBgOPB
Hope it's not too late :)
You can make use of Window.find() to search for all occurrences in a page and Node.contains() to filter out unsuitable search results.
Here is an example of how to find and highlight all occurrences of a string in a particular element:
var searchText = "something"
var container = document.getElementById("specificContainer");
// selection object
var sel = window.getSelection()
sel.collapse(document.body, 0)
// array to store ranges found
var ranges = []
// find all occurrences in a page
while (window.find(searchText)) {
// filter out search results outside of a specific element
if (container.contains(sel.anchorNode)){
ranges.push(sel.getRangeAt(sel.rangeCount - 1))
}
}
// remove selection
sel.collapseToEnd()
// Handle ranges outside of the while loop above.
// Otherwise Safari freezes for some reason (Chrome doesn't).
if (ranges.length == 0){
alert("No results for '" + searchText + "'")
} else {
for (var i = 0; i < ranges.length; i++){
var range = ranges[i]
if (range.startContainer == range.endContainer){
// Range includes just one node
highlight(i, range)
} else {
// More complex case: range includes multiple nodes
// Get all the text nodes in the range
var textNodes = getTextNodesInRange(
range.commonAncestorContainer,
range.startContainer,
range.endContainer)
var startOffset = range.startOffset
var endOffset = range.endOffset
for (var j = 0; j < textNodes.length; j++){
var node = textNodes[j]
range.setStart(node, j==0? startOffset : 0)
range.setEnd(node, j==textNodes.length-1?
endOffset : node.nodeValue.length)
highlight(i, range)
}
}
}
}
function highlight(index, range){
var newNode = document.createElement("span")
// TODO: define CSS class "highlight"
// or use <code>newNode.style.backgroundColor = "yellow"</code> instead
newNode.className = "highlight"
range.surroundContents(newNode)
// scroll to the first match found
if (index == 0){
newNode.scrollIntoView()
}
}
function getTextNodesInRange(rootNode, firstNode, lastNode){
var nodes = []
var startNode = null, endNode = lastNode
var walker = document.createTreeWalker(
rootNode,
// search for text nodes
NodeFilter.SHOW_TEXT,
// Logic to determine whether to accept, reject or skip node.
// In this case, only accept nodes that are between
// <code>firstNode</code> and <code>lastNode</code>
{
acceptNode: function(node) {
if (!startNode) {
if (firstNode == node){
startNode = node
return NodeFilter.FILTER_ACCEPT
}
return NodeFilter.FILTER_REJECT
}
if (endNode) {
if (lastNode == node){
endNode = null
}
return NodeFilter.FILTER_ACCEPT
}
return NodeFilter.FILTER_REJECT
}
},
false
)
while(walker.nextNode()){
nodes.push(walker.currentNode);
}
return nodes;
}
For the Range object, see https://developer.mozilla.org/en-US/docs/Web/API/Range.
For the TreeWalker object, see https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker
var elements = [];
$(document).find("*").filter(function () {
if($(this).text().contains(yourText))
elements.push($(this));
});
console.log(elements);
I didn't try it, but according the jQuery documentation it should work.
Here is how I am doing with jquery:
var result = $('#elementid').text().indexOf('yourtext') > -1
it will return true or false
Maybe you are trying to not use jquery...but if not, you can use this $('div:contains(whatyouarelookingfor)') the only gotcha is that it could return parent elements that also contain the child div that matches.
The Problem
I am trying to figure out the offset of a selection from a particular node with javascript.
Say I have the following HTML
<p>Hi there. This <strong>is blowing my mind</strong> with difficulty.</p>
If I select from blowing to difficulty, it gives me the offset from the #text node inside of the <strong>. I need the string offset from the <p>'s innerHTML and the length of the selection. In this case, the offset would be 26 and the length would be 40.
My first thought was to do something with string offsets, etc. but you could easily have something like
<p> Hi there. This <strong>is awesome</strong>. For real. It <strong>is awesome</strong>.</p>
which would break that method because there are identical nodes. I also need the option to throw out nodes. Say I have something like this
<p>Hi there. This <strong>is blowing my mind</strong> with difficulty.</p>
I want to throw out an elements with rel="inserted" when I do the calculation. I still want 26 and 40 as the result.
What I'm looking for
The solution needs to be recursive. If there was a <span> with a <strong> in it, it would still need to traverse to the <p>.
The solution needs to remove the length of any element with rel="inserted". The contents are important, but the tags themselves are not. All other tags are important. I'd strongly prefer not to remove any elements from the DOM when I do all of this.
I am using document.getSelection() to get the selection object. This solution only has to work in WebKit. jQuery is an option, but I'd prefer to it without it if possible.
Any ideas would be greatly appreciated.
I have no control over the HTML I doing all of this on.
I think I solved my issue. I ended not calculating the offset like I originally planned. I am storing the "path" from the chunk (aka <p>). Here is the code:
function isChunk(node) {
if (node == undefined || node == null) {
return false;
}
return node.nodeName == "P";
}
function pathToChunk(node) {
var components = new Array();
// While the last component isn't a chunk
var found = false;
while (found == false) {
var childNodes = node.parentNode.childNodes;
var children = new Array(childNodes.length);
for (var i = 0; i < childNodes.length; i++) {
children[i] = childNodes[i];
}
components.unshift(children.indexOf(node));
if (isChunk(node.parentNode) == true) {
found = true
} else {
node = node.parentNode;
}
}
return components.join("/");
}
function nodeAtPathFromChunk(chunk, path) {
var components = path.split("/");
var node = chunk;
for (i in components) {
var component = components[i];
node = node.childNodes[component];
}
return node;
}
With all of that, you can do something like this:
var p = document.getElementsByTagName('p')[0];
var piece = nodeAtPathFromChunk(p, "1/0"); // returns desired node
var path = pathToChunk(piece); // returns "1/0"
Now I just need to expand all of that to support the beginning and the end of a selection. This is a great building block though.
What does this offset actually mean? An offset within the innerHTML of an element is going to be extremely fragile: any insertion of a new node or change to an attribute of an element preceding the point in the document the offset represents is going to make that offset invalid.
I strongly recommend using the browser's built-in support for this in the form of DOM Range. You can get hold of a range representing the current selection as follows:
var range = window.getSelection().getRangeAt(0);
If you're going to be manipulating the DOM based on this offset that you want, you're best off doing so using nodes instead of string representations of those nodes.
you can use the following java script code:
var text = window.getSelection();
var start = text.anchorOffset;
alert(start);
var end = text.focusOffset - text.anchorOffset;
alert(end);
Just check if your selected element is a paragraph, and if not use something like Prototype's Element.up() method to select the first paragraph parent.
For example:
if(selected_element.nodeName != 'P') {
parent_paragraph = $(selected_element).up('p');
}
Then just find the difference between the parent_paragraph's text offset and your selected_element's text offset.
Maybe you could use the jQuery selectors to ignore the rel="inserted"?
$('a[rel!=inserted]').doSomething();
http://api.jquery.com/attribute-not-equal-selector/
What code are you using now to select from blowing to difficulty?