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 4 out of 7. View the first page

  1. 91 Posted by Stephan.Zellerh... on 13 Aug, 2014 07:47 PM

    Stephan.Zellerhoff's Avatar

    Hi Matthias!

    Initially, I imported my papers2 library into papers3 and put in my dropbox. „Reveal in Finder“ redirected me to the virtual disk with the plaintext file names. Assigning the spotlight comments using your script worked well. I didm´t check whether the original file received the spotlight comments. In the virtual disk, the spotlight comments were preserved only temporarily until the next unmount/reboot. Clicking on the links opened the pdf in papers3 - not in papers2 - as it was supposed to. After upgrading papers3 to 3.2.2. and changing the file naming preferences in papers3, „reveal in finder“ shows the original file, which get the spotlight comments - apparently permanently. Thank you very much for your help!

    Best,
    Stephan

    Am 13.08.2014 um 16:24 schrieb matthias <[email blocked]<mailto:[email blocked]>>:

  2. 92 Posted by matthias on 14 Aug, 2014 08:33 AM

    matthias's Avatar

    Hi Stephan,

    I pretty sure that "Reveal in Finder" did always display the original file. We actually had plans to make it display the virtual file instead, but this has not been implemented yet.

    Do you use the Dropbox sync feature, and do you have it currently enabled? This affects the file renaming. If sync is enabled, newly added files won't get human-readable file names. But existing files should still have their human-readable file names. So could it be that, when you tried this initially, a file with a human-readable name was displayed, and maybe you thought it must be from the virtual disk while in fact it was the original file in your Papers library package?

    Thanks, Matthias

  3. 93 Posted by Rafal on 15 Aug, 2014 08:33 PM

    Rafal's Avatar

    Such an idea for a script to make orders (small clean up) in the PDFs catalog. The script should transfer documents that are not connected to the Paper database.

  4. 94 Posted by matthias on 16 Aug, 2014 07:10 AM

    matthias's Avatar

    Hi Rafal,

    The script should transfer documents that are not connected to the Paper database.

    I'm not entirely sure I understand. Do you want to find all orphaned PDFs in your Papers library and create again publications for them in Papers?

    If so, we had also thought about this and were thinking to add this to the "Help > Troubleshooting > Repair File Path Metadata" functionality. But right now, this command only reports orphaned files in the Console.app log. You could (manually) extract the reported file paths into a list, like this: {"path 1", "path 2", "path 3"}. Then, use this in a script to loop over each path in the list and tell Papers to open each PDF.

    Matthias

  5. 95 Posted by matthias on 16 Aug, 2014 10:24 AM

    matthias's Avatar

    Hi everyone,

    I thought the below script might be useful to some of you. The posted scripts are also meant as examples so that it's easier for you to come up with your own ones.

    BibTeX users frequently want to control which fields get exported to their BibTeX file. While Papers allows to choose among different sets of fields (minimal, standard, complete), it currently doesn't allow you to control on a field-by-field level which fields should be included in the BibTeX file. The script below is meant to help with that.

    The script exports all selected publications to a BibTeX file on your desktop, and then tweaks the exported BibTeX file so that all publisher and publication month info is removed. You can edit the fieldsToRemove list in order to specify which fields shall be removed from the exported BibTeX file.

    Please note that this script cannot be run without the "Papers Scripting Lib" (v0.2) which is attached to this post. This is a scripting library that must be unzipped and then placed into your Library folder, inside a "Script Libraries" folder (i.e., at ~/Library/Script Libraries/). You may need to create the "Script Libraries" folder if it's not there yet.

    -- This script requires the Papers Scripting Lib, v0.2 or greater
    
    use PapersLib : script "PapersScriptingLib"
    use scripting additions
    
    -- List of BibTeX field names that shall be removed from the exported BibTeX file.
    property fieldsToRemove : {"month", "publisher"}
    
    tell application "Papers"
        set outFilePath to ((path to desktop from user domain) as string) & "Bibliography.bib"
        export (selected publications of front library window as list) to outFilePath
        delay 0.5
    
        set bibFile to outFilePath as alias
        set bibFileContents to PapersLib's readFromFile(bibFile)
    
        set searchPattern to "\\n *(" & PapersLib's mergeTextItems(fieldsToRemove, "|") & ") *= *.+"
        set newBibFileContents to PapersLib's regexReplace(bibFileContents, searchPattern, "")
    
        PapersLib's writeTextToFile(bibFile, newBibFileContents)
    end tell
    

    Best,
    Matthias

  6. 96 Posted by Liam on 16 Aug, 2014 08:42 PM

    Liam's Avatar

    Is there any simple way to export a manual collection? The only way I've found is to select the collection and use "selected publications". Thanks.

  7. 97 Posted by matthias on 16 Aug, 2014 10:34 PM

    matthias's Avatar

    Hi Liam,

    Is there any simple way to export a manual collection?

    Not yet, unfortunately. Scripting support for collections is one of the bigger omissions, but is high up on the scripting TODO list. Other TODO items are support for more properties, and more/better commands to add/remove related objects (e.g., to add files to publications). A BibTeX string property or similar for the publication item class would be also very useful.

    Matthias

  8. 98 Posted by Jason on 26 Aug, 2014 05:44 PM

    Jason 's Avatar

    Greetings,

    The scriptability of Papers 3 is a god-send. Regarding "matching" is there a way to to script a match using PubMed, as can be done via the GUI? This would be great because the PMCID would be updated.

    Thanks.

    Cheers,
    Jason

  9. 99 Posted by matthias on 26 Aug, 2014 07:39 PM

    matthias's Avatar

    Hi Jason,

    The scriptability of Papers 3 is a god-send. Regarding "matching" is there a way to to script a match using PubMed, as can be done via the GUI?

    Currently you cannot choose different search engines, unfortunately. ATM, the matching will be similar to the batch-matching feature in Papers itself, i.e., it will always use the CrossRef Search engine. This is in part because automatic matching (i.e., without any user intervention) requires good accuracy. The CrossRef Search engine provides a dedicated service for matching (formatted) references, and this helps greatly to automatically retrieve the correct result.

    This would be great because the PMCID would be updated.

    I see.

    As a workaround this might work: If you have the PMID for that publication, try deleting the PMID of the publication, then adding it again. This should trigger the fetching of metadata from PubMed, and add missing metadata. However, this will only work if the publication has not already been updated with data from PubMed. I.e., if you've originally imported that publication from PubMed, this probably won't work.

    If, instead, you're creating a new record, and you happen to have the PMID available, then the below may work better. At least, it works for me with this sample record:

    tell application "Papers"
        set newPub to make new publication item with properties {title:"Floating ice-algal aggregates below melting arctic sea ice", pmid:"24204642"}
        delay 0.5
        set selected publications of front library window to (newPub as list) -- for the PDF to be automatically downloaded, the new entry currently must be selected
        set matchedPubs to match (newPub as list) without replacing metadata
    end tell
    

    After running this script, if you wait long enough, then metadata from PubMed (incl. the PMCID) as well as the PDF should get fetched as well.

    Best, Matthias

  10. 100 Posted by matthias on 27 Aug, 2014 08:20 AM

    matthias's Avatar

    FYI, the latest Papers release allows to set a publication's authors or editors via a string of person names:

    tell application "Papers"
        set selectedPapers to selected publications of front library window
        set author names of first item of selectedPapers to "Griekspoor, A.C.; Neefjes, J.J.; Groothuis, T.A.M."
    end tell
    

    Previously you'd need to split the author string yourself, and use something like the below for each of the authors:

    tell application "Papers"
        set existingAuthors to person items whose name is equal to "A. Griekspoor"
        set selectedPapers to selected publications of front library window
        if (count of existingAuthors) is 1 then
            add authors existingAuthors to first item of selectedPapers
        else if (count of existingAuthors) is 0 then
            set newAuthor to make new person item with properties {family name:"Griekspoor", given name:"A."}
            add authors {newAuthor} to first item of selectedPapers
        end if
    end tell
    

    The documentation of the author names property in the scripting dictionary lists examples for recognized name formats:

    Griekspoor, A C; Neefjes, J J; Groothuis, T A M
    
    A.C. Griekspoor; J.J. Neefjes; T.A.M. Groothuis
    
    van den Belt, Georges-Edouard Henri; Van Gogh, Vincent; Mac Stevenson III, Timothy G.
    
    Georges-Edouard Henri van den Belt, and Vincent Van Gogh, and Timothy G. Mac Stevenson III
    
    Edward R. Stettinius Jr. and Gérard R. de la Martinière Sr.
    

    Best, Matthias

  11. 101 Posted by matthias on 28 Aug, 2014 05:25 AM

    matthias's Avatar

    Hi Chris & Stephan,

    My ultimate goal is to export abstracts, citekeys, notes & highlights of a paper to a devonthink note. This note file should include a paper link url so that the corresponding pdf can be opened in papers easily.

    Below is a script that exports all notes & highlight annotations of all selected publications to DEVONthink Pro. The script benefits heavily from previous DEVONthink-related script code by Rob Trew.

    Note that due to a bug in the current version of Papers, cite keys will only be exported correctly for publications that have been exported at least once. For the slected publications, this can be easily done by pressing the keyboard shortcut Command-Control-C (which triggers the "Edit > Copy As > BibTeX Record" menu command).

    Best,
    Matthias

    -- Papers annotations to DEVONthink, v0.1
    -- by Matthias Steffens, papersapp.com
    
    -- Exports all notes & highlight annotations of all selected publications to DEVONthink Pro.
    -- For each publication, the formatted reference and the cite key are included above the
    -- note/annotation text. The publication's Papers link and keywords are also transferred.
    
    -- adopt this routine to customize
    on run
        -- DEVONthink and Papers must be running for this script to work
        if not my checkAppsRunning() then return
        
        tell application id "com.mekentosj.papers3"
            -- export the currently selected publications only
            set selectedPubs to selected publications of front library window
            
            -- filter the selection so that it only contains publications with a primary PDF
            set pdfPubs to my pubsWithPDF(selectedPubs)
            
            -- get current group/window in DEVONthink which should receive the notes
            set {dtContainer, dtWin} to my getDTTargetContainers()
            
            repeat with aPub in pdfPubs
                -- gather info for this publication
                set {pubRef, pubKey, pubTitle, pubLink} to {formatted reference, citekey, title, item url} of aPub
                set pubKeywords to name of every keyword item of aPub
                
                -- get all notes & highlight annotations for this publication
                set pubNotes to every annotation item of primary file item of aPub
                
                -- for each publication that has notes, create a subfolder in DEVONthink (named like "<CITEKEY> - <TITLE>")
                if pubNotes is not {} then
                    set folderName to pubKey & " - " & pubTitle
                    set recordLocation to my createDTFolder(dtContainer, folderName, pubLink, pubKeywords)
                end if
                
                repeat with aNote in pubNotes
                    -- individual records have titles like "<CITEKEY> - <NOTE SUMMARY>"
                    set noteSummary to content summary of aNote
                    set recordName to pubKey & " - " & noteSummary
                    
                    -- assemble formatted text for this note
                    set recordContents to pubRef & linefeed & linefeed ¬
                        & "{" & pubKey & "}" & linefeed & linefeed ¬
                        & noteSummary & linefeed & linefeed
                    
                    -- create a record for this note in DEVONthink
                    my createDTRecord(recordLocation, recordName, pubLink, recordContents)
                end repeat
            end repeat
        end tell
    end run
    
    
    -- Returns all publications from the given list of publications that have a primary PDF attached.
    on pubsWithPDF(pubList)
        tell application id "com.mekentosj.papers3"
            set allPubsWithPDF to {}
            repeat with aPub in pubList
                set pdfFile to primary file item of aPub
                if pdfFile is not missing value then
                    copy contents of aPub to end of allPubsWithPDF
                end if
            end repeat
            return allPubsWithPDF
        end tell
    end pubsWithPDF
    
    
    -- Finds the DEVONthink folder for this publication, or creates it if it doesn't exist.
    -- Credit: modified after script code by Rob Trew
    -- see https://github.com/RobTrew/tree-tools/blob/master/DevonThink%20scripts/Sente6ToDevn73.applescript
    on createDTFolder(dtContainer, folderName, folderURL, folderTags)
        tell application id "DNtp"
            if (count of parents of dtContainer) is 0 then
                set dtLocation to (create location folderName in database of dtContainer)
            else
                set dtLocation to (create location (location of dtContainer & "/" & name of dtContainer & "/" & folderName) in database of dtContainer)
            end if
            
            if folderURL is not "" then
                set URL of dtLocation to folderURL
            end if
            
            if folderTags is not {} then
                set tags of dtLocation to (tags of dtLocation) & folderTags -- in case the folder already exists
            end if
            
            return dtLocation
        end tell
    end createDTFolder
    
    
    -- Creates a new (rich text) record in DEVONthink with the given text.
    -- Credit: modified after script code by Rob Trew
    -- see https://github.com/RobTrew/tree-tools/blob/master/DevonThink%20scripts/Sente6ToDevn73.applescript
    on createDTRecord(recordLocation, recordName, recordURL, recordText)
        tell application id "DNtp"
            set newRecord to create record with {type:rtf, rich text:recordText, URL:recordURL, name:recordName} in recordLocation
            
            -- discard new record if it duplicates another in this group
            set recordDuplicates to duplicates of newRecord
            if recordDuplicates is not {} then
                set newRecordLocation to location of newRecord
                repeat with aDuplicateRecord in recordDuplicates
                    if location of aDuplicateRecord = newRecordLocation then
                        delete record newRecord
                        exit repeat
                    end if
                end repeat
            end if
        end tell
    end createDTRecord
    
    
    -- Checks if DEVONthink Pro and Papers are running.
    -- Credit: modified after script code by Rob Trew
    -- see https://github.com/RobTrew/tree-tools/blob/master/DevonThink%20scripts/Sente6ToDevn73.applescript
    on checkAppsRunning()
        tell application id "sevs" -- application "System Events"
            if (count of (processes where creator type = "DNtp")) < 1 then
                activate
                display dialog "Please select a target folder in DEVONthink," & linefeed & "then run this script again." buttons {"OK"} default button "OK" with icon 2
                return false
            end if
            if (count of (processes where bundle identifier starts with "com.mekentosj.papers3")) < 1 then
                activate
                display dialog "Please select some record(s) in Papers," & linefeed & "then run this script again." buttons {"OK"} default button "OK" with icon 2
                return false
            end if
        end tell
        return true
    end checkAppsRunning
    
    
    -- Gets the target window as well as the group currently selected in DEVONthink Pro.
    -- Credit: modified after script code by Rob Trew
    -- see https://github.com/RobTrew/tree-tools/blob/master/DevonThink%20scripts/Sente6ToDevn73.applescript
    on getDTTargetContainers()
        tell application id "DNtp"
            -- get the current group, if there is one
            set dtGroup to missing value
            with timeout of 1 second
                try
                    set dtGroup to current group
                end try
            end timeout
            
            -- else, get the current database, if there is one
            try
                dtGroup
            on error
                set dtGroup to (root of database id 1)
                set dtWin to open window for record dtGroup
                return {dtGroup, dtWin}
            end try
            
            if dtGroup is missing value then
                set dtGroup to (root of database id 1)
                set dtWin to open window for record dtGroup
                return {dtGroup, dtWin}
            end if
            
            -- ensure that a window is open for this group
            set {dtDatabase, dtGroupID} to {database, id} of dtGroup
            set dtWindows to viewer windows where id of its root is dtGroupID and name of its root is name of dtDatabase
            if length of dtWindows < 1 then
                set dtWin to open window for record dtGroup
            else
                set dtWin to first item of dtWindows
            end if
            
            return {dtGroup, dtWin}
        end tell
    end getDTTargetContainers
    
  12. 102 Posted by Benjamin Piwowa... on 04 Sep, 2014 02:32 PM

    Benjamin Piwowarski's Avatar

    I am searching for a way to get the "organization note" and the "general note" of a publication, but I did not find a matching property. Would it be possible to add it to the next version of Papers (along with the bibtex string property)?

  13. 103 Posted by matthias on 22 Sep, 2014 10:48 AM

    matthias's Avatar

    Hi Benjamin,

    sory for the late reply (I've been travelling).

    I am searching for a way to get the "organization note" and the "general note" of a publication, but I did not find a matching property.

    Scripting access to the "general note" is indeed missing and should be added. I'm not sure what you mean by "organization note", could you explain? Thanks!

    Would it be possible to add it to the next version of Papers (along with the bibtex string property)?

    I'll do my best to add these to one of the next releases (the very next release won't include them, though).

    Best, Matthias

  14. 104 Posted by Benjamin Piwowa... on 22 Sep, 2014 11:29 AM

    Benjamin Piwowarski's Avatar

    Hi Matthias,

    sorry, I think it is rather called “My Review” - it is under the “organization” section of the paper.

    Thanks for the follow-up, fyi - I am trying to automate the process of copying my annotations to an XMind mind map so that I can see my papers organized by themes along with rich annotations. I will post it when done (it would be great to have a “scripts” section on the website somewhere - with all the disclaimers of course...)

    Benjamin

  15. 105 Posted by matthias on 22 Sep, 2014 01:03 PM

    matthias's Avatar

    Hi Benjamin,

    I think it is rather called “My Review” - it is under the “organization” section of the paper.

    Ok, thanks for the clarification, I understand now.

    it would be great to have a “scripts” section on the website somewhere - with all the disclaimers of course...

    Agreed! We have plans to add all these scripts to a dedicated GitHub repository. This would make it easy to update the scripts, include proper ReadMe files, and provide stable URLs for them. User submissions or enhancements to existing scripts could be done via pull requests, etc...

    For now, please post your Papers scripts (or a link to them) here. Thanks!

    Best, Matthias

  16. 106 Posted by Christian on 20 Oct, 2014 06:20 AM

    Christian's Avatar

    Hi Matthias.

    Starting to play around with scripting to utilize Devonthink and Papers more efficiently. So I started using your script as a base.

    First questions:
    Is ist possible to add the highlight colour as a differentiator into the exported note? My plan is to start highlighting in a more systematic way. For this I plant to highlight key findings of a given paper say in yellow but all referenced info I find valuable (cited by this author) in another colour (say green). The plan is to build two seperate searchable DT notes... Primaray and secondary citation data if you like.

    Any news on a Git Hub for these scripts.

    Cheers,
    C

  17. 107 Posted by matthias on 27 Dec, 2014 10:49 AM

    matthias's Avatar

    Hi Christian,

    apologies for the very late reply, I totally overlooked your post.

    Is ist possible to add the highlight colour as a differentiator into the exported note?

    In the current release version, the annotation color isn't accessible via the scripting interface, unfortunately. But I agree that this would be very useful so I've added support for getting & setting the annotation color for highlight & ink annotations. This will hopefully be part of one of the next beta versions.

    Any news on a Git Hub for these scripts.

    Unfortunately not, but I'll try to sort this out in January (again no promises, though).

    Best regards,
    Matthias

  18. 108 Posted by matthias on 27 Dec, 2014 01:20 PM

    matthias's Avatar

    Hi everyone,

    as you probably know, the recent release of Papers 3.2.6 added Spotlight support.

    When you open a Papers 3 Spotlight search result, the correpsonding publication will be opened in your Papers library (in Reader mode). However, there are cases where you'd like to directly open its attached PDF file (if there's any).

    With some Papers 3 Spotlight search results (aka "Papers Metadata Record" aka .metapaper files) selected in a Finder window, the script below will open the corresponding publication's primary PDF directly with its default application.

    Please note that this script cannot be run without the "Papers Scripting Lib" (v0.4) which is attached to this post. This is a scripting library that must be unzipped and then placed into your Library folder, inside a "Script Libraries" folder (i.e., at ~/Library/Script Libraries/). You may need to create the "Script Libraries" folder if it's not there yet.

    -- This script requires the Papers Scripting Lib, v0.4 or greater
    
    use PapersLib : script "PapersScriptingLib"
    use scripting additions
    
    tell application "Finder"
        set selectedItems to selection
        if selectedItems is {} then
            my showUsage()
        else
            set metadataRecords to {}
            repeat with selectedItem in selectedItems
                set itemExtension to name extension of selectedItem
                if itemExtension is "metapaper" then
                    copy (selectedItem as alias) to end of metadataRecords
                end if
            end repeat
            if metadataRecords is {} then
                my showUsage()
            else
                set pdfPaths to my extractPDFPaths(metadataRecords)
                if pdfPaths is {} then
                    my showNoPDFsFoundInfo()
                else
                    my openPDFs(pdfPaths)
                end if
            end if
        end if
    end tell
    
    -- Displays a usage hint if the current Finder selection doesn't contain any .metapaper files.
    on showUsage()
        display dialog "With some Papers 3 Spotlight search results selected in a Finder window, this script will open the corresponding publication's primary PDF with its default application." & linefeed & linefeed & ¬
            "Please select one or more Papers 3 Spotlight search results and run this script again." buttons {"OK"} default button "OK" with title "No Spotlight search results selected" with icon 1
    end showUsage
    
    -- Inform the user that no PDF paths were found.
    on showNoPDFsFoundInfo()
        display dialog "Couldn't find any PDFs for the Papers 3 Spotlight search results you've selected." buttons {"OK"} default button "OK" with title "No PDF paths found" with icon 1
    end showNoPDFsFoundInfo
    
    -- Extracts the PDF paths from the given alias list of .metapaper files (if there are any).
    on extractPDFPaths(metadataRecords)
        set pdfPOSIXPaths to {}
        repeat with metadataRecord in metadataRecords
            set fileContents to PapersLib's readFromFile(metadataRecord)
            set searchPattern to "(?<=<key>pdf_path</key>[\\r\\n]\\t<string>).+?(?=</string>)"
            set pdfPOSIXPath to PapersLib's regexMatch(fileContents, searchPattern)
            if pdfPOSIXPath is not "" then copy pdfPOSIXPath to end of pdfPOSIXPaths
        end repeat
        return pdfPOSIXPaths
    end extractPDFPaths
    
    -- Opens the given list of PDFs (given as POSIX paths) in their default application.
    on openPDFs(pdfPaths)
        repeat with pdfPath in pdfPaths
            set pdfFile to POSIX file pdfPath
            tell application "Finder" to open pdfFile
        end repeat
    end openPDFs
    

    Hope this is useful to some of you.

    Enjoy the Christmas break and happy new year,
    Matthias

  19. 109 Posted by matthias on 25 Jan, 2015 07:45 PM

    matthias's Avatar

    Here's an action script for LaunchBar users who want to search their Papers library from within LaunchBar:

    -- This LaunchBar script searches your favorite Papers 3 search engine(s) for the given query term(s)
    
    -- For the supported query syntax, see https://support.mekentosj.com/kb/organize-how-to-organise-and-manage-your-library/power-filter-the-articles-within-your-library-papers-3-for-mac
    
    on handle_string(theString)
        tell application id "com.mekentosj.papers3"
            activate
            search online for theString
        end tell
    end handle_string
    

    Save the above AppleScript code as a compiled script (or an alias that points to it) into your LaunchBar Actions folder (~/Library/Application Support/LaunchBar/Actions). You can then run this script via LaunchBar on your query string.

    Please note that this script will search all of your favorite search engines. I.e., to search your local Papers 3 library, you need to add it as a favorite search engine.

    Examples of the supported query syntax:

    kw:sea ice
    au:steffens ti:sea ice
    au:granskog dp:2006 rt:4+
    
  20. 110 Posted by Stephan Zellerh... on 25 Jan, 2015 09:42 PM

    Stephan Zellerhoff's Avatar

    Dear Matthias!

    Thank you for adding this great feature! Unfortunately, the script does not work (also after deleting „-test“). There seems to be a problem with the „search online“ term. The papers scripting lib is placed in the correct folder (v0.4). Do you have any suggestion how to fix this?

    Best,

    Stephan

  21. 111 Posted by matthias on 25 Jan, 2015 09:57 PM

    matthias's Avatar

    Hi Stephan,

    Unfortunately, the script does not work

    Doh, stupid me! I forgot that the 'search online' command isn't yet available in a publicly available release version. Sorry for the confusion! The next beta versions will be entirely bug-focussed, but this new AppleScript command will be hopefully included in one of the subsequent beta releases.

    Sorry again for the trouble,
    Matthias

  22. 112 Posted by ks.burch on 09 Feb, 2015 01:56 PM

    ks.burch's Avatar

    Dear Matthias,

    Thanks for all the great scripting suggestions! I'm wondering if you could help with what I think is something simple, but can't find the right approach. I currently have a lot of pdf's that are tagged using OS X tags. I have an applescript that gets the POSIX path of a selected PDF file, and can put them into a list. I have figured out how to then get papers to open that same file. However I want papers to then take that list and add those tags as keywords in papers for the recently imported PDF. Any suggestions? It seems the "open" command cannot have keywords associated with it...

    thanks!
    Ken

  23. 113 Posted by matthias on 09 Feb, 2015 02:18 PM

    matthias's Avatar

    Hi Ken,

    I have figured out how to then get papers to open that same file. However I want papers to then take that list and add those tags as keywords in papers for the recently imported PDF.

    I've recently written a script that imports all files selected in the Finder into your current Papers 3 library. And if the files have OS X tags, these will be converted into publication keywords. This sounds pretty much what you're after, right? I wanted to post it here last week, but then got distracted, so here we go…

    Note that this script cannot be run without the "Papers Scripting Lib" (v0.5) which is attached to this post. This is a scripting library that must be unzipped and then placed into your Library folder, inside a "Script Libraries" folder (i.e., at ~/Library/Script Libraries/). You may need to create the "Script Libraries" folder if it's not there yet.

    -- Imports all files selected in the Finder into your current Papers 3 library.
    -- If the files have tags, these will be converted into publication keywords.
    
    -- If no files are selected in the Finder, the script will ask you to choose some file(s) via an Open dialog.
    -- If the script was saved as an application, you can also drag files onto it.
    
    -- Upon completion, the script will report the number of imported files.
    
    -- This script requires the Papers Scripting Lib, v0.5 or greater
    
    use PapersLib : script "PapersScriptingLib"
    use scripting additions
    
    property importTags : true -- set to false if you don't want the tags of the imported file(s) to be converted into publication keywords
    
    on run
        tell application "Finder"
            set selectedItems to selection
            if selectedItems is {} then
                set selectedItems to choose file with prompt "Select the file(s) you'd like to import into your Papers 3 library:" with multiple selections allowed
            end if
            if selectedItems is not {} then
                my importFiles(selectedItems)
            end if
        end tell
    end run
    
    on open droppedFiles
        my importFiles(droppedFiles)
    end open
    
    on importFiles(theFiles)
        tell application id "com.mekentosj.papers3" to activate
        
        set importedFiles to {}
        repeat with aFile in theFiles
            set aFile to aFile as alias
            set fileInfo to info for aFile without size
            if folder of fileInfo is not true then -- folders will be ignored
                tell application id "com.mekentosj.papers3"
                    open aFile
                    copy aFile to end of importedFiles
                    
                    if importTags then
                        set tagNames to my tagsForFile(aFile)
                        if tagNames is not {} then
                            set selectedPubs to selected publications of front library window
                            if selectedPubs is not {} and selectedPubs is not missing value then
                                set selectedPub to first item of selectedPubs
                                my addTagsForPublications(tagNames, selectedPub as list)
                            end if
                        end if
                    end if
                end tell
            end if
        end repeat
        
        tell application id "com.mekentosj.papers3"
            set ct to count of importedFiles
            if ct is 1 then
                set pluralString to ""
            else
                set pluralString to "s"
            end if
            display dialog "Did import " & ct & " file" & pluralString & "." buttons {"OK"} default button "OK" with icon 1
        end tell
    end importFiles
    
    on tagsForFile(theFile)
        return PapersLib's returnTagsFor:(POSIX path of theFile)
    end tagsForFile
    
    on addTagsForPublications(tagNames, pubs)
        tell application id "com.mekentosj.papers3"
            repeat with aTagName in tagNames
                set existingTags to (every keyword item whose name is equal to aTagName)
                if (count of existingTags) is 0 then
                    set aTag to make new keyword item with properties {name:aTagName}
                else
                    set aTag to first item of existingTags
                end if
                
                repeat with aPub in pubs
                    add keywords (aTag as list) to aPub
                end repeat
            end repeat
        end tell
    end addTagsForPublications
    
  24. 114 Posted by matthias on 12 Feb, 2015 08:22 AM

    matthias's Avatar

    Hi everyone,

    our users have been asking for RSS support within Papers for quite some time. While I can't comment on if or when this will be supported, I thought an "RSS reader to Papers" import script may be useful.

    Below is a little script that takes the first article selected in the Vienna RSS feed reader and imports it into your Papers 3 library.

    Copy the below script into a new ScriptEditor.app document and save it as a compiled script (.scpt) to a location from where you can run it conveniently. E.g., you could put it in the ~/Library/Scripts/Applications/Vienna/ folder (you may need to create that folder) and then run it from the scripts menu in the OS X menu bar. This scripts menu can be enabled from within the ScriptEditor.app prefs.

    Here's the script:

    -- takes the first article selected in the Vienna RSS feed reader
    -- and imports it into your Papers 3 library
    
    set articleURL to ""
    
    tell application "Vienna"
        if (exists current article) then
            set selectedArticle to current article
            if selectedArticle is not false then
                set articleURL to the link of selectedArticle
            end if
        else
            display dialog "Please select the article you wish to import into your Papers 3 library." buttons {"OK"} default button "OK" with icon 1 with title "Nothing selected"
        end if
    end tell
    
    if articleURL starts with "http://" then
        tell application "Papers"
            activate -- if you don't want Papers 3 to become the frontmost application, comment out this line (i.e., add two hyphens in the front)
            open location articleURL
        end tell
    end if
    

    Cheers, Matthias

  25. 115 Posted by ks.burch on 12 Feb, 2015 11:43 AM

    ks.burch's Avatar

    Hi Matthias,
    Thanks for the fast response! Sorry I’m just responding now. Just tried this out and its a bit weird. It seems to work, but the keywords only show up 30 second or so after I click “ok” and then not always. Always Imports the file just fine, and I think it is correlated with me clicking on the newly imported paper.

    Another weird thing, if I run it with no finder window even open it doesn’t prompt to select a paper…

    thanks again!
    k

    Ken Burch | Assistant Professor
    LASE | Laboratory for Assembly and Spectroscopy of Emergence
    | Boston College

    Web: burchlab.org
    Email: [email blocked]
    Office: Higgins 330E
    MeetMe: http://meetme.so/KBurch

    Mail:
    Department of Physics
    140 Commonwealth Ave
    Chestnut Hill, MA 02467-3804
    USA

  26. 116 Posted by mendelkranz on 16 Feb, 2015 02:16 AM

    mendelkranz's Avatar

    Matthias,

    My question is related Chris & Stephan's above. I'd like to export abstracts, citekeys, notes, highlights, and the 'my review' tab to a simple plain text file in my dropbox (as opposed to a Devonthink note).

    Ideally, the script would pull the name of the book/pdf/article, the author's name, and the current date and use those as a title.

    If this would be able to run automatically, say once a day, that would be even better--as opposed to selecting files and running the script only on those files. I guess for this to work it would have to recognize any changes made in the files though and update them if more highlights or notes were made..

    P.s. Unfortunately, my knowledge of of applescript is pretty limited so if you could be as specific as possible in the answer that would be very helpful!

    Thanks so much for your help.

    Mendel

  27. 117 Posted by matthias on 16 Feb, 2015 06:16 AM

    matthias's Avatar

    Hi Ken,

    It seems to work, but the keywords only show up 30 second or so after I click “ok” and then not always. Always Imports the file just fine, and I think it is correlated with me clicking on the newly imported paper.

    This is probably because the scripting API currently doesn't always update the Papers UI properly. So the UI sometimes needs some user interaction to trigger a UI refresh. For the case of adding keywords via the scripting API, I have already fixed this issue so that the UI is updated properly. But, unfortunately, this isn't yet available in a beta or release version.

    Another weird thing, if I run it with no finder window even open it doesn’t prompt to select a paper…

    I just tried this again on my machine. With no Finder windows being open (or none of them having focus), the script always presented a "choose file" dialog for me. Maybe the Finder (which presents the dialog) wasn't brought into focus and thus you couldn't see it?

    Best regards,
    Matthias

  28. 118 Posted by mendelkranz on 17 Feb, 2015 06:02 AM

    mendelkranz's Avatar

    Matthias,

    This is a slightly updated request from my previous one above

    My question is related Chris & Stephan's above. I'd like to export abstracts, citekeys, notes, highlights, and the 'my review' tab to a simple plain text file in my dropbox (as opposed to a Devonthink note).

    I'm trying to use a script that you posted here previously, which I modified very slightly to change what goes into the text. However, I'm having trouble--due to my lack of knowledge in applescript--in actually saving the file (the code you wrote was only to copy all the highlights). I'll attach my code below.

    Can someone help as to how to save the file to a designated location on my computer and name it a certain way?
    Also, is there any way to include the bibtex reference for the selected pdf at the top of the file itself?

    Any help is much appreciated.

    Best,
    Mendel

    ---Here's an AppleScript that copies all notes & highlight annotations of all selected publications to the clipboard.
    ---For each publication, the Papers link as well as the cite key are included above the notes & annotations.
    tell application "Papers"
        set selectedPubs to selected publications of front library window
        set allPubTexts to {}
        repeat with aPub in selectedPubs
            set pubNotes to content summary of every annotation item of primary file item of aPub
            set {pubRef, pubKey, pubTitle, pubLink} to {formatted reference, citekey, title, item url} of aPub
            set mergedNotes to my mergeTextItems(pubNotes, linefeed & "---" & linefeed)
            set pubText to pubRef & linefeed & linefeed ¬
                & item url of aPub & linefeed & linefeed ¬
                & "{" & citekey of aPub & "}" & linefeed & linefeed ¬
                & mergedNotes & linefeed
            copy pubText to end of allPubTexts
        end repeat
    end tell
    -- 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
    
  29. 119 Posted by matthias on 17 Feb, 2015 06:59 AM

    matthias's Avatar

    HI Mendel,

    I'd like to export abstracts, citekeys, notes, highlights, and the 'my review' tab to a simple plain text file in my dropbox (as opposed to a Devonthink note).

    See this post for a script that will save all Papers notes and highlight annotations of all selected publications to individual text files.

    It should be possible to adopt the script to your needs. If you provide detailed description & examples for the desired file names and content I may be able to help you with that.

    If this would be able to run automatically, say once a day, that would be even better

    You can save a script as stay open, and make it run every x minutes/hours etc. But you could also trigger it using a tool like Keyboard Maestro or QuicKeys.

    Hope this helps,
    Matthias

  30. 120 Posted by matthias on 02 Mar, 2015 02:07 PM

    matthias's Avatar

    Hi,

    below is a script we use for debugging purposes. We've had reports from users where some of their PDFs got disconnected from their corresponding entries in the Papers library. While we've never really been able to reproduce this ourselves, this script may be useful for you if you have a similar issue. The "Repair File Path Metadata" menu command (under "Help > Troubleshooting") is also worth trying (it reports its findings to the Console.app log).

    The script will select all publications in your library whose main PDF file appears to be missing. To run the below script, copy it into a new ScriptEditor.app document and save it, e.g., as an application that you can double click. Then select the "All Papers" collection (in Library mode) and run the script. After the script indicates it's finished, you can hit Cmd-Shift-N to create a new manual collection from all selected papers.

    Matthias

    -- Selects all publications whose main PDF file is missing.
    -- Before running this script, please make sure that you've selected the "All Papers" collection in Library mode.
    
    tell application id "com.mekentosj.papers3"
        tell front library window to set selected mode to Library Mode
        set pubList to every publication item
        set pubsWithMissingPDFs to {}
        repeat with aPub in pubList
            set f to primary file item of aPub
            if f is not missing value then
                if full path of f is "" or full path of f is missing value then
                    copy aPub to end of pubsWithMissingPDFs
                end if
            end if
        end repeat
        activate
        tell front library window to set selected publications to pubsWithMissingPDFs
        display dialog "Did select publications with missing PDF: " & (count of pubsWithMissingPDFs) & linefeed & linefeed & "To create a new collection for these papers, choose 'File > New Collection > Collection from Selection'." buttons {"OK"} default button "OK" with icon 1
    end tell
    

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