Jump to content

How: macOS Text Replacement -> Alfred Snippets


Recommended Posts

Hi, I have a lot of text expansion snippets in macOS system preferences and have managed to export these into a plist file.

 

Is there a way to simply import these into Alfred or do I have to manually add them in, one by one?

 

Many thanks.

 

C

Link to comment
  • 1 month later...

@deanishe

hi 

I am trying to get the sun macOs text replacements to alfred snippets using the script but I am not making any progress
I am total noob so Please be Patient with me an help me out. 
First I made a folder called snippets here (Please see image)
Then I modified the script as mentioned by replacing SNIPPETS_DIR to snippets(the folder I created)
Then finally i ran the script and i get this error
any help will be much appreciated
 
 
 

image.png

image.jpeg

image.png

Link to comment
3 hours ago, Shantni said:

First I made a folder called snippets here (Please see image)

 

No, the “snippets” folder is inside the Alfred.alfredpreferences bundle. Right-click on it and choose “Show Package Contents"

 

That should be clear from the “Configuration” section on the page linked above. It's important to read carefully if you're a noob.

Link to comment

@deanishe

Thank you  for your reply.

 I did read that part but I guess I am simply too dumb to understand that. So I just copy the script and run instead of making any changes?  I'm getting the same error message still?  

 I tried running  the terminal from both snippets directory in the bundle you suggested and also from the macOS sub directory 

zsh: event not found: /usr/bin/python is the error I get 

Edited by Shantni
Added more info
Link to comment
7 hours ago, Shantni said:

I tried running  the terminal from both snippets directory

 

Just run it from this directory. You seem to be running it wrong. I don’t know what app you’re using in your screenshot, but it isn’t a code editor. The script must be plain text, not some RTF or DOC file. If you haven’t made the script executable with chmod +x shortcuts2alfred.py, you have to run it like in a shell this: /usr/bin/python shortcuts2alfred.py

 

To specify the snippet directory, run SNIPPET_DIR=/path/to/Alfred.preferences/snippets /usr/bin/python shortcuts2alfred.py

 

So if you’re using the standard prefs location (i.e. you aren’t syncing your prefs), the shell command you need would be: SNIPPET_DIR="~/Library/Application Support/Alfred/Alfred.alfredpreferences/snippets" /usr/bin/python shortcuts2alfred.py

 

Link to comment
  • 2 years later...
On 7/17/2021 at 1:14 AM, deanishe said:

If something about my instructions isn't clear, then I'd be happy to clarify.

Hi @deanishe

Thank so much for your code.

 

*** when I run it in Terminal I had this error message:
 line 89
    os.makedirs(dirpath, 0700)
                                        ^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

 

*** To resolve it I used 0o prefix to be like that:
os.makedirs(dirpath, 0o700)
 

*** After I run the code again I had this error message:

Traceback (most recent call last):

  File "/Users/farisal-mawwashi/Downloads/untitled folder/shortcuts2alfred (1).py", line 113, in <module>

    main()

  File "/Users/farisal-mawwashi/Downloads/untitled folder/shortcuts2alfred (1).py", line 106, in main

    shortcuts = load_shortcuts()

                         ^^^^^^^^^^^^^^^^

  File "/Users/farisal-mawwashi/Downloads/untitled folder/shortcuts2alfred (1).py", line 56, in load_shortcuts

    for row in reader:

_csv.Error: iterator should return strings, not bytes (the file should be opened in text mode)

*** The attached screenshot shows this.

Please, How can I resolve the error?
NOTE: I am not a programmer, and my knowledge is limited in this field, but I can follow the instructions to get the desired result.

 

Thank you so much.

 

MacBook Pro 16” m1pro 2021
macOS Sonoma 14.4.1 

Alfred 5.5

 

 

image.thumb.png.fb23e38c783ee1e8b19bdca831d72045.png

Link to comment

