Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Daily notes format with locale support #42

Open
nerdneilsfield opened this issue Sep 23, 2021 · 5 comments
Open

Daily notes format with locale support #42

nerdneilsfield opened this issue Sep 23, 2021 · 5 comments

Comments

@nerdneilsfield
Copy link

nerdneilsfield commented Sep 23, 2021

My daily note format is 'YYYY-MM-DD_dddd' with setting the language of obsidan vault to Chinese, so the daily note is looking like 2021-09-23_星期四. When using the obsidian-alfred after setting the daily note format, it can not determine the language setting and open the current daily note but only English version 2021-09-23_Thursday. Maybe there can be a new feature to determine the language settings?

@hauselin
Copy link
Owner

hauselin commented Oct 3, 2021

This workflow only supports English right now, but feel free to make changes/pull requests.

If you want to, you can edit the code yourself here by clicking on the bash script and making minor changes. Let me know if the solution below works for you.

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
var months_short = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', '星期四', 'Friday', 'Saturday']
var days_short = ['Sun', 'Mon', 'Tue', 'Wed', '星期四', 'Fri', 'Sat']

Screenshot_20211002_231000

@daolou
Copy link

daolou commented Dec 10, 2021

image
image

it not work

@daolou
Copy link

daolou commented Dec 10, 2021

image

this line throw an error, but it print "[native code]", so I don't know why

@daolou
Copy link

daolou commented Dec 13, 2021

image

It seems necessary to have an .md suffix of app.read

@daolou
Copy link

daolou commented Dec 13, 2021

My script is:

/* cSpell:disable */

ObjC.import('stdlib');
console.log('Running script - od')

// get the current app to access the standard additions
app = Application.currentApplication();
app.includeStandardAdditions = true;

// replace ~ with homepath
function interpolate_homepath(path) {
    homepath = app.pathTo('home folder')
    return path.replace(/^~/, homepath)
}

// date format
date_format = $.getenv('dailyformat')
console.log('date_format',date_format)

// vault name
v = $.getenv('dailyvaultname');
console.log('dailyvaultname', v)

// specify the absolute/full path to the directory where you keep your daily notes
fulldir_daily = $.getenv('dailyabspath');
fulldir_daily = interpolate_homepath(fulldir_daily)
console.log('fulldir_daily',fulldir_daily)

// if you have a template for your daily note, specify the absolute/full path to this note
fullpath_template = $.getenv('dailytempabspath');
fullpath_template = interpolate_homepath(fullpath_template)
console.log('fullpath_template',fullpath_template)






var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
var months_short = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

// https://momentjscom.readthedocs.io/en/latest/moment/07-customization/04-weekday-abbreviations/
var days = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
var days_short = ['周天', '周一', '周二', '周三', '周四', '周五', '周六'];
var days_e = [0, 1, 2, 3, 4, 5, 6]
var days_E = [7, 1, 2, 3, 4, 5, 6]

// get week of year
function ISO8601_week_no(dt) {
    var tdt = new Date(dt.valueOf());
    var dayn = (dt.getDay() + 6) % 7;
    tdt.setDate(tdt.getDate() - dayn + 3);
    var firstThursday = tdt.valueOf();
    tdt.setMonth(0, 1);
    if (tdt.getDay() !== 4) {
        tdt.setMonth(0, 1 + ((4 - tdt.getDay()) + 7) % 7);
    }
    return 1 + Math.ceil((firstThursday - tdt) / 604800000);
}


function isCharacterALetter(char) {
    return (/[a-zA-Z]/).test(char)
}




// get today's date
today = new Date();
yyyy = today.getFullYear().toString();
mm = (today.getMonth() + 1).toString();
dd = today.getDate().toString();
ww = ISO8601_week_no(today).toString();
day = today.getDay()










var date_format_original = date_format;

