obsidian-execute-code icon indicating copy to clipboard operation
obsidian-execute-code copied to clipboard

[FEATURE] Allow code block to fold and still be able to run

Open JCSnap opened this issue 10 months ago β€’ 5 comments

Is your feature request related to a problem? Please describe. Currently, my workflow includes running some code blocks as "buttons". However, the code can be very long, and I want the code block to look like a "button" where I can press it without it being 80 lines long

Describe the solution you'd like Allow an interface that allows us to "fold" the code block into one line and still be able to run it

Describe alternatives you've considered Right now, if I define a header on top of the code block, I can fold the code block, but I can't run the code block.

JCSnap avatar Mar 11 '25 13:03 JCSnap

Hi, I think that's an interesting use case of this plugin.

However, it's a funny coincidence that you opened this issue. Just yesterday I thought of creating a plugin that lets you embed buttons in your notes. Do you mind sharing an example script of what you use the buttons for?

twibiral avatar Mar 11 '25 15:03 twibiral

@twibiral sure!

I am trying to "gamify" my life by turning it into an RPG game and I use Obsidian as a medium to moderate this real life RPG.

I have tasks which, when completed, will add coins to my account. Instead of manually changing the "coins" count I have every time I complete a task, ideally I should be able to automate it.

For instance, I could have the following in RLRPG Main.md:

Inventory

coins: 50

Active Tasks

  • [ ] Finish assignment 1

Passive Tasks

  • [x] walk 5k steps 10 coins
  • [ ] read 5 pages of book 5 coins
  • [ ] consume within 1600 calories 10 coins
  • [ ] use < 1 hour of tiktok 5 coins

Ideally, I have a Python code block which I run at the end of the day, which will:

  1. open up RLRPG Main.md
  2. iterate through each line of the tasks
  3. if task is completed, add the coin amount to my inventory (by literally running a script to open up RLRPG Main.md, locate # Inventory and editing the coin count, append {date}: +10 coins (daily steps count met) to RLRPG Transactions.md
  4. For recurring tasks like "walk 5k steps", unmark the [ ], for one-time off tasks, delete them

Another use case I have (also part of this gamification system) is that I want to add coins every time I finish one LeetCode question.

So, every time I do a leetcode question, I will create a note using this template. Once I am done, I will "submit" and the Python code will add coins to my account (and transaction history) based on the difficulty of the LeetCode problem etc.

Right now it is a bit cumbersome because this "submit" script will appear in all my LeetCode notes haha

Leetcode template

<%*
const id = tp.file.title.split(" ")[0];
const createdDate = tp.file.creation_date('YYYY-MM-DD');
const updatedDate = tp.file.last_modified_date('YYYY-MM-DD');

const difficultyOptions = ["easy", "medium", "hard"];
const difficulty = await tp.system.suggester(difficultyOptions, difficultyOptions, false, "Select difficulty level");

const yamlContent = `---
id: ${id}
created_date: ${createdDate}
updated_date: ${updatedDate}
type: leetcode
difficulty: ${difficulty}
---
`;

tR += yamlContent;
%>
# πŸ“š <% tp.file.title %>
- **🏷️Tags** :   #<% tp.file.creation_date('MM-YYYY') %> #leetcode
## πŸ’­ Approach
- 

## βœ… Suggested solution
```python

πŸ‘¨β€πŸ’» Your solution

πŸ“ Note

Submit to RLRPG

import os
import re
from datetime import datetime

vault_path = @vault_path
rlrpg_folder = "/RLRPG/"
main_file = vault_path + rlrpg_folder + "RLRPG Main.md"
transactions_file = vault_path + rlrpg_folder + "RLRPG Transactions.md"
cur_file = os.path.join(vault_path, @note_path)

difficulty = None
with open(cur_file, "r", encoding="utf-8") as f:
    for line in f:
        if match := re.match(r"difficulty:\s*(easy|medium|hard)", line, re.IGNORECASE):
            difficulty = match.group(1).lower()
            break

gold_rewards = {"easy": 2, "medium": 5, "hard": 10}
if difficulty not in gold_rewards:
    print("Difficulty not found. No changes made.")
    exit()

gold_to_add = gold_rewards[difficulty]

with open(main_file, "r", encoding="utf-8") as f:
    lines = f.readlines()

in_items_section, gold_updated, new_lines = False, False, []

for line in lines:
    if line.strip() == "## Items":
        in_items_section = True
    elif in_items_section and re.match(r"^\s*## ", line):  
        in_items_section = False

    if in_items_section and (match := re.match(r"^(gold:\s*`)(\d+)(`)", line, re.IGNORECASE)):
        new_gold = int(match.group(2)) + gold_to_add
        line = f"{match.group(1)}{new_gold}{match.group(3)}\n"
        gold_updated = True

    new_lines.append(line)

if gold_updated:
    with open(main_file, "w", encoding="utf-8") as f:
        f.writelines(new_lines)

    leetcode_title = @title
    transaction_entry = f"{datetime.now().strftime('%Y-%m-%d')}: `+{gold_to_add}` (LeetCode {leetcode_title} - {difficulty.capitalize()})\n"

    with open(transactions_file, "a", encoding="utf-8") as f:
        f.write(transaction_entry)

    print(f"Gold increased by {gold_to_add}. Transaction logged.")

else:
    print("Gold value not found. No changes made.")

JCSnap avatar Mar 11 '25 16:03 JCSnap

Wow, that's amazing! I love that the plugin helps people like you to implement such incredible ideas!

Maybe I can add a button mode or something similar for you. At the same time I can add a "danger mode" that allows you to access the JS runtime of Obsidian.

twibiral avatar Mar 11 '25 16:03 twibiral

thanks for your work on this plugin! being able to run code snippets has expanded my use case a lot, looking forward to the new feature :)

JCSnap avatar Mar 11 '25 19:03 JCSnap

Wow, that's amazing! I love that the plugin helps people like you to implement such incredible ideas!

Maybe I can add a button mode or something similar for you. At the same time I can add a "danger mode" that allows you to access the JS runtime of Obsidian.

Just wondering if the button mode got added? I'd like to hide the code and just have a run button

paulharman avatar Jun 23 '25 10:06 paulharman