### Example Usage of ExtendScript Debugger Class Source: https://github.com/extendscript/wiki/wiki/Classes This example demonstrates how to integrate and utilize the 'Debugger' class within an ExtendScript project. It shows the necessary '#include' directive, global initialization of the debugger, and typical usage within a 'main' function, including displaying alerts, adding content to the debug log, and writing the final debug file. ```js #include 'Debugger.jsx';// include the file. needs to be next to this script var deeBug = new Debugger(true,"MyScript.jsx version 0.1.2","This is a debug version");// Debugger init global main(); function main(){ deeBug.message();// this is just an alert that only pops up if the debugger is true var something = 5; something++;// do something deeBug.addLineToInfo("This is a line in the file" + something); // add some content deeBug.writeInfos();// writes and opens a file } ``` -------------------------------- ### ExtendScript File Inclusion Source: https://github.com/extendscript/wiki/wiki/HEX-to-RGB-And-Sort Demonstrates how to specify include paths and include external JavaScript libraries like basil.js in an ExtendScript project, essential for modular code. ```ExtendScript #includepath "~/Documents/;%USERPROFILE%Documents"; #include "basiljs/bundle/basil.js"; ``` -------------------------------- ### Create and Manage InDesign Documents, Pages, and Text Frames with ExtendScript Source: https://github.com/extendscript/wiki/wiki/Pages-And-Margins This comprehensive ExtendScript example illustrates how to programmatically create a new InDesign document, define its properties (page size, bleed, grid), add multiple pages, connect text frames across pages, and apply custom margin and column settings. It includes functions for document setup (`doc_build`), main document flow (`main`), and calculating geometric bounds (`myGetBounds`). The `myGetBounds` function is adapted from the InDesign Scripting SDK's 'ImprovedHelloWorld.jsx' example. ```javascript /** * Lets build a doc */ main(); function main() { // add a doc var doc = app.documents.add(); // lets store some data in an object for better handling meta = { pw: 200, ph: 200, top: 20, left: 20, bottom: 20, right: 20, gutter: 5, textColumnCount: 5 }; // have a look at the build function below doc_build(doc, true, false, meta); // now lets make something with those pages var count = 0; // counter var range = 10; // until var frames = []; // to store the textFrames // now loop it while (count < range) { // the first page is always there // so we have to check if we are at index 0 var page; if (count != 0) { page = doc.pages.add(); // if not add a page } else { page = doc.pages[0]; // we are at index 0 take the existing page } // apply a master spread page.appliedMaster = doc.masterSpreads.item(0); // add a textFrame and push it into an array // for better handling frames.push(page.textFrames.add()); // now get the margins from the page // the get bounds function is part of the // Scripting Tutorial Hello World from the SDK frames[count].geometricBounds = myGetBounds(doc, page); // once again we have to check if we are at index 0 // because the textFrame 0 cant have a previous text frame // if we are not at 0 connect the actual textFrame with the previous if (count != 0) { frames[count].previousTextFrame = frames[count - 1]; } // now we change the gutter on every second text frame // just for the fun of it. // get the gutter from the page // and give the textFrame the same margins if (count % 2 == 0) { frames[count].textFramePreferences.properties = { textColumnCount: page.marginPreferences.columnCount / 2, textColumnGutter: page.marginPreferences.columnGutter }; } //increment the count for the next loop count++; } // add some placeholder text frames[0].contents = TextFrameContents.placeholderText; // The End return 0; } /** * Lets build a document * with lots of preferences */ function doc_build(doc, makeColumns, facingPages, meta) { doc.layers.item(0).name = "the standard layer"; doc.layers.add({ name: "a new layer" }); if (facingPages) { doc.documentPreferences.facingPages = true; } else { doc.documentPreferences.facingPages = false; } // set some view parameters doc.viewPreferences.properties = { horizontalMeasurementUnits: MeasurementUnits.MILLIMETERS, verticalMeasurementUnits: MeasurementUnits.MILLIMETERS }; // set the page size and bleed box doc.documentPreferences.properties = { pageWidth: meta.pw, pageHeight: meta.ph, documentBleedBottomOffset: 3, documentBleedTopOffset: 3, documentBleedInsideOrLeftOffset: 3, documentBleedOutsideOrRightOffset: 3 }; // the baseline settings doc.gridPreferences.properties = { baselineStart: meta.top }; // how big are the steps doc.gridPreferences.baselineDivision = "15pt"; // lets create some master spreads var master_spread1 = doc.masterSpreads.item(0).pages.item(0); // edit the master spreads master_spread1.marginPreferences.properties = { right: meta.right, top: meta.top, left: meta.left, bottom: meta.bottom + 10, columnGutter: meta.gutter * 2 }; var master_spread2 = doc.masterSpreads.item(0).pages.item(1); //edit the other master spread master_spread2.marginPreferences.properties = { right: meta.right, top: meta.top, left: meta.left, bottom: meta.bottom, columnGutter: meta.gutter }; if (makeColumns) { master_spread1.marginPreferences.columnCount = meta.textColumnCount * 2; master_spread2.marginPreferences.columnCount = meta.textColumnCount; } } // end make doc // part of //ImprovedHelloWorld.jsx from InDesign scripting SDK //An InDesign CS6 JavaScript function myGetBounds(myDocument, myPage) { var myPageWidth = myDocument.documentPreferences.pageWidth; var myPageHeight = myDocument.documentPreferences.pageHeight; if (myPage.side == PageSideOptions.leftHand) { var myX2 = myPage.marginPreferences.left; var myX1 = myPage.marginPreferences.right; } else { var myX1 = myPage.marginPreferences.left; var myX2 = myPage.marginPreferences.right; } var myY1 = myPage.marginPreferences.top; var myX2 = myPageWidth - myX2; var myY2 = myPageHeight - myPage.marginPreferences.bottom; return [myY1, myX1, myY2, myX2]; } ``` -------------------------------- ### Example ExtendScript (JSX) file content Source: https://github.com/extendscript/wiki/wiki/ExtendScript-Toolkit This is a simple ExtendScript (JSX) example that targets InDesign and displays an alert with the application's name. When executed with the `-run` flag, the `//@target` directive is respected, allowing the script to interact with the specified Adobe application. ```JavaScript //@target indesign alert(app.name); ``` -------------------------------- ### Calculate String Length in ExtendScript Source: https://github.com/extendscript/wiki/wiki/Functions This ExtendScript example defines a 'main' function that demonstrates how to calculate the length of different strings using a helper function 'calc_str_length'. It utilizes the 'length' property of strings and displays the result using 'alert'. ```JavaScript /* To keep your code tidy you can put code pieces together in a function. You can use them more than one time. Like this */ main(); // the main code function main() { var a_string = "Uh. I really want to know how many characters are in me!"; var res = calc_str_length(a_string); alert(res); var b_string = "lets see how many characters I have!"; res = calc_str_length(b_string); alert(res); // you don't need this return thing here // but it is cleaner that way // also have a look at the ESTK console return 0; } // the calc function function calc_str_length(str) { var l = str.length; return l; } ``` -------------------------------- ### ExtendScript Conditional Statement Examples Source: https://github.com/extendscript/wiki/wiki/Conditionals Demonstrates practical usage of `if`, `else`, and `else if` statements in ExtendScript, incorporating various comparison (`>`, `>=`, `==`, `!=`) and logical (`&&`) operators to control program flow based on variable values. ```JavaScript /* create conditions like this */ var a = 5; var b = 7; var c = 13; if (a > b) { alert(b + " is smaller than " + a); } else { alert(a + " is smaller than " + b); } if (a + b >= c) { alert(c); } else if (a + b == b + a) { alert("equal"); } else if (a > c && b > c) { alert("combined"); } else { alert("something else"); } if (a != "foo") { alert("bah!"); } ``` -------------------------------- ### Basic ExtendScript Progress Bar with $.sleep Source: https://github.com/extendscript/wiki/wiki/Progress-And-Delay This snippet creates a simple palette window with a progress bar and a start button. Clicking the button updates the progress bar using `$.sleep` for a delay, then displays an alert when complete. It demonstrates basic UI creation and progress updates. ```JavaScript var w = new Window("palette", "Progress Demo"); var pbar = w.add("progressbar", undefined, 0, 100); pbar.preferredSize = [300, 20]; var btn = w.add("button", undefined, "Start"); btn.onClick = function () { for (var i = 0; i <= 100; i++) { pbar.value = i; $.sleep(20); } alert("Done!"); }; w.show(); ``` -------------------------------- ### Create Basic Window with Resource String in ExtendScript Source: https://github.com/extendscript/wiki/wiki/Script-UI-Resource-Strings This ExtendScript example demonstrates how to define a complete UI layout using a single resource string. It creates a simple palette window with a button, setting its text, style, and `preferredSize` directly within the resource string. This method allows for concise UI definition. ```js // ex 05 basic window with resource string // define the wohle string var res = "palette{text:'Hello',\ btn: Button {text:'World!',\ properties: { style : 'toolbutton'},\ preferredSize:[125,25]}\ }"; //Or separate the string into it parts //var pal = "palette{text:'Hello'}"; var w = new Window(res); w.show(); ``` -------------------------------- ### Arithmetic and String Operations in JavaScript Source: https://github.com/extendscript/wiki/wiki/Variables-And-Operations Illustrates various arithmetic operators (+, -, *, /, %, ++, --, +=) and string concatenation in JavaScript. Includes examples of basic calculations, modulo operations, and combining strings with numerical results. ```JavaScript /* You can use operators to transform variables + - * / % = . ++ -- += -= *= /= like this */ var a = 10000; var b = 356; var res = b / a; alert(res); alert((5 % 4) + " modulo?"); // modulo var calc = (a / 100) * 13; alert(calc); var str = "Hi there buddy!" + "\n" + "The result is: "; alert(str + calc); calc += 5; calc++; calc--; calc = calc + 5; alert(calc); ``` -------------------------------- ### Example .command Shell Script Content Source: https://github.com/extendscript/wiki/wiki/Executing-Shell-Commands This snippet shows the basic structure of a `.command` file, which is a standard shell script (e.g., Bash) that can be made executable. Such files provide a straightforward way to encapsulate shell commands for later execution, often used as a target for ExtendScript's `execute()` method. ```shell #!/bin/bash ls ``` -------------------------------- ### Retrieving ExtendScript Application Version Source: https://github.com/extendscript/wiki/wiki/app This example shows how to access and display the name and version of the current ExtendScript application using the `app.name` and `app.version` properties. This can be useful for version-specific logic, compatibility checks, or providing informative messages to the user. ```ExtendScript alert(app.name + " v" + app.version); ``` -------------------------------- ### ExtendScript UI Element Sizing Without Explicit Bounds Source: https://github.com/extendscript/wiki/wiki/Script-UI-Resource-Strings This ExtendScript example illustrates UI element creation without explicitly defining `bounds`. It shows that button sizes automatically adjust based on the length of their `text` content when `bounds` are not set, resulting in a more natural, rounded appearance. The example also logs the automatically determined bounds, demonstrating the dynamic sizing behavior. ```javascript // ex global properties 02 // no defined bounds // define the window with 2 buttons var pal = "palette{text:'Buttons'}"; var grp = "group{\ orientation:'row',\ btnone: Button {\ text:'Hello!',\ enabled:false,\\ }\ btntwo: Button {text:'World!',\ helpTip:'some text',\ active:true,\\ }\ }"; var w = new Window(pal); w.g = w.add(grp); w.show(); $.writeln(w.g.btnone.bounds); $.writeln(w.g.btntwo.bounds); ``` -------------------------------- ### Writing to Console with $.writeln in ExtendScript Source: https://github.com/extendscript/wiki/wiki/Output-And-Interaction This example shows how to output text to the ExtendScript Toolkit (ESTK) console using `$.writeln()`. This method is essential for logging information, debugging, and tracing script execution without interrupting the user with dialogs. ```JavaScript var text = "write me into the console"; $.writeln(text); ``` -------------------------------- ### Bulk Document Creation and Text Addition with Dynamic Preferences in ExtendScript Source: https://github.com/extendscript/wiki/wiki/Documents Provides a comprehensive example of creating multiple documents in a loop, dynamically adjusting their page dimensions based on an initial data object. It then demonstrates how to add text frames with content to each created document using a helper function, showcasing advanced document manipulation. ```JavaScript /** * You can create objects with the same structure as * a documents to define values * and than in inject them within a loop * **!Achtung!** This works only in InDesign CS5+ */ main(); // everyting is in here function main() { var doc_data = { documentPreferences: { pageWidth: 10, pageHeight: 10, }, }; /* now you could do a lot of fancy stuff and still have your important data like the settings for the doc on the top of the script also you could place them into another file or something like this. */ // now loop and create some documents var i = 1; var num = 13; var arr = new Array(); while (i < num) { // do something fancy here doc_data.documentPreferences.pageWidth += 10; doc_data.documentPreferences.pageHeight += 10; // now push it into an array arr.push(app.documents.add(doc_data)); i++; } // add some text. just for fun add_text(arr); } /** * This function adds text to an doc * it takes an array of documents as argument */ function add_text(arr) { for (var j in arr) { var d = arr[j]; var pw = d.documentPreferences.pageWidth; var ph = d.documentPreferences.pageHeight; var gutter = pw / 10; var gb = [gutter, gutter, ph - gutter, pw - gutter]; var pg = d.pages.item(0); pg.textFrames.add({ geometricBounds: gb, contents: "I'm doc number " + j, }); } } ``` -------------------------------- ### String Manipulation and Array Processing with For Loop in JavaScript Source: https://github.com/extendscript/wiki/wiki/Loops A comprehensive example showcasing string splitting, array iteration using a `for` loop, and array joining. It includes detailed comments explaining loop mechanics, counter management, and the use of `break` and `continue` statements for loop control. ```JavaScript /* Loops */ // this is our string var source_string = "Hi there. I am a string please chop me into pieces"; var source_array = new Array(); // create a new array like this var target_array = []; // or like this var target_string; // this will hold our result var delimiter = " "; // this is what we use to split and join our string var source_array = source_string.split(delimiter); // split the string into an array alert("Source string: " + source_string + "\nTarget array:\n" + source_array); // lets see what it did /* Now loop that array we created there are three parts in this for loop construct var index = 0; // this is our counter than follows a condition index < source_array.length as long as this is true we do the third part index = index + 1; // we increment the index by one Than the condition loop block { } is executed when the block is done he will again check if the condition index < source_array.length is still true. If so increment by one and execute the block { } you can stop a loop by using break; like: if(index == 5){ break; } or step over one index by using if(index == 5){ continue } Play with it a lot. Don't worry you wont go blind */ for (var index = 0; index < source_array.length; index = index + 1) { target_array.push(source_array[index]); } // lets see what happened in the target array alert("Target array: " + target_array); // join the array again target_string = target_array.join(delimiter); // hey we got our string back alert("hey we got our string back:\n" + target_string); ``` -------------------------------- ### Reusable ExtendScript Progress Bar with Custom Delay Source: https://github.com/extendscript/wiki/wiki/Progress-And-Delay This example provides a more structured approach to progress bars in ExtendScript. It includes a `main` function, a `delay` function for custom time-based pauses, and a `progress_bar` function that creates and returns a progress bar for external updates. It's designed for more complex, multi-step operations. ```JavaScript // @target indesign main(); // main function everything happens in here function main() { var progress_win = new Window("palette"); // create new palette var progress = progress_bar( progress_win, 4, "Doing Something. Please be patient", ); // call the pbar function delay(1); // wait a second progress.value = progress.value + 1; // update the progress bar delay(1); // wait another second progress.value = progress.value + 1; // update the progress bar delay(5); // wait another second progress.value = progress.value + 1; // update the progress bar progress.parent.close(); // close the palette return 0; // we are done } // delay function found here //found here http://www.wer-weiss-was.de/theme157/article1143593.html function delay(prmSec) { prmSec *= 1000; // Dates work in milliseconds var eDate = null; var eMsec = 0; var sDate = new Date(); var sMsec = sDate.getTime(); do { eDate = new Date(); eMsec = eDate.getTime(); } while (eMsec - sMsec < prmSec); } /** * Taken from ScriptUI by Peter Kahrel * * @param {Palette} w the palette the progress is shown on * @param {[type]} stop [description] * @return {[type]} [description] */ function progress_bar(w, stop, labeltext) { var txt = w.add("statictext", undefined, labeltext); // add some text to the window var pbar = w.add("progressbar", undefined, 1, stop); // add the bar pbar.preferredSize = [300, 20]; // set the size w.show(); // show it return pbar; // return it for further use } ``` -------------------------------- ### Programmatic UI Creation with Window.add (ExtendScript) Source: https://github.com/extendscript/wiki/wiki/Script-UI-Resource-Strings This example illustrates a programmatic approach to building user interfaces in ExtendScript. It initializes a Window object and then iteratively adds button controls using the w.add() method, assigning text and preferred size directly to each button object. An event listener is attached to a specific button via its array index for interaction. ```ExtendScript var text = new Array( "Hello", "World", "This", "is", "your", "computer", "speaking", "!", "Keep", "coding", ); var numOButtons = 10; var w = new Window("palette", "lets talk nerd", undefined); var b = new Array(); for (var i = 0; i < numOButtons; i++) { b[i] = w.add("button", undefined, { style: "toolbutton" }); b[i].text = text[i]; b[i].preferredSize = [125, 25]; } b[6].onClick = function () { alert("still working. nifty ain't it?"); }; w.show(); ``` -------------------------------- ### Targeting Application and Accessing Properties in ExtendScript Source: https://github.com/extendscript/wiki/wiki/app This example illustrates how to explicitly target an Adobe application, such as InDesign, using the `#target` directive at the beginning of the script. It then accesses and displays the source representation of the application's color settings properties, demonstrating how to inspect application-specific configurations programmatically. ```ExtendScript #target indesign alert(app.colorSettings.properties.toSource()); ``` -------------------------------- ### Set Button Preferred Size in ExtendScript Source: https://github.com/extendscript/wiki/wiki/Script-UI-Resource-Strings This ExtendScript example demonstrates how to define a window palette and a group containing two buttons. It explicitly sets the `preferredSize` property for each button to control its dimensions, then prints their bounds to the console. This illustrates basic UI element sizing. ```js // ex global properties 03 // no define preferredSize: [WIDTH,HEIGHT] // define a window with 2 buttons var pal = "palette{text:'Buttons'}"; var grp = "group{\ orientation:'row',\ btnone: Button {\ text:'Hello!',\ preferredSize:[100,23]\ }\ btntwo: Button {text:'World!',\ preferredSize:[100,23]\ }\ }"; var w = new Window(pal); w.g = w.add(grp); w.show(); $.writeln(w.g.btnone.bounds); $.writeln(w.g.btntwo.bounds); ``` -------------------------------- ### Apply Geometric Bounds to a Rectangle in ExtendScript Source: https://github.com/extendscript/wiki/wiki/GeometricBounds-and-Coordinates This example demonstrates how to programmatically create a new InDesign document or use an existing one, add a rectangle to its first page, and then apply calculated `geometricBounds` to define the rectangle's size and position. It shows the full workflow from document handling to object manipulation. ```JavaScript var doc; // if there is no doc create one // if there is one - use it if (app.documents.length < 1) { doc = app.documents.add(); } else { doc = app.activeDocument; } var rect = doc.pages.item(0).rectangles.add(); var y1 = 10; var x1 = 10; var y2 = y1 + 100; var x2 = x1 + 100; var gb = [y1, x1, y2, x2]; rect.geometricBounds = gb; ``` -------------------------------- ### Creating InDesign Document with Text Frame and Iterating Content using ExtendScript Source: https://github.com/extendscript/wiki/wiki/ExtendScript-in-InDesign-Scripting-DOM This ExtendScript snippet demonstrates how to programmatically create a new InDesign document, add a text frame to its first page, and populate it with content. It calculates geometric bounds for the text frame based on document preferences. The example then iterates through paragraphs and words within the text frame, displaying their contents using alert(), showcasing basic text manipulation and DOM traversal. ```javascript /* As in javascript in the ID DOM everything is an object you can for example add a doc with a text frame on the first page with */ var aString = "Hello World!\rHello Dude. How are you?\rFine and you?"; var doc = app.documents.add(); var pg = doc.pages[0]; var d_pref = doc.documentPreferences; var pw = d_pref.pageWidth; var ph = d_pref.pageHeight; var x1 = 13; var y1 = 13; var x2 = pw - x1; var y2 = ph - y1; var gb = [y1, x1, y2, x2]; var tf = pg.textFrames.add(); tf.geometricBounds = gb; tf.contents = aString; for (var i = 0; i < tf.paragraphs.length; i++) { var par = tf.paragraphs[i]; alert(par + "-->" + par.contents); for (var j = 0; j < par.words.length; j++) { alert(par.words[j].contents); } } ``` -------------------------------- ### Define ExtendScript UI Buttons with Preferred Size Source: https://github.com/extendscript/wiki/wiki/Script-UI-Resource-Strings This JavaScript code demonstrates creating ExtendScript UI buttons using the `preferredSize` property. Instead of fixed `bounds`, this property suggests a desired width and height, allowing the layout manager to adjust. The example creates two buttons with specified preferred sizes and then prints their actual `bounds` after layout. ```JavaScript // ex button properties 02 // no define preferredSize: [WIDTH,HEIGHT] // define a window with 2 buttons var pal = "palette{text:'Buttons'}"; var grp = "group{\n orientation:'row',\n btnone: Button {\n text:'Hello!',\n preferredSize:[100,23]\n }\n btntwo: Button {text:'World!',\n preferredSize:[100,23]\n }\n }"; var w = new Window(pal); w.g = w.add(grp); w.show(); $.writeln(w.g.btnone.bounds); $.writeln(w.g.btntwo.bounds); ``` -------------------------------- ### Inspecting Selected Item Type in ExtendScript Source: https://github.com/extendscript/wiki/wiki/app This snippet demonstrates how to get the constructor name of the first selected item in the active application using `app.selection[0].constructor.name`. It requires a page and a selected item to be present in the application, and is useful for identifying the type of object currently selected for conditional processing. ```ExtendScript alert(app.selection[0].constructor.name); ``` -------------------------------- ### Setting UI Element Properties with Bounds in ExtendScript Source: https://github.com/extendscript/wiki/wiki/Script-UI-Resource-Strings This ExtendScript example demonstrates how to define a UI palette with two buttons, explicitly setting their `text`, `enabled`, `active`, `helpTip`, and `bounds` properties. It highlights how `bounds` can cause elements to overlap if not carefully managed, and shows how to inspect the final calculated bounds after layout, illustrating the effect of parent `margin` and `spacing`. ```javascript // global properties 01 // define the a window with 2 buttons string var pal = "palette{text:'Buttons'}"; var grp = "group{\ orientation:'row',\ btnone: Button {\ text:'Hello!',\ enabled:false,\ bounds:[0,0,100,100]\ }\ btntwo: Button {text:'World!',\ helpTip:'some text',\ active:true,\ bounds:[0,0,100,100]\ }\ }"; var w = new Window(pal); w.g = w.add(grp); w.show(); $.writeln(w.g.btnone.bounds); $.writeln(w.g.btntwo.bounds); ``` -------------------------------- ### Generate German Placeholder Text with ExtendScript Source: https://github.com/extendscript/wiki/wiki/Text-Find-Locations This ExtendScript function provides a static block of German placeholder text, commonly known as 'Blindtext'. It demonstrates how to include and handle Unicode characters within a string literal in ExtendScript. The function takes no arguments and simply returns the pre-defined string. ```ExtendScript function create_placeholder() { var the_text = "Ich bin Blindtext. Von Geburt an.\r" + "Es hat lange gedauert, bis ich begriffen habe,\r" + "was es bedeutet, ein blinder Text zu sein:\r" + "Man macht keinen Sinn. Man wirkt hier und da aus dem Zusammenhang gerissen.\r" + "Oft wird man gar nicht erst gelesen.\r" + "Aber bin ich deshalb ein schlechter Text?\r" + "Ich wei\u00df, dass ich nie die Chance haben werde im Stern zu erscheinen.\r" + "Aber bin ich darum weniger wichtig? Ich bin blind!\r" + "Aber ich bin gerne Text.\r" + "Und sollten Sie mich jetzt tats\u00E4chlich zu Ende lesen,\r" + "dann habe ich etwas geschafft, was den meisten 'normalen' Texten nicht gelingt.\r" + "Ich bin Blindtext. Von Geburt an.\r" + "Es hat lange gedauert, bis ich begriffen habe, was es bedeutet, ein blinder Text zu sein:\r" + "Man macht keinen Sinn. Man wirkt hier und da aus dem Zusammenhang gerissen.\r" + "Oft wird man gar nicht erst gelesen. Aber bin ich deshalb ein schlechter Text?\r" + "Ich wei\u00df, dass ich nie die Chance haben werde im Stern zu erscheinen.\r" + "Aber bin ich darum weniger wichtig? Ich bin blind!\r" + "Aber ich bin gerne Text.\r" + "Und sollten Sie mich jetzt tats\u00E4chlich zu Ende lesen, dann habe ich etwas geschafft,\r" + "was den meisten 'normalen' Texten nicht gelingt. Ich bin Blindtext."; return the_text; } // end of placeholder text function ``` -------------------------------- ### Remove Empty Swatch Groups in Illustrator Source: https://github.com/extendscript/wiki/wiki/swatchGroups This ExtendScript snippet iterates through all swatch groups in the active Illustrator document and removes any groups that contain no swatches. It uses `app.activeDocument` to get the current document and `doc.swatchGroups` to access the swatch groups. The `getAllSwatches()` method is used to check if a group is empty, allowing for cleanup of the document's swatch panel. ```js var doc = app.activeDocument; // get the doc // loop all groups and remove the empty ones for (var i = doc.swatchGroups.length - 1; i >= 0; i--) { // alert(doc.swatchGroups[i].getAllSwatches()) if (doc.swatchGroups[i].getAllSwatches() == "") { //$.writeln('group "' + doc.swatchGroups[i].name + '" is empty. removing it!'); //Enable this line for testing only doc.swatchGroups[i].remove(); } else { //$.writeln(doc.swatchGroups[i].name + ' group is not empty'); //Enable this line for testing only } } ``` -------------------------------- ### Find Selected Character Coordinates in InDesign ExtendScript Source: https://github.com/extendscript/wiki/wiki/Text-Find-Locations This script demonstrates how to retrieve the horizontalOffset and baseline coordinates of a single selected character in an InDesign document. It alerts the user if no character or multiple items are selected, guiding them to select only one character for the script to function correctly. ```JavaScript /* You need a doc with text select only one character */ if (app.selection[0] instanceof Character) { var x = app.selection[0].horizontalOffset; var y = app.selection[0].baseline; alert( "Your selected character is at these coordiantes:\n" + "x: " + x + " y: " + x, ); } else { alert("Please select only one character"); } ``` -------------------------------- ### Creating a New Document and Setting Preferences Step-by-Step in ExtendScript Source: https://github.com/extendscript/wiki/wiki/Documents Illustrates how to create a new document and then set its page width and height properties individually using the `documentPreferences` object. This method is useful for understanding property assignment but can be verbose. ```JavaScript var doc = app.documents.add(); var val = 150; var prefs = doc.documentPreferences; prefs.pageWidth = val; prefs.pageHeight = val; ``` -------------------------------- ### Find Word Locations and Draw Lines in InDesign ExtendScript Source: https://github.com/extendscript/wiki/wiki/Text-Find-Locations This comprehensive ExtendScript example finds occurrences of a specified word (e.g., 'ich') within an InDesign document using built-in find and change options. It then draws graphic lines from a defined origin point on the page to the horizontalOffset and baseline coordinates of each found word. The example also illustrates a common challenge with simple string searches, where partial matches (e.g., 'ich' in 'mich') can occur, suggesting the need for more advanced text or GREP searches for better control. ```JavaScript main(); function main() { var pw = 200; // for easier handling var ph = 200; // for easier handling /* These functions build a basic setup this is for better reuse */ var placeholder_text = create_placeholder(); // this is the placeholder text var result_of_doc_setup = basic_doc_setup(pw, ph, false, placeholder_text); alert("This is the result of the doc setup function:" + result_of_doc_setup); // have a look at the result of the setup function /* separate the result of the setup function into single variables. for better handling */ var doc = result_of_doc_setup[0]; // This is a doc var page = result_of_doc_setup[1]; // This is a page var tFrame = result_of_doc_setup[2]; // this is our text frame /* The next function uses the built-in search options to find a user defined word and returns an object that looks like this { "word":"Hello World", "position":[100,200] } down and inspect the function with care the trick is to look for an objects var x = Object.horizontalOffset; var y = Object.baseline; This only works with Text not with graphic objects Go down and look into the function */ var result_of_search = text_find_word(doc, "ich"); // lets have a detailed look // first use toSource() to get the object as string // split the string into an array by "," // joined the string with a break line // this is only for display alert( "This is the result of the search:\n" + result_of_search.toSource().split(",").join("\n"), ); // these variables are for better handling var radius = 2.5; // this is the radius of a oval we will draw var origin_x = pw / 2; // this is its x loc var origin_y = 0; // this is the y loc // create a circle on top of the page var origin = page.ovals.add(); origin.geometricBounds = [ origin_y - radius, origin_x - radius, origin_y + radius, origin_x + radius, ]; origin.fillColor = doc.swatches.item(3); /* That's black on creation */ // now loop through the results and draw a line from every words location // to the origin oval for (var i = 0; i < result_of_search.length; i++) { var res_x = result_of_search[i].position[0]; // this is x of the result var res_y = result_of_search[i].position[1]; // this is y of the result var gl = page.graphicLines.add(); // set the anchors of the graphicLine gl.paths.item(0).pathPoints[0].anchor = [origin_x, origin_y]; gl.paths.item(0).pathPoints[1].anchor = [res_x, res_y]; } // end of loop } // end of main function /* This uses the find and change options to find the location of a word */ function text_find_word(the_doc, word_string) { app.findTextPreferences = NothingEnum.nothing; // now empty the find what field!!! that's important!!! app.changeTextPreferences = NothingEnum.nothing; // empties the change to field!!! that's important!!! var result = new Array(); // this will be our return value app.findTextPreferences.findWhat = word_string; // set the find what field var fc_result = the_doc.findText(); // execute the search findText() returns an Array // alert(fc_result.length); // now loop thru the results for (var i = 0; i < fc_result.length; i++) { var x = fc_result[i].horizontalOffset; var y = fc_result[i].baseline; /* There are also these two options endBaseline - Vertical offset of the end of the text. endHorizontalOffset - Horizontal offset of the end of the text. */ // create an object and push it into the array result.push({ word: word_string, position: [x, y] }); } // this returns an array of objects return result; } // end of text_find_word function /* ``` -------------------------------- ### User Interaction with Alert, Prompt, and Confirm in ExtendScript Source: https://github.com/extendscript/wiki/wiki/Output-And-Interaction This snippet illustrates how to interact with the user in ExtendScript using `confirm()`, `prompt()`, and `alert()` functions. It demonstrates conditional logic based on user input from a confirmation dialog and captures text input from a prompt, then displays it. ```JavaScript var res = null; res = confirm("Hello World?", false, "Title WIN only"); if (res == true) { res = prompt("Enter something:", "Hello World!", "Title WIN only"); alert(res); } else if (res == false) { alert("nothing to see here. Move along!"); } ``` -------------------------------- ### Set Checkbox and Slider Preferred Size in ExtendScript Source: https://github.com/extendscript/wiki/wiki/Script-UI-Resource-Strings This ExtendScript example expands on UI element sizing by demonstrating how to apply `preferredSize` to a checkbox and a slider within a palette. It shows how to define a window with a group containing a checkbox, a button, and a slider, each with specified dimensions. The example highlights that while `preferredSize` sets the component's space, text within a checkbox might not stretch to fill it. ```js // ex global properties 04 // no define preferredSize: [WIDTH,HEIGHT] // define a window with 2 buttons var pal = "palette{text:'Buttons'}"; var grp = "group{\ orientation:'row',\ chkbbxone: Checkbox {\ text:'Hello!',\ value:true,\ preferredSize:[100,23]\ }\ btnone: Button {text:'World!',\ preferredSize:[100,23]\ }\ sldr: Slider{text:'Slider',\ preferredSize:[600,23]\ }\ }"; var w = new Window(pal); w.g = w.add(grp); w.show(); $.writeln(w.g.chkbbxone.bounds); $.writeln(w.g.btnone.bounds); ``` -------------------------------- ### Create Folder and Write File in ExtendScript Source: https://github.com/extendscript/wiki/wiki/File This ExtendScript snippet demonstrates how to create a new folder on the user's desktop if it doesn't already exist, and then create a new text file within that folder, writing content to it. It uses Folder.desktop for the base path and handles file opening and closing. ```JavaScript // Folder.desctop A Folder object for the folder that contains the user’s desktop. Read only. var myFolder = Folder(Folder.desktop.absoluteURI + "/testing"); if (myFolder.exists !== true) { myFolder.create(); } var f = new File(myFolder.absoluteURI + "/file.txt"); f.open("w"); f.write("test"); f.close(); ```