Skip to content

Project: To-Do List CLI

In this project you’ll build a small to-do list that lives in your terminal. You type add Buy milk, and it remembers. Close the terminal, come back tomorrow, type list, and your tasks are still there.

It’s a good second project because it looks like a real tool. It uses structs with methods, printing your own types, lists, match, custom errors, command-line arguments and file I/O. We’ll build and test each piece on its own, and then put it all together.

Here’s a real session with the finished tool:

Terminal window
$ mojo run todo.mojo add Buy milk
Added task 1.
$ mojo run todo.mojo add Call grandma
Added task 2.
$ mojo run todo.mojo done 1
Marked task 1 as done.
$ mojo run todo.mojo list
[x] 1: Buy milk
[ ] 2: Call grandma
$ mojo run todo.mojo done two
error: 'two' isn't a task number
$ mojo run todo.mojo remove 1
Removed task 1: Buy milk

The tasks live in a file called todo.txt, one task per line, in the form id|done|text:

2|0|Call grandma

done is 1 for finished and 0 for not finished. A plain text format like this is easy to read, easy to fix by hand, and easy to parse.

Every task has a number (so you can refer to it), a done flag and some text. That’s a struct. We give it three methods: one to turn a task into a line for the file, one to read a task back from a line, and write_to so print(task) shows it nicely.

@fieldwise_init
struct Task(Copyable, Writable):
var id: Int
var done: Bool
var text: String
def to_line(self) -> String:
return String(t"{self.id}|{1 if self.done else 0}|{self.text}")
@staticmethod
def from_line(line: StringSlice) raises -> Task:
var parts = line.split("|", maxsplit=2)
if len(parts) != 3:
raise Error(t"bad line: {line}")
return Task(Int(parts[0]), parts[1] == "1", String(parts[2]))
def write_to(self, mut writer: Some[Writer]):
writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def main() raises:
var task = Task(1, False, "Buy milk | eggs")
print(task)
var line = task.to_line()
print(line)
var back = Task.from_line(line)
print(back.id, back.done, back.text)
try:
_ = Task.from_line("oops")
except e:
print("Error:", e)

Output:

[ ] 1: Buy milk | eggs
1|0|Buy milk | eggs
1 False Buy milk | eggs
Error: bad line: oops

Let’s go through it:

  • to_line builds the line with a t-string. 1 if self.done else 0 is a conditional expression, the same as in Python.
  • from_line is a static method: it has no self, and you call it on the type, Task.from_line(...). It raises because a broken line (or a bad number in it) is an error the caller should hear about.
  • split("|", maxsplit=2) splits at most twice. That’s what keeps a | inside the text safe: Buy milk | eggs survives the round trip in one piece.
  • write_to is what print calls for a Writable type. The Mojo Printing Your Types lesson explains it.

All the tasks live in a List[Task]. We need three small helpers: pick the next free number, find a task by its number, and change or remove it.

@fieldwise_init
struct Task(Copyable, Writable):
var id: Int
var done: Bool
var text: String
def write_to(self, mut writer: Some[Writer]):
writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def next_id(tasks: List[Task]) -> Int:
var biggest = 0
for task in tasks:
biggest = max(biggest, task.id)
return biggest + 1
def find(tasks: List[Task], id: Int) -> Int:
for i in range(len(tasks)):
if tasks[i].id == id:
return i
return -1
def main():
var tasks: List[Task] = []
tasks.append(Task(next_id(tasks), False, "Buy milk"))
tasks.append(Task(next_id(tasks), False, "Call grandma"))
tasks.append(Task(next_id(tasks), False, "Water the plants"))
var i = find(tasks, 2)
tasks[i].done = True
var removed = tasks.pop(find(tasks, 1))
print("Removed:", removed.text)
tasks.append(Task(next_id(tasks), False, "Read a book"))
for task in tasks:
print(task)
print("Task 9 is at index", find(tasks, 9))

Output:

Removed: Buy milk
[x] 2: Call grandma
[ ] 3: Water the plants
[ ] 4: Read a book
Task 9 is at index -1