@Faris Najem That code is Python 2, and Python 3 broke quite a few things. Fortunately, this script seems simple enough that automatic conversion might be possible. Replace the contents of the script with the code below and try again.

 

#!/usr/bin/python3
# encoding: utf-8
#
# Copyright (c) 2020 Dean Jackson <deanishe@deanishe.net>
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2020-06-22
# Modified with 2to3 on 2024-05-01

"""Convert macOS text shortcuts to Alfred snippets."""



from collections import namedtuple
import csv
from io import BytesIO
import json
import os
from os.path import expanduser, join, realpath
from subprocess import check_output
import sys


# directory to save snippets to
SNIPPET_DIR = os.getenv('SNIPPET_DIR') or '.'
COLLECTION_NAME = os.getenv('COLLECTION_NAME') or 'macOS'


DBPATH = expanduser('~/Library/KeyboardServices/TextReplacements.db')
QUERY = """
select ZUNIQUENAME, ZSHORTCUT, ZPHRASE
    from ZTEXTREPLACEMENTENTRY
    where ZWASDELETED = 0;
"""


Shortcut = namedtuple('Shortcut', 'uid keyword snippet')


def log(s, *args, **kwargs):
    """Log to STDERR."""
    if args:
        s = s % args
    elif kwargs:
        s = s % kwargs

    print(s, file=sys.stderr)


def load_shortcuts():
    """Read shortcuts from system SQLite database."""
    output = check_output(['/usr/bin/sqlite3', '-csv', DBPATH, QUERY])

    reader = csv.reader(BytesIO(output), delimiter=',', quotechar='"')
    shortcuts = []
    for row in reader:
        if len(row) == 3:
            sc = Shortcut(*[s.decode('utf-8') for s in row])
            if sc.keyword == sc.snippet:  # ignore do-nothing shortcuts
                continue
            shortcuts.append(sc)

    return shortcuts


def shortcut_to_snippet(shortcut):
    """Create Alfred snippet dict from macOS shortcut."""
    return {
        'alfredsnippet': {
            'snippet': shortcut.snippet,
            'uid': shortcut.uid,
            'name': shortcut.keyword,
            'keyword': shortcut.keyword,
        }
    }


def safename(s):
    """Make filesystem-safe name."""
    for c in ('/', ':'):
        s = s.replace(c, '-')
    return s


def export_shortcuts(shortcuts, dirpath):
    """Save macOS shortcuts to directory as Alfred snippets."""
    log('exporting snippets to %r ...', dirpath)
    if not os.path.exists(dirpath):
        os.makedirs(dirpath, 0o700)

    # remove existing snippets
    for name in os.listdir(dirpath):
        if name.endswith('.json'):
            os.unlink(os.path.join(dirpath, name))

    for i, sc in enumerate(shortcuts):
        name = '%s [%s].json' % (safename(sc.keyword), sc.uid)
        path = join(dirpath, name.encode('utf-8'))
        log('[%d/%d] saving snippet %r to %r ...', i+1, len(shortcuts), sc.keyword, path)
        with open(path, 'wb') as fp:
            json.dump(shortcut_to_snippet(sc), fp, indent=2, separators=(',', ': '))


def main():
    """Run script."""
    shortcuts = load_shortcuts()
    log('loaded %d macOS shortcut(s)', len(shortcuts))
    dirpath = realpath(expanduser(join(SNIPPET_DIR, COLLECTION_NAME)))
    export_shortcuts(shortcuts, dirpath)


if __name__ == '__main__':
    main()

 

Link to comment
4 hours ago, vitor said:

Replace the contents of the script with the code below and try again.

Thank you so much @vitor to your response.


As you can see in the attached screenshot, I ran the new script (pasted over the old one) via Terminal several times, but encountered errors each time. Could you please provide any assistance?

 

Thanks again.

 

image.thumb.png.303232b546befb26b3a1ee945db8763b.png

Link to comment
  • 2 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...