// get today's day if requested
if (date_format.includes('dddd')) {
    day_string = days[day]
    date_format = date_format.replace('dddd', 'zzzz')
}
if (date_format.includes('ddd')) {
    day_string_short = days_short[day]
    date_format = date_format.replace('ddd', 'zzz')
}

// TODO clean up the two blocks of if statements
// don't replace letter e or E that appear before/after alphabets
if (date_format.includes('e')) {
    for (var i = 0; i < date_format.length; i++) {
        console.log(date_format.charAt(i));
        if (i == (date_format.length - 1) && date_format.charAt(i) == "e") {
            if (!isCharacterALetter(date_format.charAt(i - 1))) {
                date_format = date_format.substring(0, i) + '!!!' + date_format.substring(i + 1);
            } 
        }
        if (i == 0 && date_format.charAt(i) == "e") {
            if (!isCharacterALetter(date_format.charAt(i + 1))) {
                date_format = date_format.substring(0, i) + '!!!' + date_format.substring(i + 1);
            }
        }
        if (i > 0 && i < (date_format.length - 1) && date_format.charAt(i) == "e") {
            if (isCharacterALetter(date_format.charAt(i - 1)) || isCharacterALetter(date_format.charAt(i + 1))) {
                continue
            } else {
                console.log("replacing this e")
                // date_format = date_format.replaceAll('e', '!!!')
                date_format = date_format.substring(0, i) + '!!!' + date_format.substring(i + 1);
            }
        }
    }    
}

// if (date_format.includes('E')) {
//     date_format = date_format.replaceAll('E', '@@@')
// }
if (date_format.includes('E')) {
    for (var i = 0; i < date_format.length; i++) {
        console.log(date_format.charAt(i));
        if (i == (date_format.length - 1) && date_format.charAt(i) == "E") {
            if (!isCharacterALetter(date_format.charAt(i - 1))) {
                date_format = date_format.substring(0, i) + '@@@' + date_format.substring(i + 1);
            }
        }
        if (i == 0 && date_format.charAt(i) == "E") {
            if (!isCharacterALetter(date_format.charAt(i + 1))) {
                date_format = date_format.substring(0, i) + '@@@' + date_format.substring(i + 1);
            }
        }
        if (i > 0 && i < (date_format.length - 1) && date_format.charAt(i) == "E") {
            if (isCharacterALetter(date_format.charAt(i - 1)) || isCharacterALetter(date_format.charAt(i + 1))) {
                continue
            } else {
                console.log("replacing this E")
                // date_format = date_format.replaceAll('e', '@@@')
                date_format = date_format.substring(0, i) + '@@@' + date_format.substring(i + 1);
            }
        }
    }
}




date_format = date_format.toLowerCase();
console.log('original: ' + date_format_original);
console.log('date_format: ' + date_format);

// determine no. of y, m, d needed
function repeatingSeqs(arr) {
    // 	repeatingSeqs('day-yyyy-mm-dd'.split("")) == [
    //   [ 'd' ],
    //   [ 'a' ],
    //   [ 'y' ],
    //   [ '-' ],
    //   [ 'y', 'y', 'y', 'y' ],
    //   [ '-' ],
    //   [ 'm', 'm' ],
    //   [ '-' ],
    //   [ 'd', 'd' ]
    // ]
    return arr.reduce((agg, x) => {
        const phrase = agg[agg.length - 1];
        if (phrase && phrase.length && phrase[0] === x) {
            return [...agg.slice(0, -1), phrase.concat(phrase[0])];
        } else {
            return [...agg, [x]];
        }
    }, []);
}

function maxRepeatingSeqLens(arr) {
    return repeatingSeqs(arr).reduce(
        (counts, chain) => ({
            ...counts,
            [chain[0]]:
                counts[chain[0]] > chain.length
                    ? counts[chain[0]]
                    : chain.length,
        }),
        {}
    );
}

console.log(date_format)
n_char = maxRepeatingSeqLens(date_format.split(""))