A few details worth a closer look:

  • next_id uses the biggest number plus one, not len(tasks) + 1. After removing task 1, there are 2 tasks left, and len + 1 would hand out the number 3 a second time. The biggest-plus-one rule never repeats a number that’s still in use.
  • find returns the index, or -1 when there’s no such task. Mojo has no negative indexing, so -1 can’t be mistaken for a real position.
  • tasks[i].done = True changes the task inside the list. That works because tasks[i] refers to the item in place. A loop variable doesn’t: see Common mistakes below.
  • tasks.pop(i) removes the item at index i and gives it back, so we can print what was removed.

The program gets its command as a list of words, like ["add", "Buy", "milk"] or ["done", "2"]. A match on the first word picks what to do. Every problem (unknown command, missing text, bad number) becomes a raised Error with a helpful message.

For now the “command line” is a hard-coded list, and the tasks stay in memory, so we can test every command in one run:

@fieldwise_init
struct Task(Copyable, Writable):
var id: Int
var done: Bool
var text: String
def write_to(self, mut writer: Some[Writer]):
writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def next_id(tasks: List[Task]) -> Int:
var biggest = 0
for task in tasks:
biggest = max(biggest, task.id)
return biggest + 1
def find(tasks: List[Task], id: Int) -> Int:
for i in range(len(tasks)):
if tasks[i].id == id:
return i
return -1
def run(args: List[String], mut tasks: List[Task]) raises:
var command = args[0]
match command:
case "add":
if len(args) < 2:
raise Error("add needs some text, like: add Buy milk")
var id = next_id(tasks)
tasks.append(Task(id, False, " ".join(args[1:])))
print(t"Added task {id}.")
case "list":
if len(tasks) == 0:
print("Nothing to do!")
for task in tasks:
print(task)
case "done" | "remove":
if len(args) != 2:
raise Error(t"{command} needs a task number, like: {command} 2")
var id: Int
try:
id = Int(args[1])
except:
raise Error(t"'{args[1]}' isn't a task number")
var i = find(tasks, id)
if i == -1:
raise Error(t"there's no task {id}")
if command == "done":
tasks[i].done = True
print(t"Marked task {id} as done.")
else:
var removed = tasks.pop(i)
print(t"Removed task {id}: {removed.text}")
case _:
raise Error(t"unknown command '{command}'")
def main():
var tasks: List[Task] = []
var commands: List[String] = [
"list", "add Buy milk", "add Call grandma", "done 1",
"done two", "remove 7", "fly", "list",
]
for line in commands:
print(t"> {line}")
var args: List[String] = []
for word in line.split():
args.append(String(word))
try:
run(args, tasks)
except e:
print(t"error: {e}")

Output:

> list
Nothing to do!
> add Buy milk
Added task 1.
> add Call grandma
Added task 2.
> done 1
Marked task 1 as done.
> done two
error: 'two' isn't a task number
> remove 7
error: there's no task 7
> fly
error: unknown command 'fly'
> list
[x] 1: Buy milk
[ ] 2: Call grandma

The new pieces:

  • mut tasks: List[Task] lets run change the caller’s list. Without mut, arguments are read-only. See Mojo Argument Conventions.
  • case "done" | "remove": matches either word, because both need the same checks. Inside, a plain if decides which one we’re doing.
  • " ".join(args[1:]) glues the remaining words back together, so add Buy milk stores Buy milk.
  • raise Error(...) inside except: when Int(args[1]) fails, we replace its technical message with a friendlier one.
  • In main, one try/except around run handles every problem in one place. That keeps run simple: it raises and moves on.

To remember tasks between runs, we write them to todo.txt after every change and read them back at the start. If the file doesn’t exist yet, that just means there are no tasks.

from std.os.path import exists
@fieldwise_init
struct Task(Copyable, Writable):
var id: Int
var done: Bool
var text: String
def to_line(self) -> String:
return String(t"{self.id}|{1 if self.done else 0}|{self.text}")
@staticmethod
def from_line(line: StringSlice) raises -> Task:
var parts = line.split("|", maxsplit=2)
if len(parts) != 3:
raise Error(t"bad line: {line}")
return Task(Int(parts[0]), parts[1] == "1", String(parts[2]))
def write_to(self, mut writer: Some[Writer]):
writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def load(path: String) raises -> List[Task]:
var tasks: List[Task] = []
if not exists(path):
return tasks^
var text = open(path, "r").read()
for line in text.splitlines():
if line.byte_length() > 0:
tasks.append(Task.from_line(line))
return tasks^
def save(tasks: List[Task], path: String) raises:
with open(path, "w") as f:
for task in tasks:
f.write(task.to_line(), "\n")
def main() raises:
print("Before saving:", len(load("demo-todo.txt")), "tasks")
var tasks: List[Task] = [Task(1, True, "Buy milk"), Task(2, False, "Call grandma")]
save(tasks, "demo-todo.txt")
print("File contents:")
print(open("demo-todo.txt", "r").read(), end="")
print("Loaded back:")
for task in load("demo-todo.txt"):
print(task)

