Last active
September 19, 2024 13:19
-
-
Save marcbelmont/e715f807a30d96cf74f66006d0e5e4a6 to your computer and use it in GitHub Desktop.
Manage notes stored in a text file using Rofi. Bonus: tiny calculator using Python's eval. For details, see first comment.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python3 | |
import os | |
import sys | |
from pathlib import Path | |
NOTES = Path('~/Documents/notes.txt').expanduser() | |
def to_clipboard(text): | |
os.system('echo "%s"|xclip -f -r -sel c > /dev/null' % str(text).strip()) | |
def calc_mode(user_input): | |
try: | |
result = eval(user_input) | |
print(user_input) | |
to_clipboard(result) | |
print(f"\0message\x1f🐍: {result} <i>(copied to clipboard)</i>\n") | |
return True | |
except Exception: | |
return False | |
def main(): | |
if not NOTES.exists(): | |
print(f'{NOTES} does not exist.') | |
return | |
user_input = sys.argv[1] + '\n' if len(sys.argv) > 1 else None | |
if user_input and calc_mode(user_input): | |
return | |
# Notes | |
with open(NOTES) as fp: | |
lines = fp.readlines() | |
if user_input: | |
try: | |
deleted = lines.pop(lines.index(user_input)) | |
to_clipboard(deleted) | |
except Exception: | |
if '[empty]' not in user_input: | |
lines.append(user_input) | |
with open(NOTES, 'w') as fp: | |
fp.writelines(lines) | |
# Display list | |
print("\0message\x1f<i>(Type text or a Python expression)</i>\n") | |
if lines: | |
print('\n'.join(reversed(lines))) | |
else: | |
print('[empty]') | |
if __name__ == "__main__": | |
main() |
Nice.
You can replace notes path to
NOTES = Path('~/Documents/notes.txt').expanduser()
Execute eval()
for every input, even if you want to add a new text node is extreme dangerous.
@rysson
Thanks, I've updated NOTES
.
You're right about eval
. What's a better way to handle this?
Oh, the best is using eg. simpleeval
(https://github.com/danthedeckie/simpleeval) but it's external dependencies.
Otherwise maybe you cloud use some prefix character (like =
) to call calculator (still using evil eval
), to avoid call eval
for every input.
Instead
if user_input and calc_mode(user_input):
return
I propose
if user_input and user_input.startswith('=') and calc_mode(user_input)[1:]:
return
It's not perfect and change behavior. It's only proposition.
Actually, on my local version, I removed it entirely and switched to https://github.com/svenstaro/rofi-calc. It's based on qalc and does live updates. Very convenient.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Installation
/path/to/rofi_notes.py
NOTES
to a text file in your local file system.rofi -show notes -modi notes:/path/to/rofi_notes.py
Features