Custom search in filtered decks?

I’m trying to create a custom search with the format: dadded:YYYY-MM-DD. Anki should interpret it as added:x, where x is the number of days elapsed from YYYY-MM-DD to the current date.

For example, if I search for dadded:2024-06-01 and today is 2024-06-21, it should correspond to added:20.

The following code seems to work well enough in the Browser, but I haven’t been able to adapt it for Filtered decks. I also couldn’t find anything useful in the documentation. Any help would be much appreciated.

def on_browser_will_search(context):
    search_text = context.search.strip()

    # Helper function to replace custom keys
    def replace_custom_key(search_text, custom_key, replacement_value):
        return search_text.replace(custom_key, replacement_value)

    # Pattern for "dadded:YYYY-MM-DD"
    pattern = re.compile(r'dadded:(\d{4}-\d{2}-\d{2})')
    match = pattern.search(search_text)
    if match:
        date_str = match.group(1)
        try:
            # Converts the date to a datetime object
            date_obj = datetime.strptime(date_str, "%Y-%m-%d")
            # Calculates the difference in days between the specified date and today
            delta_days = (datetime.now() - date_obj).days
            # Replaces the original query with the new query with added:<days>
            search_text = replace_custom_key(search_text, match.group(0), f"added:{delta_days}")
        except ValueError:
            pass

    context.search = search_text

gui_hooks.browser_will_search.append(on_browser_will_search)

I don’t think you’ll be able to do that in Python. You could make the add-on automatically rewrite the search term stored in the filtered deck instead, though.

1 Like

Thanks, Damien!

Automatically replacing the search term is an interesting idea. However, I don’t think it would be very useful in my specific case, at least as far as I understand it. My goal is to have a search term that doesn’t require manual updates over time.

For instance, instead of having to update “added:10” to “added:11,” “added:12,” and so on daily, I would prefer a search term that includes all cards added since a specific date. The same applies to other search terms such as rated, prop:due.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.