Output:

Before saving: 0 tasks
File contents:
1|1|Buy milk
2|0|Call grandma
Loaded back:
[x] 1: Buy milk
[ ] 2: Call grandma

(Run it twice and the first line says 2 tasks, because the file is still there from the first run. Delete demo-todo.txt to start over.)

  • exists(path) from std.os.path checks for the file before we try to open it.
  • open(path, "w") creates the file, or empties it if it exists, and with closes it for us at the end of the block. The open() reference lists the other modes, such as "a" to add to the end of a file. f.write(...) takes several values, like print.
  • splitlines() cuts the text into lines, and we skip empty ones, for example a blank line you added by hand.
  • Both functions raise: a file you can’t write, or a line that isn’t id|done|text, is a real problem and the user should see it.

Now we read the real command-line arguments with argv(), load the tasks, run the command and save. Save this as todo.mojo:

from std.os.path import exists
from std.sys import argv, exit, stderr
comptime FILE = "todo.txt"
@fieldwise_init
struct Task(Copyable, Writable):
var id: Int
var done: Bool
var text: String
def to_line(self) -> String:
return String(t"{self.id}|{1 if self.done else 0}|{self.text}")
@staticmethod
def from_line(line: StringSlice) raises -> Task:
var parts = line.split("|", maxsplit=2)
if len(parts) != 3:
raise Error(t"bad line: {line}")
return Task(Int(parts[0]), parts[1] == "1", String(parts[2]))
def write_to(self, mut writer: Some[Writer]):
writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def next_id(tasks: List[Task]) -> Int:
var biggest = 0
for task in tasks:
biggest = max(biggest, task.id)
return biggest + 1
def find(tasks: List[Task], id: Int) -> Int:
for i in range(len(tasks)):
if tasks[i].id == id:
return i
return -1
def load(path: String) raises -> List[Task]:
var tasks: List[Task] = []
if not exists(path):
return tasks^
var text = open(path, "r").read()
for line in text.splitlines():
if line.byte_length() > 0:
tasks.append(Task.from_line(line))
return tasks^
def save(tasks: List[Task], path: String) raises:
with open(path, "w") as f:
for task in tasks:
f.write(task.to_line(), "\n")
def run(args: List[String]) raises:
var tasks = load(FILE)
var command = args[0]
match command:
case "add":
if len(args) < 2:
raise Error("add needs some text, like: add Buy milk")
var id = next_id(tasks)
tasks.append(Task(id, False, " ".join(args[1:])))
save(tasks, FILE)
print(t"Added task {id}.")
case "list":
if len(tasks) == 0:
print("Nothing to do!")
for task in tasks:
print(task)
case "done" | "remove":
if len(args) != 2:
raise Error(t"{command} needs a task number, like: {command} 2")
var id: Int
try:
id = Int(args[1])
except:
raise Error(t"'{args[1]}' isn't a task number")
var i = find(tasks, id)
if i == -1:
raise Error(t"there's no task {id}")
if command == "done":
tasks[i].done = True
print(t"Marked task {id} as done.")
else:
var removed = tasks.pop(i)
print(t"Removed task {id}: {removed.text}")
save(tasks, FILE)
case _:
raise Error(t"unknown command '{command}'")
def main():
var args: List[String] = []
for arg in argv()[1:]:
args.append(String(arg))
if len(args) == 0:
print("usage: todo add <text> | list | done <id> | remove <id>")
return
try:
run(args)
except e:
print(t"error: {e}", file=stderr)
exit(1)

Run it with a command after the file name. Everything after todo.mojo goes to your program:

Terminal window
mojo run todo.mojo add Buy milk
mojo run todo.mojo list

