Scripting support in Papers

matthias's Avatar

matthias

12 Jul, 2014 01:50 PM

Hi,

this is meant as a public space to gather feedback, questions and sample scripts for the AppleScript support in Papers 3.0.35 and above.

Matthias (from the Papers Mac team)

Showing page 6 out of 7. View the first page

  1. 151 Posted by jtaekman on 21 Dec, 2015 09:52 PM

    jtaekman's Avatar

    I dislike .webarchive too. As I talk about in my blog, Wippp.com, I extract each individual highlight from every manuscript I've read. Each highlight becomes its own text file. This lets me find single concepts rather than having to dig through an entire paper. I then slide those individual thoughts over to Scrivener. I also can find related information using Devonthink.

    In order to keep track of the individual highlight files, I need to tag them with their originating metadata, this is where the script comes in handy.

    Matthias, would love a script that automates all this and puts the individual files into their own distinct folder. I currently use a series of Keyboard Maestro scripts to make this happen. Wish it was built in to Papers!

  2. 152 Posted by Christian Werne... on 22 Dec, 2015 10:24 AM

    Christian Werner's Avatar

    Hi there.

    This is interesting! I wanted and tried to do something similar some time ago... As I find I'm often re-reading large parts of my references when writing a manuscript again and again...

     Can you explain a bit more? So you read every manuscript thoroughly and create single files with snippets of the key findings...? I struggeled with this... How many items would you end up with on average? What do you do with interesting references within those paper? Follow them up or have snippets for them, too? Do you tag them in any special way or do you rely on devonthink fulltext search?

  3. 153 Posted by jtaekman on 23 Dec, 2015 12:36 AM

    jtaekman's Avatar

    Check out my blog for more information.....I have changed how I do this
    a bit since my original blog posting, but you'll get the idea
    http://wippp.com/blog/?s=annotation

    I'll write an updated blog entry soon.....

  4. 154 Posted by mendel on 13 Feb, 2016 01:24 AM

    mendel's Avatar

    Hi,

    Is there a way to only export a certain type of annotation item? I want to export only the notes I wrote but not the highlights. Is this possible at all? And if not, does anyone know of a good way to parse the file and delete all the highlighted information?
    Thanks!

  5. 155 Posted by matthias on 13 Feb, 2016 01:07 PM

    matthias's Avatar

    Hi mendel,

    Is there a way to only export a certain type of annotation item? I want to export only the notes I wrote but not the highlights.

    The scripting API allows you to distinguish between note, highlight and ink annotations. The script below lets you copy just the notes (or highlights) from all the papers currently selected in your Papers 3 library. Optionally it allows you to only copy those annotations that contain a certain string.

    Hope this helps.
    Best, Matthias

    -- For all publications selected in your Papers 3 library, this script extracts all note or
    -- highlight annotations containing the given string, and copies them to the clipboard.
    
    -- If you don't enter anything in the displayed dialog, all note/highlight annotations
    -- from the selected publications will be copied to the clipboard.
    
    
    property queryString : ""
    
    tell application id "com.mekentosj.papers3"
        set pubList to (selected publications of front library window) as list
        if pubList is {} then
            display alert "Nothing selected" message "Please select the publications in your Papers 3 library whose annotations you'd like to extract, then run this script again." as critical buttons {"OK"} default button "OK"
        else
            set theDialogResult to display dialog "For all selected papers, copy their note or highlight annotations, optionally filtered by string:" default answer queryString buttons {"Cancel", "Copy Notes", "Copy Highlights"} default button "Copy Highlights" with icon note
            if button returned of theDialogResult is not "Cancel" then
                set queryString to text returned of theDialogResult
                if button returned of theDialogResult is "Copy Highlights" then
                    set annotationType to "Annotation"
                else
                    set annotationType to "Note"
                end if
                my copyAnnotationsMatchingTypeAndString(pubList, annotationType, queryString)
            end if
        end if
    end tell
    
    on copyAnnotationsMatchingTypeAndString(pubList, annotationType, queryString)
        set annotationInfoList to {}
        tell application id "com.mekentosj.papers3"
            set annotationsList to my gatherAnnotations(pubList, annotationType, queryString)
            repeat with anAnnotation in annotationsList
                set annotationInfo to my infoForAnnotation(anAnnotation)
                if annotationInfo is not missing value and annotationInfo is not "" then
                    copy annotationInfo to end of annotationInfoList
                end if
            end repeat
    
            set queryInfo to ""
            if queryString is not missing value and queryString is not "" then
                set queryInfo to " containing \"" & queryString & "\""
            end if
            if annotationType is "Annotation" then
                set annotationTypeDesc to "highlight(s)"
            else
                set annotationTypeDesc to "note(s)"
            end if
            if annotationInfoList is {} then
                display dialog "Couldn't find any " & annotationTypeDesc & queryInfo & "." buttons {"OK"} default button "OK" with icon 1
            else
                set annotationsCount to count of annotationInfoList
                copy "Found " & annotationsCount & " " & annotationTypeDesc & queryInfo & ":" & linefeed to beginning of annotationInfoList
                set the clipboard to my mergeTextItems(annotationInfoList, linefeed & "---" & linefeed & linefeed) & linefeed
                display dialog "Copied " & annotationsCount & " " & annotationTypeDesc & " to the clipboard." buttons {"OK"} default button "OK" with icon 1
            end if
        end tell
    end copyAnnotationsMatchingTypeAndString
    
    on gatherAnnotations(pubList, annotationType, queryString)
        if pubList is {} then return {}
        if annotationType is not "Note" and annotationType is not "Annotation" then return {}
        set annotationsList to {}
        set filterString to ""
        if queryString is not missing value and queryString is not "" then
            set filterString to queryString
        end if
        tell application id "com.mekentosj.papers3"
            repeat with aPub in pubList
                set primaryFile to primary file item of aPub
                if primaryFile is not missing value then
                    set pubAnnotations to every annotation item of primaryFile
                    repeat with aPubAnnotation in pubAnnotations
                        if resource type of aPubAnnotation is annotationType then
                            if filterString is "" or (content of aPubAnnotation contains filterString) then
                                copy aPubAnnotation to end of annotationsList
                            end if
                        end if
                    end repeat
                end if
            end repeat
        end tell
        return annotationsList
    end gatherAnnotations
    
    on infoForAnnotation(theAnnotation)
        if theAnnotation is missing value then return ""
        tell application id "com.mekentosj.papers3"
            set aPDF to source file of theAnnotation
            if aPDF is missing value then return ""
    
            set aPub to publication item of aPDF
            if aPub is missing value then return ""
    
            set annotationContent to content summary of theAnnotation
            if annotationContent is missing value or annotationContent is "" then return ""
    
            set infoText to "{" & citekey of aPub & "}" & linefeed & ¬
                item url of aPub & linefeed & ¬
                formatted reference of aPub & linefeed & linefeed ¬
                & annotationContent & linefeed
            return infoText
        end tell
    
        return my mergeTextItems(infoItems, linefeed & linefeed)
    end infoForAnnotation
    
    
    -- Merges the given list of text items using the given separator string.
    on mergeTextItems(textItemList, aSeparator)
        considering case
            set prevTIDs to text item delimiters of AppleScript
            set text item delimiters of AppleScript to aSeparator
            set mergedText to textItemList as text
            set text item delimiters of AppleScript to prevTIDs
        end considering
        return mergedText
    end mergeTextItems
    
  6. 156 Posted by mendelkranz on 13 Feb, 2016 06:46 PM

    mendelkranz's Avatar

    Hi Matthias,

    Thanks for the quick reply!

    Unfortunately my apple scripting isn't great, so I'm wondering if you can help. I'm working with this script below (that you once provided here) that exports each annotation into individual text files. Would you be able to help modify it so that it only exports the note files?

    Thanks so much again!

    tell application "Papers"
        set selectedPubs to selected publications of front library window
        set allAnnotations to {}
        repeat with aPub in selectedPubs
            set pubAnnotations to annotation items of primary file item of aPub
            repeat with anAnnotation in pubAnnotations
                copy anAnnotation to end of allAnnotations
            end repeat
        end repeat
        
        set desktopFolderPath to POSIX path of file (("SSD:Users:Mendel:Dropbox:Papers:") as string)
        set containerFolderPath to my createNewFolder(desktopFolderPath, "Reviews")
        
        my writeAnnotationsToTextFiles(containerFolderPath, allAnnotations)
    end tell
    
    
    --- Takes a list of Papers annotations and writes them to individual text files.
    --- Text files will be written to subfolders (one per publication) within the given container folder.
    --- Note that annotations for publications that don't have a title will be ignored.
    on writeAnnotationsToTextFiles(containerFolderPath, annotationsList)
        tell application "Papers"
            set previousPubTitle to ""
            set fileNamePrefix to 1
            set ct to count of annotationsList
            repeat with i from 1 to ct
                set anAnnotation to item i of annotationsList
                set aPubTitle to title of publication item of source file of anAnnotation
                set pubyear to publication year of publication item of source file of anAnnotation
                set pubaut to author info of publication item of source file of anAnnotation
                if aPubTitle is not "" and aPubTitle is not missing value then
                    -- NOTE: this will only be correct if annotationsList is sorted by publication
                    if aPubTitle is not equal to previousPubTitle then
                        set previousPubTitle to aPubTitle
                        set fileNamePrefix to 1
                    else
                        set fileNamePrefix to fileNamePrefix + 1
                    end if
                    
                    
                    set theSubFolderPath to my createNewFolder(containerFolderPath, pubaut & " " & "-" & " " & pubyear & " " & "-" & " " & aPubTitle)
                    
                    
                    
                    
                    ---set theSubFolderPath to (do shell script "echo " & quoted form of (theSubFolderPath) & " | tr '[:upper:]' '[:lower:]'")
                    
                    set theFileName to aPubTitle & "-" & fileNamePrefix & "-" & resource type of anAnnotation & ".txt"
                    set theFilePath to theSubFolderPath & theFileName
                    tell me to set theAnnotationFile to POSIX file theFilePath
                    set theAnnotationText to my summarizeAnnotation(anAnnotation)
                    my writeTextToFile(theAnnotationFile, theAnnotationText)
                end if
            end repeat
        end tell
    end writeAnnotationsToTextFiles
    
    
    -- Takes a Papers note or highlight annotation and returns a formatted summary of the annotation as text.
    on summarizeAnnotation(anAnnotation)
        tell application "Papers"
            set anAnnotationClass to class of anAnnotation
            set annotationSummary to ""
            if anAnnotationClass is highlight item or anAnnotationClass is note item then
                set aPub to publication item of source file of anAnnotation
                set {aPubTitle, anItemURL, aCitekey} to {title, item url, citekey} of aPub
                if aPubTitle is "" or aPubTitle is missing value then
                    set aPubTitle to "(Untitled)"
                end if
                if aCitekey is "" or aPubTitle is missing value then
                    set aCitekey to "(Undefined cite key)"
                end if
                set annotationSummary to formatted reference of aPub & linefeed & linefeed & aCitekey & linefeed & linefeed & anItemURL ¬
                    & linefeed & linefeed & content summary of anAnnotation & linefeed & linefeed
            end if
            return annotationSummary
        end tell
    end summarizeAnnotation
    
    
    --- Creates a new folder of the given name at the given folder location (specified as POSIX path),
    --- and returns the newly created (or existing) folder's POSIX path.
    on createNewFolder(aFolderPOSIXPath, aFolderName)
        set aFolderName to cleanFolderName(aFolderName)
        set containerFolder to POSIX file aFolderPOSIXPath as alias
        tell application "Finder"
            set newFolderPath to (folder containerFolder as string) & aFolderName
            if not (exists folder newFolderPath) then
                set newFolderPath to (make new folder at folder containerFolder with properties {name:aFolderName}) as string
            end if
            return POSIX path of (alias newFolderPath)
        end tell
    end createNewFolder
    
    
    on cleanFolderName(aFolderName)
        set aFolderName to my replaceText(":", " - ", aFolderName)
        set aFolderName to my replaceText("/", " - ", aFolderName)
        set aFolderName to my replaceText("  ", " ", aFolderName) -- removes double whitespace (a regex replace would be better)
        return aFolderName
    end cleanFolderName
    
    
    -- Replaces a string of text with another.
    on replaceText(find, replace, someText)
        considering case
            set prevTIDs to text item delimiters of AppleScript
            set text item delimiters of AppleScript to find
            set textItemList to text items of someText
            set text item delimiters of AppleScript to replace
            set newText to textItemList as text
            set text item delimiters of AppleScript to prevTIDs
        end considering
        return newText
    end replaceText
    
    
    --- Saves a text file to the given file. Note that this will replace any existing file content.
    on writeTextToFile(aFile, theText)
        set aFileRef to open for access aFile with write permission
        set eof aFileRef to 0
        write theText to aFileRef as «class utf8»
        close access aFileRef
    end writeTextToFile
    
  7. 157 Posted by matthias on 13 Feb, 2016 08:51 PM

    matthias's Avatar

    Hi Mendel,

    in your script, please change this code block (which starts at line 4):

    repeat with aPub in selectedPubs
        set pubAnnotations to annotation items of primary file item of aPub
        repeat with anAnnotation in pubAnnotations
            copy anAnnotation to end of allAnnotations
        end repeat
    end repeat
    

    with this one:

    repeat with aPub in selectedPubs
        set primaryFile to primary file item of aPub
        if primaryFile is not missing value then
            set pubAnnotations to (every annotation item of primaryFile whose resource type is "Note")
            repeat with anAnnotation in pubAnnotations
                copy anAnnotation to end of allAnnotations
            end repeat
        end if
    end repeat
    

    With this change, the script will only export notes (but no highlights). It also fixes an issue where the script caused an error if one of the selected papers had no PDF attached.

    Hope this helps!
    Matthias

  8. 158 Posted by mendelkranz on 13 Feb, 2016 08:58 PM

    mendelkranz's Avatar

    Matthias,

    I tested that real quick and I'm getting an error for some reason, as you can see in this screenshot. What do you think is the problem?
    I see that it does create the designated folder but gets caught up when it tries exporting each note file.

  9. 159 Posted by matthias on 13 Feb, 2016 10:17 PM

    matthias's Avatar

    Hi Mendel,

    I tested that real quick and I'm getting an error for some reason, as you can see in this screenshot.

    I fail to see where exactly this goes wrong for you. Does the script work with other papers for you? And does it only create the "Reviews" folder, or does the "Hegel, Friedrich - 1977 - Phenomenology of Spirit " folder get created as well before the script throws this error?

    Thanks, Matthias

  10. 160 Posted by mendelkranz on 14 Feb, 2016 08:25 PM

    mendelkranz's Avatar

    Matthias,

    I tried it with other papers and it seems to work fine. With this one though, it creates the Hegel folder, and exports the first note, then it creates another Hegel folder with an error message appended to the name, and then I get the script error. Not quite sure what's wrong with this paper.

    Thanks for the help

  11. 161 Posted by matthias on 16 Feb, 2016 01:35 PM

    matthias's Avatar

    Hi Mendel,

    With this one though, it creates the Hegel folder, and exports the first note, then it creates another Hegel folder with an error message appended to the name, and then I get the script error.

    More detailed information would be appreciated, e.g., a screenshot of your "Reviews" folder showing the "Hegel" folders, and what's the exact wording of the error message that is appended to the second "Hegel" folder name? Also, a BibTeX and Papers Archive export of the Hegel paper would be helpful.

    Thanks, Matthias

  12. 162 Posted by Mendel on 19 Feb, 2016 03:20 AM

    Mendel's Avatar

    Matthias,

    Thanks for the help. I've tried it now with a number of other papers and haven't run into the problem, so really not sure what it is.
    Attached is all the info. The first two screenshots show what happens the first time I try exporting the notes--the script error and the empty Hegel folder. The second two show the error that happens when there's already a Hegel folder created. (With other papers, it seems to overwrite the folder rather than create another.)

    Also, if possible, I'm going to attach another applescript I use to export everything into one file. I'm trying to also change it to export just notes but when I switch the same wording as you provided above, I get a long error (final screenshot). Any suggestions?

    Thanks again for all the help!

  13. 163 Posted by Mendel on 19 Feb, 2016 03:24 AM

    Mendel's Avatar
  14. 164 Posted by matthias on 19 Feb, 2016 08:14 AM

    matthias's Avatar

    Hi Mendel,

    thanks for the detailed info. I'm still not really sure why this issue happens. That said, the " (White Space Conflict)" error appended to the second folder name sounds interesting. I've never seen the OS X system or AppleScript do anything like that. It seems to be Dropbox that does this:

    https://www.dropbox.com/help/248

    It would be nice if you could try these three things and run the script again:
    1. Remove the trailing space from "Hegel, Friedrich - 1977 - Phenomenology of Spirit ".
    2. Make sure that all spaces in "Hegel, Friedrich - 1977 - Phenomenology of Spirit " are regular spaces (simply replace the spaces in the title again with regular spaces).
    3. Try the script in a target folder which is NOT within your Dropbox folder.

    If that doesn't help, a Papers Archive export (with "Include Notes and Highlights" checked in the export dialog) might still be useful so that I can try reproducing the issue on my end.

    I'm going to attach another applescript I use to export everything into one file. I'm trying to also change it to export just notes but when I switch the same wording as you provided above, I get a long error

    This should do the trick:

    set pubNotes to "(no comments available)"
    set primaryFile to primary file item of aPub
    if primaryFile is not missing value then
        set pubNotes to (content summary of every annotation item of primaryFile whose resource type is "Note")
    end if
    

    Hope this helps,
    Matthias

  15. 165 Posted by Mendel on 20 Feb, 2016 01:41 AM

    Mendel's Avatar

    Matthias,

    This should do the trick:

    Perfect that did it, thanks!

    1. Remove the trailing space from "Hegel, Friedrich - 1977 - Phenomenology of Spirit ".

    I think that did it too, it works now both on the desktop and in dropbox.
    Thanks so much for all your help, much appreciated!

  16. 166 Posted by matthias on 20 Feb, 2016 10:21 AM

    matthias's Avatar

    Hi Mendel,

    I'm happy to hear that the scripts are working for you now!

    Best, Matthias

  17. 167 Posted by christian on 17 Mar, 2016 02:18 PM

    christian's Avatar

    Hi.

    I'm revisiting scripting in Papers3...

    Not sure if this was covered before, but here is what I want to do...

    I just started a project with colleagues and we are currently browsing available literature and what I want to do is to export all papers with a tag PROJECTX to a folder on my disk...
    Then, the papers should be further subdivided in subfolders based on other keywords/ tags that exist for these papers (I would provide a list of valid keywords that they need to match: for instance climate, vegetation, soil would be valid and used as subfolders, all others should be ignored)...

    Is this possible at all? Any script example to start doing this would be very appreciated!

    Thanks guys,
    Christian

  18. 168 Posted by Jason on 17 Mar, 2016 02:44 PM

    Jason 's Avatar

    Greetings,

    As I am working to become more facile with using AppleScript and Papers, I've been going through the Papers Getting Started Guide http://support.mekentosj.com/kb/tutorials/scripting-papers-3-for-mac-with-applescript-a-getting-started-guide. This has been helpful, but I am wondering if anyone can tell me what application is being used in the first few pictures of the guide? The program would seem to be very useful in identifying various elements/variables, and their values, that could be used in a script. Any help with this issue would be greatly appreciated.

    Cheers,
    Jason

  19. 169 Posted by matthias on 17 Mar, 2016 03:08 PM

    matthias's Avatar

    Hi Jason,

    I am wondering if anyone can tell me what application is being used in the first few pictures of the guide?

    The app which is depicted in the screenshots is called ScriptDebugger. A short description of ScriptDebugger is given in the guide, under the "Tools" section:

    http://support.mekentosj.com/kb/tutorials/scripting-papers-3-for-ma...

    A demo of ScriptDebugger is available at:

    http://www.latenightsw.com

    ScriptDebugger is a professional tool and is priced as such. But if you do a little bit more scripting, this is a god's end. It's a powerful and mature Mac app with lots of features, and attention to detail. Its value explorers, dictionary viewers and the fully-featured debugger (with break points etc) are totally awesome. These features have helped me tremendously to develop and debug scripts. I recommend it wholeheartedly.

    Best, Matthias

  20. 170 Posted by matthias on 17 Mar, 2016 03:35 PM

    matthias's Avatar

    Hi Christian,

    I want to do is to export all papers with a tag PROJECTX to a folder on my disk... Then, the papers should be further subdivided in subfolders based on other keywords/ tags that exist for these papers

    I think this should be doable, and I might be able to help you getting started. Some questions:

    1. By "export all papers", do you mean exporting the primary PDF of the publication? Or should a BibTeX file etc be exported instead? And what should happen if there's no PDF?

    2. W.r.t. the creation of subfolders for a controlled list of keywords: What happens if a publication was tagged with several keywords from the controlled list of keywords? Should the publication then get exported multiple times (once for each matching keyword)? Or should the script export each paper only once, or maybe create symlinks?

    Thanks,
    Matthias

  21. 171 Posted by Jason on 17 Mar, 2016 03:42 PM

    Jason 's Avatar

    Matthias,

    Thanks for the quick response. I will definitely check out ScriptDebugger! Thanks for the suggestion. The reason for my question is that I am trying to find the correct properties to select and then export two sets of references. The first: gets publications with a specific author and the publication type is "Article > Journal Article" - The second: gets publications with a specific author and the publication type is "Media > Abstract"

    I've figured out the first part, but am struggling with the second as seen below. Any help is greatly appreciated.
    Cheers,
    Jason

    (* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % CREATED BY: JASON CRAGGS % % CREATED ON: 2015-11-19 % MODIFIED ON: 2016_03_17 % % % USAGE: EXPORT CRAGGS ARTICLES FROM PAPERS-3 TO A BibTex LIBRARY % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% *)

    tell application "Papers"
    set MyPubs to every publication item whose author names contains "Smith" and type is "Journal Article" export (MyPubs as list) to "Macintosh HD:Users:xxx:Documents:References:Smith_AllRefs.bib" end tell

  22. 172 Posted by Christian Werne... on 17 Mar, 2016 04:21 PM

    Christian Werner's Avatar

    Hi

    Yes, I want to place the article PDF files in these folders.
    I would store them either a) in a folder named like the first match of valid keywords (these will be defined in a list in the script or b) in each folder of matching keywords... If no keyword is matched, store in folder named "other"...
    A bibtex file for each folders' content would be a bonus but is not crucial right now (actually would be kind of nice)

    Thanks for your help
    Christian

  23. 173 Posted by matthias on 17 Mar, 2016 04:41 PM

    matthias's Avatar

    Hi Jason,

    I am trying to find the correct properties to select and then export two sets of references

    The below script shows how this could be done. Note that the script exports all of the papers matching a given author name. If you remove the two dashes ("--") from the line that starts with set allPubs to … then it will only export papers of type "Journal Article". Note that the correct scripting property is called resource type and not just type.

    This script should be easy to adopt so that it also exports a second .bib file matching only papers of another type. Let me know if you need help with this.

    Hope this helps,
    Matthias

    -- For the given author name, this script exports all of his/her publications
    -- to a .bib file in your documents folder.
    
    property authorName : "Smith"
    
    set dialogResult to display dialog "Export all papers of the given author name to a .bib file in your documents folder:" default answer authorName buttons {"Cancel", "Export"} default button "Export" cancel button "Cancel" with icon note
    if button returned of dialogResult is "Export" then
        set authorName to text returned of dialogResult
    end if
    
    set documentsFolderPath to path to documents folder as string
    set allPubsFilePath to documentsFolderPath & authorName & "_All.bib"
    
    tell application "Papers"
        set allPubs to every publication item whose author names contains authorName -- and resource type is "Journal Article"
        if allPubs is not {} then
            export (allPubs as list) to allPubsFilePath
            display dialog "Exported " & (count of allPubs) & " paper(s) with author name \"" & authorName & "\" to file:" & linefeed & linefeed & allPubsFilePath buttons {"OK"} default button "OK" with icon note
        else
            display dialog "Couldn't find any papers with author name \"" & authorName & "\"." buttons {"OK"} default button "OK" with icon caution
        end if
    end tell
    
  24. 174 Posted by matthias on 17 Mar, 2016 04:52 PM

    matthias's Avatar

    Hi Christian,

    Yes, I want to place the article PDF files in these folders.

    Thanks for the info, I'll try to make a sample script along these lines.

    Matthias

  25. 175 Posted by Mendel Kranz on 17 Mar, 2016 06:24 PM

    Mendel Kranz's Avatar

    Mendel

  26. 176 Posted by Jason on 17 Mar, 2016 08:44 PM

    Jason 's Avatar

    Matthias,

    This is perfect. Thank you! Also, I’ve been trying ScriptDebugger and love it!

    Is there a way to get the citekeys for the publications that are exported? This would help me automate updating different bibliographies.

    Cheers,
    Jason

    ---------------------------------
    Jason G Craggs, Ph.D.
    Assistant Professor
    SHP/Physical Therapy
    University of Missouri
    801 Clark Hall
    Columbia, MO 65211-4250

    Phone: 573-884-9345

  27. 177 Posted by matthias on 18 Mar, 2016 12:37 PM

    matthias's Avatar

    Hi Jason,

    it's great to hear that the script worked for you.

    Is there a way to get the citekeys for the publications that are exported?

    The citekey property of the publication item class gives you the publication's citekey. I.e., this line of code would get a list of all citekeys for the found papers:

    set allCiteKeys to citekey of every publication item whose author names contains authorName -- and resource type is "Journal Article"
    

    The Papers scripting dictionary (available in ScriptEditor or ScripDebugger) will tell you what other properties & elements are available for the publication item class.

    Depending on your needs, you could process this list of citekeys further, or simply copy its entries to the clipboard, e.g., like this:

    -- …
    set allCiteKeys to citekey of every publication item whose author names contains authorName -- and resource type is "Journal Article"
    set the clipboard to my mergeTextItems(allCiteKeys, linefeed) & linefeed
    -- …
    
    -- Merges the given list of text items using the given separator string.
    on mergeTextItems(textItemList, aSeparator)
        considering case
            set prevTIDs to text item delimiters of AppleScript
            set text item delimiters of AppleScript to aSeparator
            set mergedText to textItemList as text
            set text item delimiters of AppleScript to prevTIDs
        end considering
        return mergedText
    end mergeTextItems
    

    Hope this helps,
    Matthias

  28. 178 Posted by Jason on 18 Mar, 2016 05:34 PM

    Jason 's Avatar

    Matthias,

    Thank you for the code. I was using:
    get citekey for (every publication item whose author names contains "Craggs")

    and kept getting this error:
    A for:(every publication item whose author names contains Craggs) can’t go after this citekey.

    I will continue to tweak what you’ve sent and report back!

    Once again, thank you, as always, your support has been outstanding!

    Cheers,
    Jason

    ---------------------------------
    Jason G Craggs, Ph.D.
    Assistant Professor
    SHP/Physical Therapy
    University of Missouri
    801 Clark Hall
    Columbia, MO 65211-4250

    Phone: 573-884-9345

  29. 179 Posted by Christian on 21 Mar, 2016 02:44 PM

    Christian's Avatar

    Hi Matthias

    Ok, think I have a rough script going that exports the PDFs and creates subfolders (please excuse my ugly/ noonish AS code).
    Might be rough and I'm still interested to learn if you have some cleaner way of doing this...
    I use my collection EarthShape as an example here...

    -- Export PDFs of EarthShape collection to structured folders
    
    set documentsFolderPath to path to documents folder as string
    
    -- create base folder
    tell application "Finder"
        if not (exists folder "EarthShape" of folder documentsFolderPath) then
            make new folder at documentsFolderPath with properties {name:"EarthShape"}
        end if
    end tell
    
    
    -- find all EarthShape papers
    
    tell application "Papers"
        
        -- filter publications to only contain EarthShape papers
        
        set esColl to first collection item whose name is "EarthShape"
        set esPubs to every publication item of esColl
        
        repeat with i from 1 to count of esPubs
            set aPub to item i of esPubs
            set theTitel to title of aPub
            set theKeywords to keyword items of aPub
            
            -- log theTitel
            -- log theKeywords
            -- set theAuthors to author names of aPub
            
            -- iterate over keywords
            set validKeywords to {"climate", "vegetation", "soil", "paleoclimate", "conceptual", "erosion"}
            set target to "other"
            
            -- loop over existing keywords
            repeat with i from 1 to count of theKeywords
                set theKeyword to name of item i of theKeywords as string
                
                -- loop over valid keywords
                repeat with j from 1 to count of validKeywords
                    if (item j of validKeywords) is equal to theKeyword then
                        set targetName to item j of validKeywords
                        log theTitel
                        log target
                        
                        -- try to create subfolder
                        set folderEarthShape to documentsFolderPath & "EarthShape"
                        tell application "Finder"
                            if not (exists folder targetName of folder folderEarthShape) then
                                make new folder at folderEarthShape with properties {name:targetName}
                            end if
                        end tell
                        
                        -- copy PDF into this folder
                        set outFolder to documentsFolderPath & "EarthShape:" & targetName
                        log outFolder
                        export ((publication item of primary file item of aPub) as list) as PDF Files to outFolder
                        
                        
                    end if
                    
                end repeat
                
            end repeat
            
        end repeat
        
    end tell
    
  30. 180 Posted by matthias on 23 Mar, 2016 02:55 PM

    matthias's Avatar

    Hi Christian,

    I want to do is to export all papers with a tag PROJECTX to a folder on my disk... Then, the papers should be further subdivided in subfolders based on other keywords/ tags that exist for these papers

    Sorry for the late reply, and great that you did already come up with your own script for this!

    My script version below tries to set human-readable PDF names (which may be helpful if your library is synched and thus has UUID-style PDF names), and attempts to uniquify the file names. For each subfolder, it will also write a .bib file with BibTeX entries for each of the contained PDFs.

    Let me know if the script doesn't work for you.

    Hope this helps,
    Matthias

    -- Exports all PDFs in your Papers 3 library to a selected folder.
    
    -- If a publication is tagged with one of the keywords given in `folderKeywords`, this script will export the publication's PDF
    -- to a subfolder named after the keyword. If the publication has no matching keywords (or no keywords at all), it will get
    -- exported to a folder named "Other" (you can change this name in `otherFolderName` below).
    
    -- Each subfolder will also contain a BibTeX file (named <subfolder>.bib) which contains BibTeX entries for all ist contained PDFs.
    
    property folderKeywords : {"climate", "vegetation", "soil"} -- adopt this list of keywords to fit your needs
    
    property ignorePubsWithoutKeywords : true -- set to FALSE if you also want to export publications that have no keywords at all
    
    property otherFolderName : "Other" -- the subfolder name which contains all PDFs whose keywords don't match any of the keywords in folderKeywords
    
    -- ----------- usually, you don't need to edit anything below this line -----------
    
    property exportFolderPath : "" -- the path to the root folder's location on disk (the script will ask you to choose its location)
    
    property exportedFilePaths : {} -- holds paths of all exported PDF files (note that a publication may get exported to multiple subfolders)
    property exportedPublications : {} -- holds all exported publications
    
    on run
        set defaultFolderLocation to path to home folder
        set exportFolder to choose folder with prompt "Select the folder which should contain all exported PDFs:" default location defaultFolderLocation
        set exportFolderPath to POSIX path of exportFolder
    
        tell application id "com.mekentosj.papers3"
            if ignorePubsWithoutKeywords is true then
                set allPubs to publication items whose keyword names is not ""
            else
                set allPubs to publication items
            end if
    
            my exportPubs(allPubs)
        end tell
    
        if exportedPublications is {} then
            display dialog "Couldn't export any files." buttons {"OK"} default button "OK" with icon 1
        else
            set the clipboard to my mergeTextItems(exportedFilePaths, linefeed) & linefeed
            display dialog "Exported " & (count of exportedPublications) & " publication(s), and copied the paths of all exported files to the clipboard." buttons {"OK"} default button "OK" with icon 1
        end if
    end run
    
    on exportPubs(allPubs)
        set exportedFilePaths to {}
        set exportedPublications to {}
        tell application id "com.mekentosj.papers3"
            repeat with aPub in allPubs
                set aPDF to primary file item of aPub
                if aPDF is not missing value then
                    set pdfPath to full path of aPDF
                    if pdfPath is not missing value then
                        set exportFilePath to missing value
                        set pubKeywords to name of every keyword item of aPub
                        repeat with aKeyword in pubKeywords
                            if aKeyword is in folderKeywords then
                                set exportFilePath to my exportPub(aPub, aKeyword)
                            end if
                        end repeat
                        if exportFilePath is missing value then
                            set exportFilePath to my exportPub(aPub, otherFolderName)
                        end if
                        if exportFilePath is not missing value then
                            copy aPub to end of exportedPublications
                        end if
                    end if
                end if
            end repeat
        end tell
    end exportPubs
    
    on exportPub(aPub, subfolderName)
        set exportFilePath to missing value
        if aPub is not missing value then
            tell application id "com.mekentosj.papers3"
                set aPDF to primary file item of aPub
                if aPDF is not missing value then
                    set pdfPath to full path of aPDF
                    if pdfPath is not missing value then
                        set fileName to formatted file name of aPDF
                        set exportFilePath to my exportFile(pdfPath, exportFolderPath, subfolderName, fileName)
                        if exportFilePath is not missing value then
                            copy exportFilePath to end of exportedFilePaths
                            set bibTeXString to bibtex string of aPub
                            set bibTeXFilePath to exportFolderPath & subfolderName & "/" & subfolderName & ".bib"
                            my exportBibTeX(bibTeXString, bibTeXFilePath)
                        end if
                    end if
                end if
            end tell
        end if
        return exportFilePath
    end exportPub
    
    -- Duplicates the file at the given sourceFilePath to targetFolderPath (or, if a targetSubfolderName is given,
    -- to a subfolder with that name). The duplicated file will be renamed to targetFileName. Note that the file
    -- name will be uniquified if necessary. And the given paths must be specified as POSIX paths. Returns the
    -- POSIX path of the duplicated file.
    on exportFile(sourceFilePath, targetFolderPath, targetSubfolderName, targetFileName)
        if targetSubfolderName is not "" or targetSubfolderName is not missing value then
            set targetFolderPath to my createNewFolder(targetFolderPath, targetSubfolderName)
        end if
        set exportFilePath to my duplicateItem(sourceFilePath, targetFolderPath, targetFileName)
        return exportFilePath
    end exportFile
    
    -- Appends the given BibTeX string to the BibTeX file specified by bibTeXFilePath
    -- (specified as POSIX path). If the file doesn't yet exist, a new file will be created.
    on exportBibTeX(bibTeXString, bibTeXFilePath)
        my appendTextToFile(bibTeXFilePath, bibTeXString)
    end exportBibTeX
    
    --- Creates a new folder of the given name at the given folder location (specified as POSIX path),
    --- and returns the newly created (or existing) folder's POSIX path.
    on createNewFolder(aFolderPath, aFolderName)
        set aFolderName to cleanFolderName(aFolderName)
        set containerFolder to POSIX file aFolderPath as alias
        tell application "Finder"
            set newFolderPath to (folder containerFolder as string) & aFolderName
            if not (exists folder newFolderPath) then
                set newFolderPath to (make new folder at folder containerFolder with properties {name:aFolderName}) as string
            end if
            return POSIX path of (alias newFolderPath)
        end tell
    end createNewFolder
    
    -- Replaces invalid characters in folder names.
    on cleanFolderName(aFolderName)
        set aFolderName to my replaceText(":", " - ", aFolderName)
        set aFolderName to my replaceText("/", " - ", aFolderName)
        set aFolderName to my replaceText("  ", " ", aFolderName) -- removes double whitespace (a regex replace would be better)
        return aFolderName
    end cleanFolderName
    
    -- Replaces a string of text with another.
    on replaceText(find, replace, someText)
        considering case
            set prevTIDs to text item delimiters of AppleScript
            set text item delimiters of AppleScript to find
            set textItemList to text items of someText
            set text item delimiters of AppleScript to replace
            set newText to textItemList as text
            set text item delimiters of AppleScript to prevTIDs
        end considering
        return newText
    end replaceText
    
    -- Duplicates the file at the given sourceFilePath to targetFolderPath, and renames it to
    -- targetFileName. Note that the file name will be uniquified if necessary. And the given
    -- paths must be specified as POSIX paths. Returns the POSIX path of the duplicated file.
    on duplicateItem(sourceFilePath, targetFolderPath, targetFileName)
        try
            set sourceFile to POSIX file sourceFilePath as alias
            set targetFolder to POSIX file targetFolderPath as alias
        on error errorMessage number errorNumber
            return missing value
        end try
        tell application "Finder"
            set {targetFilePath, targetFileName} to my uniquifyFilePath(targetFolderPath, targetFileName)
            -- the `cp` shell command allows to duplicate AND rename the file at the same time
            do shell script "cp " & quoted form of sourceFilePath & space & quoted form of targetFilePath
            return targetFilePath
        end tell
    end duplicateItem
    
    -- Generates a unique file name (which doesn't yet exist at the given folder path).
    -- Note that folderPath must be specified as a POSIX path.
    on uniquifyFilePath(folderPath, fileName)
        try
            set aFolder to POSIX file folderPath as alias
        on error errorMessage number errorNumber
            return {missing value, fileName}
        end try
        set i to 0
        set done to false
        tell application "Finder"
            set fileHFSPath to (aFolder as string) & fileName -- the HFS path is necessary for the Finder's `exists` check
            set fileNameExtension to my fileExtensionForName(fileName)
            if fileNameExtension is not "" then set fileNameExtension to "." & fileNameExtension
            repeat until done is true
                if exists fileHFSPath then
                    set i to i + 1
                    if i = 1 then
                        set findText to fileNameExtension
                    else
                        set findText to "-" & (i - 1) & fileNameExtension
                    end if
                    set fileName to my replaceText(findText, "-" & i & fileNameExtension, fileName)
                    set fileHFSPath to (aFolder as string) & fileName
                else
                    set done to true
                end if
            end repeat
        end tell
        set filePOSIXPath to folderPath & fileName -- return the fiile's POSIX path (not the HFS one)
        return {filePOSIXPath, fileName}
    end uniquifyFilePath
    
    -- Returns the file extension of the given file name, or "" if there isn't any.
    on fileExtensionForName(fileName)
        if fileName is "" or fileName is missing value then return ""
        set fileNameParts to my splitString(fileName, ".")
        if (count of fileNameParts) > 1 then return last item of fileNameParts
        return ""
    end fileExtensionForName
    
    -- Splits the given string on the given delimiter and returns the resulting list of substrings.
    on splitString(aString, splitDelim)
        considering case
            set prevTIDs to text item delimiters of AppleScript
            set text item delimiters of AppleScript to splitDelim
            set itemList to text items of aString
            set text item delimiters of AppleScript to prevTIDs
        end considering
        return itemList
    end splitString
    
    -- Merges the given list of text items using the given separator string.
    on mergeTextItems(textItemList, aSeparator)
        considering case
            set prevTIDs to text item delimiters of AppleScript
            set text item delimiters of AppleScript to aSeparator
            set mergedText to textItemList as text
            set text item delimiters of AppleScript to prevTIDs
        end considering
        return mergedText
    end mergeTextItems
    
    --- Appends a text file to the given file. If the file does not exist, a new file is created.
    on appendTextToFile(aFile, theText)
        set aFileRef to open for access aFile with write permission
        write theText to aFileRef as «class utf8» starting at eof
        close access aFileRef
    end appendTextToFile
    

Discussions are closed to public comments.
If you need help with Papersapp please start a new discussion.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac