Rudy’s OBTF Rudolf Adamkovič

Home / Notmuch / Notmuch


My pre-new hook

The ~/.notmuch/hooks/pre-new script

runs just before notmuch new,

written in Bash:

# Notmuch `pre-new' hook.
#
# This script:
# 1. moves messages from/to correct folders
# 2. synchronizes messages with the IMAP server.
#
# Rudolf Adamkovič <rudolf@adamkovic.org>
# Licensed under the General Public License (GPL), version 3.

set -e

# Signature:
#   file QUERY...
# Description:
#   Return all files matching QUERY.
files() {
    QUERY=$@
    notmuch search --output=files --exclude=false ${QUERY}
}

# Signature:
#   move DIR QUERY...
# Description:
#   Move COUNT files matching QUERY to DIR.
move() {
    DIR=${1} QUERY=${@:2}
    FILES=($(files ${QUERY}))
    for FILE in ${FILES[*]}; do
        # if test -f ${FILE}; then
            TO_FILE=${FILE##*/} # just basename
            TO_FILE=${TO_FILE/,U=[0-9]*/} # no metadata
            mv ${FILE} ${DIR}/${TO_FILE}
        # fi
    done
}

# Signature:
#   delete QUERY...
# Description:
#   Delete all files matching QUERY.
delete() {
    QUERY=${@}
    FILES=($(files ${QUERY}))
    if test ${#FILES[*]} -gt 0; then
        rm -f ${FILES[*]}
    fi
}

# Signature:
#   sync
# Description:
#   Synchronize with IMAP server.
sync() {
    if ping -c 1 imap.fastmail.com &>/dev/null; then
        mbsync --all
    else
        echo "IMAP server unreachable." >&2
    fi
}

ROOT=$(notmuch config get database.mail_root)
mkdir -p ${ROOT}

echo "Deleting..."
delete is:deleted
delete is:draft

echo "Moving spam in..."
move ${ROOT}/Spam/new is:spam and not folder:Spam and is:unread
move ${ROOT}/Spam/cur is:spam and not folder:Spam and not is:unread

echo "Moving spam out..."
move ${ROOT}/INBOX/new folder:Spam and not is:spam and is:unread
move ${ROOT}/INBOX/cur folder:Spam and not is:spam and not is:unread

echo "Syncing..."
sync

© 2025 Rudolf Adamkovič under GNU General Public License version 3.
Made with Emacs and secret alien technologies of yesteryear.