You’ll get the session from the top of this page. Run it with no command and it prints the usage line.

Compared with Step 3, two things changed:

  • argv()[1:] skips the program name and copies each argument into a String, so run gets the same kind of list it got in our test.
  • Errors go to stderr and the program ends with exit(1), so a shell script can tell that something went wrong. run also saves the file after add, done and remove, but not after list, which changes nothing.

Changing a task through the loop variable. A plain loop variable is read-only, so this doesn’t compile:

@fieldwise_init
struct Task(Copyable):
var id: Int
var done: Bool
def main():
var tasks: List[Task] = [Task(1, False), Task(2, False)]
for task in tasks:
if task.id == 2:
task.done = True
print(tasks[1].done)
todo.mojo:10:17: error: expression must be mutable in assignment
task.done = True
~~~~^~~~~
mojo: error: failed to parse the provided Mojo source module

Write for ref task in tasks: to get a reference you can change, or use an index as in tasks[i].done = True. The Mojo For lesson covers both.

Comparing a line with "". splitlines() gives you StringSpan views, and in Mojo 1.2 comparing one with a string literal doesn’t compile:

def main():
var text = "1|0|Buy milk\n\n2|1|Call grandma\n"
for line in text.splitlines():
if line != "":
print(line)
todo.mojo:4:20: error: cannot implicitly convert 'String' value to 'StringSpan[origin_of(text["bytes"])]'
if line != "":
^~
mojo: error: failed to parse the provided Mojo source module

Check line.byte_length() > 0, as in load, or turn the line into a String first.

Reusing numbers. Using len(tasks) + 1 as the next id gives two tasks the same number after a remove. Use the biggest id plus one.

  • clear: remove every finished task in one go. (Practice 1.)
  • Show a summary after list, like 1 of 3 done.
  • edit <id> <text> to change a task’s text.
  • undo <id> to mark a task as not done again.
  • Priorities: add a fourth field, high or low, and list high ones first with sort.
  • A different file: read the file name from an environment variable like TODO_FILE, with todo.txt as the default.

This exercise works on an in-memory list, like Step 2, so you can compare your output with ours.

Write def clear_done(mut tasks: List[Task]) -> Int that removes every finished task and returns how many it removed.

Hint: build a new list with only the unfinished tasks, then replace the old one: tasks = keep^.

Show solution
@fieldwise_init
struct Task(Copyable, Writable):
var id: Int
var done: Bool
var text: String
def write_to(self, mut writer: Some[Writer]):
writer.write("[x] " if self.done else "[ ] ", self.id, ": ", self.text)
def clear_done(mut tasks: List[Task]) -> Int:
var keep: List[Task] = []
for task in tasks:
if not task.done:
keep.append(task.copy())
var removed = len(tasks) - len(keep)
tasks = keep^
return removed
def main():
var tasks: List[Task] = [
Task(1, True, "Buy milk"),
Task(2, False, "Call grandma"),
Task(3, True, "Water the plants"),
]
print("Removed", clear_done(tasks), "tasks")
for task in tasks:
print(task)

Output:

Removed 2 tasks
[ ] 2: Call grandma

Removing items from a list while you loop over it is a classic bug in any language, because the positions shift under you. Building a new list avoids it. task.copy() is needed because a Task holds a String and isn’t copied implicitly.

  • A struct with methods keeps a task’s data and its file format together: to_line() and a @staticmethod from_line() that raises on bad input.
  • split("|", maxsplit=2) splits a line into a fixed number of parts and keeps the rest of the text in one piece.
  • match on the command word with case "done" | "remove": and case _: reads like a menu.
  • Raise an Error with a clear message wherever something’s wrong, and catch it once in main.
  • Save with open(path, "w") inside with, load with read() and splitlines(), and check exists(path) first.
  • Change list items with tasks[i] or for ref, never through a plain loop variable.

Next up: Project: Mandelbrot Set, where you draw a famous fractal in the terminal and make it faster with SIMD.

Quick check

1. The text of a task contains a |, like Buy milk | eggs. Why does from_line still read it back correctly?
2. Why does next_id use the biggest id plus one instead of len(tasks) + 1?
3. Which loop lets you set task.done = True on the items of tasks?
4. What does open("todo.txt", "w") do if the file already exists?