20 Replies Latest reply on Mar 10, 2011 2:09 AM by Jeremy bowmangraphics

    Newbie question

    Rocksand1 Level 1

      I don't have much experience with scripts. Everytime I run one, it applies to every image box on the page. If I select certain frames only, it still applies the script to every image frame. How can I make a script only apply to what I have selected, instead of the entire page?




        • 1. Re: Newbie question
          John Hawkinson Level 5

          (I could have sworn I typed a reply to this message but it didn't seem to post?!)


          Scripts can do almost anything! Whether a script applies itself to every image box in the current document; the 14th image box; all images in all open documents; logs into the Adobe Forums, downloads some documents people have posted, opens them, applies to image boxes that are multiples of 7 as ordered from right to left bottom to top, and then emails the files to president at whitehouse.gov -- all of those things are possible!


          So you need to tell us which script your using (if it's a standard sample script) or paste it or give a link to it.


          Chances are the script ignores your selection.

          • 2. Re: Newbie question
            Rocksand1 Level 1

            The script I am using is an applescript called LabelGraphics that came standard with InDesign.


            Also, I am using one called ScaleGraphics.jsxbin, which I downloaded from a website somewhere, and it does the same thing, changing every image on the page.


            I am brand new to scripts but am astounded at how much easier they can make my job! The two I'm using so far are saving me hours and hours of work!

            • 3. Re: Newbie question
              John Hawkinson Level 5

              Ah, there we go.


              Yes, LabelGraphics operates on all graphics in the document.


              Personally, I suggest you use JavaScript. But probably it's not worth trying to learn Applescript and JavaScript at the same time...pick one. .jsxbin files are compiled JavaScript files. You can't modify them and you can't change them and you have way to know what the author of the script did. So generally speaking I would avoid them very much.


              (Wow, every time I look at the Adobe sample scripts I shudder. I'm afraid they're not exactly good examples of clean code. And all those "my"s. Oh noooooooooooooo.)


              Anyhow, the AppleScript version does:


              83         tell application "Adobe InDesign CS4"
              84                 set myGraphics to all graphics of document 1
              85                 repeat with myCounter from 1 to (count myGraphics)


              and the JavaScript version does the same (starting at line 90):


                      var myGraphics = myDocument.allGraphics;
                      myLabelStyle = myDocument.paragraphStyles.item(myLabelStyleName);
                      for(var myCounter = 0; myCounter < myGraphics.length; myCounter++){


              If you just want to operate on the selected graphics, you could easily change this. For instance, in the JavaScript version,

              just change "myDocument.allGraphics" to "myDocument.selection". Note that this assumes everything you have selected is a graphic (or at least, is compatible with what the script is trying to do). To be robust, you should probably check the type inside the loop.


              I'm not totally sure what the equivalent applescript is (not in front of a mac right now), but it's probably something like "set myGraphics to selection of document 1".

              • 4. Re: Newbie question
                Jeremy bowmangraphics Level 2

                John Hawkinson wrote:

                every time I look at the Adobe sample scripts I shudder. I'm afraid they're not exactly good examples of clean code. And all those "my"s.


                As a learner from an entirely different field (nothing like computer programming), I find that convention extremely helpful. It's an easy way of keeping track of objects, learning the DOM, and exchanging snippets of code and ideas with other scripters. (As long as 'myParagraph' isn't used as a variable containing something other than paragraphs, of course!)


                Is there something wrong with that convention? I understood that when a script is compiled, any long, self-explanatory names would "get turned into 0s and 1s" (or something like that) and so not slow the execution of the script down. Am I wrong about that?

                • 5. Re: Newbie question
                  Rocksand1 Level 1

                  Thanks so much! I haven't had time to try this yet but I'm sure it will work just fine. Thanks!

                  • 6. Re: Newbie question
                    [Jongware]-9BC6tI Level 4

                    There is nothing against Adobe's myConvention ... except, after myWhile it starts to get on myNerves


                    myGuess is it's because there are lots and lots of reserved words -- both from the Javascript language itself, and from Adobe's DOM --, so just about any useful name is 'taken'. Prepending "my" makes sure you can use myPage, myDocument, myAnimationBehavior, myCompositeFontEntry, and so on as variable names.


                    You think advanced programmers don't need it, because they won't fall for this sort of problems? I ran into serious problems a while ago, trying to make an InDesign script run on Illustrator. After some hours of patiently debugging and slicing my script into ever thinner slices, I found the problem: a variable named "path" couldn't be changed, and apparently is a read-only variable -- in Illustrator.

                    • 7. Re: Newbie question
                      John Hawkinson Level 5

                      I want to lead off noting that when I said Adobe's scripts are not good examples of clean code, I was not referring to the "my" issue.


                      The "my" issue is mostly one of Programmer Pride, I guess. Jongware's goofy example says it best. myI myHave myGreat myDifficulty myReading myAnd myWriting mySentences myThat myHave myMy myIn myFront myOf myEverything. It just drives me up the wall andis unnecessary


                      But it also  makes programs more annoying to type and edit. Typical programmer style for a counter variable is to use "i", and if that's taken, then "j", etc., etc.

                      Because you might use that counter variable a lot within a small area. Writing "myCounter" (or even "counter") just feels awfully cumbersome.

                      It can also change loops that can fit on one line into a multi-line loop, and that makes code harder to read. Compare the difference between:


                      myParagraphs = app.selection[0].paragraphs;
                      for(myCounter = 0; myCounter < myParagraphs.length; myCounter ++){
                          myParagraph = myParagraphs.item(myCounter);



                      pars = app.selection[0].paragraphs;
                      for (i=0; i<pars.length; i++) {
                          par = pars[i];


                      Anyhow, this style issue has no discernable impact on script performance -- it's not a speed issue or anything like that. Except when "with" is involved.


                      There are some good reasons against the proliferaton of mys, though, and oddly enough some examples mentioned just now are pertinent.


                      You mention "myParagraph" as distinguishing it from members in the DOM. This is only an issue if you use the "with" operator. Because otherwise everything in the DOM is buried under "app.activeDocument" and its friends, and is similarly verbose. There are only a small handful of global variables (like "app") to worry about conflicting with.


                      OK, but you want to use "with"? Well, in Javascript, you should never use "with". Please see "with Statement Considered Harmful" but basically it is impossible to predict from looking at the code which variable a "with" statement will actually use in the case of an ambiguity, because it depends on the state of global variables that you may not see or know about. It also encourages a somewhat sloppy style where you can't tell what is in the DOM and what is a variable . Also, every use of "with" does incur some kind of minor performance penalty as a new scope is added to the scope chain.


                      (Now everyone's going to look at me say "Hey! That's silly! I use 'with' all the time and it causes me no problems! And it's very very convenient. And those guys in the larger world who write JavaScript are in an entirely different environment, where there are many bits of javascript code all jumbled together and they have to worry about compatibility and unexpected global variables and namespace conflicts, and none of that applies to my simple script in InDesign."


                      And that's true.


                      But the habits we learn are the habits we use, and Adobe ExtendScript scripts get more and more complicated, and the chances of interaction are greater. and people who start writing JavaScript in Adobe products will keep doing it in other products as the world evolves and Javascript (apparently the world's most popular computer language!) gets even more popular.


                      So what do you do instead?


                      Just use a variable:


                      var dialog = new Window('dialog', 'AddGUides');
                      dialog.alignChildren = 'fill';



                      With respect to Jongware's point about "path":


                      You think advanced programmers don't need it, because they won't fall for this sort of problems? I ran into serious problems a while ago, trying to make an InDesign script run on Illustrator. After some hours of patiently debugging and slicing my script into ever thinner slices, I found the problem: a variable named "path" couldn't be changed, and apparently is a read-only variable -- in Illustrator.


                      Well, more advanced progammers won't run into that problem because you shouldn't be using global variables. This is a much bigger problem in PhotoShop (or web browsers) than it is in InDesign. At least of the enumerable properties and methods: InDesign has 27 properties and 39 methods. But PhotoShop has 156 properties and 30 methods.


                      But you should never write this:


                      var path = "~/Desktop/love.pdf";
                      var file = new File(path);


                      Instead you should write:

                      function main() {
                          path = "~/Desktop/love.pdf",
                          file = new File(path);


                      And then you are protected.


                      Actually, you could lose if someone else redefined main(). Certainly Adobe isn't going to do this, but with multiple scripts running in #targetengine session, that could still happen. So the right answer is to use:


                      (function() {
                          path = "~/Desktop/love.pdf",
                          file = new File(path);


                      which creates an anonymous function and then executes it instantly. I don't usually use this pattern on the forums because it is a bit confusing to read if you're not familiar with it, and people don't redefine main (I hope!).


                      If for some reason you need global access to functions, well, keep a small number of global variables. Ideally one.

                      Crockford recommends ALLCAPS for these. E.g.:


                      var JONGWARE = {};
                      JONGWARE.main = function() {
                          path = "~/Desktop/love.pdf",
                          file = new File(path);


                      Oof. this is too long. TL;DR!

                      • 8. Re: Newbie question
                        Harbs. Level 6

                        FWIW, the reason the sample scripts are not written in the best javascript is because the scripts were written to support all three languages. They were written in such a way that they can be easily converted between the different languages...

                        • 9. Re: Newbie question
                          Jeremy bowmangraphics Level 2

                          The "my" issue is mostly one of Programmer Pride, I guess.



                          You and I obviously take pride in different things! I take pride in being clear. The "myWhatever" idiom is easy to understand. That says almost everything that needs to be said in its defence. However, I might add:


                          (1) Human nature being what it is, and since "knowledge is power", we are all naturally attracted to "arcane" terminology. Lawyers use legalese, which effectively excludes non-lawyers from their discussions (and effectively increases their fees). All professions have their own arcane jargon, as well as technical terms they have no choice but to use. As a matter of pride I think we should try to avoid the former as much as possible, reminding ourselves of our universal weakness for it.


                          (2) Functions increase the "portability" of code, and so too in its own more modest way does a "lingua franca" of variable names. Loop counters such as 'i', 'j', etc. are fine, and widely used, but as soon as we get to options versus preferences, and all that, consistency of variable names can be very helpful, especially if more than one person is working on the same project. The "myWhatever" device is an instant variable-name generator, and one that everyone can understand and use. Self-explanatory variable names can work like comments.


                          (3) The more people examine a bit of code, the more likely they are to spot errors, or think up better ways of doing things. But only code that can be easily read by many people will be examined by many.


                          But I speak as a learner.

                          • 10. Re: Newbie question
                            John Hawkinson Level 5



                            Well, one has to acknowledge one's faults. I acknowledge that being prideful is part of my dislike of "myVariables." A visceral internal emotional hate that I don't expect everyone to share. It's not a performance problem and it's not an operational problem -- it's just cosmetic.


                            I certainly do take pride in being clear as well; I just don't see myVar as part of clarity. And I'd much rather have a potentially vague variable name with a clear comment next to it written in plain English, than I would have a variable name that is allegedly self-documenting but annoying to type.


                            I do disagree with you on the merits though -- there is no clarity loss in naming a variable without a "my."

                            I'd be fine with Adobe's sample scripts using "counter", but I'm afraid "myCounter" just makes makes me very sad.


                            (Now, when one starts to use things like "mtf" instead of masterTextFrame and things like that, then there can be serious problems. But we're not discussing the use cryptic abbreviations or unrelated letters -- the discussion was about my versus noMy.)


                            Functions are great. Did someone say something against functions?


                            You will find that very few people with a programming background are comfortable with myPrefix -- and if you're dealing with a project with multiple people, the liklihood of encountering experienced programmers is higher. And those people will be viscerally unhappy with myFoo, and will push you against you, and will ask for consistency with Everything Else in the World. So I think the consistency argument cuts against myFoo a lot more than it cuts in favor of it.


                            Also, you have to be very careful with things like "consistency." Because in JavaScript, people have a tendancy to use far too many global variables (see above example about "path" in PhotoShop). And if two functions (possibly written by the same people, possibly by different people, but whatever--operating in the same context) happen to use the same variable names in the same scope (like the global scope!), then everything just breaks in mysterious hard-to-debug ways. So to a certain extent, you're better off with variable names not actually being consistent. But this only goes so far. Much better to take other protections against global namespace conflicts anyhow. Unfortunately JavaScript makes it a bit too easy, like if you don't declare a variable with 'var', it is promoted to the global scope.


                            (Portability is not the correct term here. Portability means writing code that runs on different systems, those that may have incompatibilities or are built to different specifications. In the context of JavaScript, writing portable code might mean writing something that works in both Adobe ExtendScript and also in Flash's ActionScript; or it might mean portability to Firefox's JavaScript interpretter as well as Internet Explorer's.)


                            If you find people who can read the code with myVariable and who cannot do so with Variable, I'll give you a cash prize.


                            I'm sure that's true, though it only goes so far. I think another big part of it is that much of the sample code looks like it was written by Java programmers, who tend to try to use JavaScript like it has classical inheritance, when it really has prototypical [prototypal?] inheritance. This leads to hard-to-read constructs...

                            • 11. Re: Newbie question
                              Jeremy bowmangraphics Level 2

                              I certainly do take pride in being clear as well; I just don't see myVar as part of clarity.

                              I would "object" to that all right -- the idiom normally prefixes 'my' to the name of an object or class, thereby identifying the type of object the variable contains at the same time as naming it. I'm surprised to hear 'myVar' appears anywhere in the example scripts.

                              You will find that very few people with a programming background are comfortable with myPrefix

                              Yes, but you'll find very few lawyers who are comfortable with non-legalese, or philosophers who are comfortable with ordinary English, and so on... -- it makes them feel uncomfortably exposed to everyday scrutiny. But the arcane terminology doesn't make them any better lawyers or philosophers. It actually makes them worse teachers of law or philosophy.


                              On a philosophical tangent, in his younger days Wittgenstein thought that the symbols of a "perfect language" would somehow show the type of thing they referred to at the same time as referring to it. (Thus the word 'left' could never be part of such a language, because it can stand either for the direction opposite to right, or the state of being abandoned, which is quite different.) The "my" convention goes some way towards that ideal, thereby achieving a sort of conceptual "beauty". I guess I rate that more highly than the "cosmetic" beauty you speak of.

                              • 12. Re: Newbie question
                                John Hawkinson Level 5

                                Sorry for the ambiguity; I did not mean a literal "myVar," that was conceptual notation. Suggesting that omitting "my" is arcane really overstates the case. But one has to look at the context. If you come to the world of programming from Adobe's sample scripts and that's what you know, you're going to have a very different set of presumptions than if you come to the world of programming from anywhere else. This is where pride comes in...


                                Re Wittgenstein, you should check out Hungarian Notation, which is just that, only a bit more arcane :-). First sentence of the Wikipedia page:

                                Hungarian notation is an identifier naming convention in computer programming, in which the name of a variable or function indicates its type or intended use.


                                I don't think your legal analogy holds up. Hence our argument on the merits (now I feel like a lawyer) - - it's one thing to say that "the Court moved sua sponte to admit Barry pro hac vice" instead of "the Court moved, on it's own motion, to permit Barry to practice before it even though he was licensed in another state and not a member of its bar organization." It's rather another to distinguish between "myAdmit(myCourt, myBarry, myAdmissionOptions.PRO_HAC_VICE)" and "admit(court, barry, AdmissionOptions.PRO_HAC_VICE)."


                                BTW, you only have to look at message #3 in this thread to see a a practical problem with the verbosity of "my" that interfers with readability. The Jive forums introduce a horizontal scroll bar at 72 characters. So the code with mys becomes unreadable without scrolling and if that same code lacked the mys, it would fit just fine. This sort of thing happens rather frequently.

                                • 13. Re: Newbie question
                                  Jeremy bowmangraphics Level 2

                                  We can probably agree to differ on this, but I find the discussion very interesting, and I appreciate your comments.


                                  I would argue that JavaScript and any similar computer "language" is a "user interface" (of sorts: note the inverted commas there -- as with "portability" before, they are meant to warn of non-standard usage). That is, these languages are designed to facilitate communication between a sloppy human and a not-so-sloppy machine. The machine is prone to the opposite sort of failing from the human -- it cannot grasp context, its rigidity makes it fragile, and so on.


                                  So an important aspect of this "user interface" is that it is able to "straddle the gap" between human and machine in a way that is reasonably un-prone to the failings that both humans and machine are liable to make, in their different ways. This involves compromise.


                                  Extremely strict rules about how JavaScript should be written strike me as a mirror-image of a human insisting on WYSIWYG -- it skews the bridging of the gap between human and machine too far to one side. If you don't like compromise, there is machine code.


                                  I'm assuming the role of "the later Wittgenstein" here. But "the earlier Wittgenstein" was a decent fellow too. Perhaps we can say, in the spirit of "the earlier Wittgenstein", that the "my" idiom is a ladder that we can kick away after we have climbed up it? I have learned an incredible amount from both the sample scripts and the "Scripting Guide" scripts. I think both must have been written by a natural teacher, and a natural philosopher.

                                  • 14. Re: Newbie question
                                    John Hawkinson Level 5

                                    I think we will have to agree to disagree -- I only hope we have not injured poor Rocksand1, who is is probably getting these emails and not sure what to make of them?


                                    I'm confused by your comment about strictness -- isn't insisting on "my" in variables more strict than permiting variable names that don't have "my"? Yet you seem to be arguing excessive strictness is a bad thing.


                                    One of the funny thing about JavaScript is that because it is a poorly designed language (it was designed and written over something like two weeks at Netscape, not by a commitee over years and refined over decades), it has a bunch of rather serious errors and problems. One of the few ways to avoid those errors is to be strict in how you use the language.


                                    I'm not comfortable with the ladder example, because in my view, "my" doesn't bring any benefit to the neophyte, and brings a habit to un-learn later on. Better not to learn things that you must later un-learn.

                                    • 15. Re: Newbie question
                                      Harbs. Level 6

                                      Actually, my comment about the support for the three languages did not come from conjecture.


                                      The sample scripts were written by Ole Kvern and he has stated that the style was used to accommodate the fact that he was supporting all three languages. (AFAIK his background is not coming from Java...)



                                      • 16. Re: Newbie question
                                        Jeremy bowmangraphics Level 2

                                        I'm not comfortable with the ladder example, because in my view, "my" doesn't bring any benefit to the neophyte, and brings a habit to un-learn later on. Better not to learn things that you must later un-learn.


                                        The 'my' idiom gave me immeasurable help as a "neophyte", and as one who intends never to regard himself as anything but a "neophyte", I expect it to bring greater benefits in the future.


                                        Better not to learn things that you must later un-learn.


                                        If you were teaching physics, would you start your students off on Einstein, or start them off on Newton, then later lead them on to Einstein, un-learning Newton in the process?


                                        (I suggest you start with Newton!)

                                        • 17. Re: Newbie question
                                          John Hawkinson Level 5

                                          Respectfully, I think it is quite difficult for you to ascertain how you would have done as true initial neophyte in the absence of "my".

                                          It's quite tough to replay that same situation more than once. You also haven't really established why you believe it provides immeasurable help.


                                          You've made a case for clearly naming variables, and I do agree with that. But, at least in my view, you haven't made the case for why "my" makes the naming of variables clearer. Keep in mynd, too, that Adobe's convention prefixes "my" not just to variables, but also to functions.


                                          (Similarly, it is quite tough for me to evaluate exactly what effect "my" would have had on me when I was first learning a language. But I do have the benefit of having watched many many people learn computer programming and paid quite a lot of attention to the pedagogical aspects of the teaching of computer languages, so I think I have a pretty good undersanding of that aspect. Though, of course, there is a difference between computer science students and programmers, versus casual users of a software package who just want to add a few scripts. I've also watched plenty of people who are not and never will be computer programmers learn to "program" or struggle through attempting to do so.)


                                          It is better to not learn things you must un-learn, but sometimes it is necessary, and you point to one example; but they should be few and far between. Though, as I said, we must agree to disagree, because I don't think it fits. That should only happen in extreme cases.

                                          • 18. Re: Newbie question
                                            Harbs. Level 6

                                            I think the difference of opinion might have to do with background.


                                            For someone who is out to learn programming, I'd have to agree with John. Learning it "right" from the get-go is a much better way to go about it.


                                            However, I don't think the sample scripts were written with the mind to help people become programmers, or for programmers to learn how to program InDesign. They wee written to enable people who are not programmers (think designers) who don't have any intention of becoming programmers do a little automation. The idea was to make scripting less scary. To that end, the more verbose the code is, the more understandable it is to laymen. Yes. it is harder for programmers to read being it's unnecessarily verbose, but it is probably more accessible.



                                            • 19. Re: Newbie question
                                              [Jongware]-9BC6tI Level 4

                                              My my, wot heated discussion


                                              I think I agree with Harbs -- for a non-programmer, it's really much more clearer that "myPage" is a private object, where both names Page and Pages are 'taken' and should not be used, and an all-lowercase name would invite newbees to use variables such as "default = 1".


                                              I'm no newb when it comes to programming, but as I never did anything with Javascript before, I was careful to copy Adobe's style in its own examples. Only when confidence grew, I found out the proper rules for variable-naming and I could throw out the my's.

                                              • 20. Re: Newbie question
                                                Jeremy bowmangraphics Level 2

                                                [Jongware] wrote:

                                                Only when confidence grew, I found out the proper rules for variable-naming and I could throw out the my's.


                                                I'm still not clear why we'd want to throw out the 'my's, as long as we give proper consideration to the scope of variables. I suspect the real objection to 'my' is it "doesn't look technical enough". That's a source of potential trouble in itself.


                                                I always cringe when graduate students describe introductory logic courses as "baby logic". This is to give the impression that they have passed into the stratosphere of advanced logic. In my experience these "grown-ups" are more prone to make really basic mistakes, precisely because they think they've acquired an immunity to them. We're all capable of drowning in 3 inches of water, and if we don't occasionally remind ourselves of that fact, we are more likely to drown in 3 inches of water!


                                                Harbs. wrote:

                                                Learning it "right" from the get-go is a much better way to go about it.



                                                I'll take your word for it, but that does make computer programming an unusual discipline. Most skills are learned in a hands-on, incremental sort of way, so that the avoidance of error is not a mere "ritual" but something guided by first-hand recollection of what goes wrong when error is not avoided.


                                                I see computer programming as a branch of engineering, and engineering always involves approximation. The point is not to avoid approximation, but to approximate in an intelligent way. Engineers -- and even physicists -- still use Newton's Laws, even though strictly speaking they are known to be false.