n_y = n_char['y'] || 1
n_m = n_char['m'] || 1
n_d = n_char['d'] || 1
n_w = n_char['w'] || 1

y_char = "y".repeat(n_y);
m_char = "m".repeat(n_m);
d_char = "d".repeat(n_d);
w_char = "w".repeat(n_w);

console.log('y_char: ' + y_char);
console.log('m_char: ' + m_char);
console.log('d_char: ' + d_char);
console.log('w_char: ' + w_char);


// format date according to user specification (e.g., yy, m, d)
yyyy = yyyy.slice(4 - n_y, 4);
if (mm.length == 1) { mm = mm.padStart(2, '0').slice(2 - n_m, 2) };
if (dd.length == 1) { dd = dd.padStart(2, '0').slice(2 - n_d, 2) };
if (ww.length == 1) { ww = ww.padStart(2, '0').slice(2 - n_w, 2) };

date_format = date_format.replace(y_char, yyyy);
date_format = date_format.replace(m_char, mm);
date_format = date_format.replace(d_char, dd);
date_format = date_format.replace(w_char, ww);

console.log('2. date_format: ' + date_format);

// convert to MMM or MMMM
if (m_char == 'mmmm') {
    date_format = date_format.replace(mm, months[Number(mm) - 1])
}
if (m_char == 'mmm') {
    date_format = date_format.replace(mm, months_short[Number(mm) - 1])
}
// if (m_char == 'mm') {
//     date_format = date_format.replace(mm, mm.padStart(2, '0'))
// }

// day of week if requested
if (date_format.includes('zzzz')) {
    date_format = date_format.replace('zzzz', day_string)
}
if (date_format.includes('zzz')) {
    date_format = date_format.replace('zzz', day_string_short)
}
// e is day of week (0, 1, ... 7)
if (date_format_original.includes('e')) {
    date_format = date_format.replace('!!!', days_e[day].toString())
}
if (date_format_original.includes('E')) {
    date_format = date_format.replace('@@@', days_E[day].toString())
}

console.log('3. date_format: ' + date_format);

p = encodeURIComponent(v) + "&file=" + encodeURIComponent(date_format) + ".md";
uri = "obsidian://open?vault=" + p;


console.log('uri', uri);


// create new daily note if it doesn't exist
if (fulldir_daily != "") {
    // format file path
    if (fulldir_daily[(fulldir_daily.length - 1)] != "/") { fulldir_daily += "/" }
    filepath = fulldir_daily + date_format + ".md"

    console.log('filepath', filepath);

    // get template content
    var template_txt = ""
    if (fullpath_template != "") {
        console.log('fullpath_template', fullpath_template);
        var template_path_obj = Path(fullpath_template);
        console.log('template_path_obj', template_path_obj)
		var template_txt_path = Path(fullpath_template);
		console.log('template_txt_path', template_txt_path);
		template_txt = app.read(template_txt_path+".md");
    }

    console.log('template_txt', template_txt);

    // create note with template (if exists)
    var path = Path(filepath)
    var finderApp = Application("Finder")
    if (!finderApp.exists(path)) {
        console.log("Note doesn't exist. Creating note.")
        var openedFile = app.openForAccess(path, { writePermission: true })
        app.write(template_txt, { to: openedFile, startingAt: app.getEof(openedFile) })
        app.closeAccess(openedFile)
        uri = "obsidian://open?path=" + encodeURIComponent(filepath)
        // wait a bit for note to show up in file system
        delay(1)
    }
}


if (v == "" | date_format == "2111") {
    app.displayDialog("Set up the workflow first")
} else {
    // open file in vault
    app.openLocation(uri);
    console.log(uri);
}


// save today note path
Application('com.runningwithcrayons.Alfred').setConfiguration("dailytodaypath", {
    toValue: filepath,
    exportable: false,
    inWorkflow: $.getenv('alfred_workflow_bundleid'),
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants