The code for save-task-list is shown below. Because this function does not use any DUIM code, it is described only briefly.
define function save-task-list
(task-list :: <task-list>, #key filename)
=> (saved? :: <boolean>)
let filename = filename | task-list-filename(task-list);
with-open-file (stream = filename, direction: #"output")
for (task in task-list.task-list-tasks)
format(stream, "%s\n%s\n",
task.task-name, as(<string>, task.task-priority))
end
end;
task-list.task-list-modified? := #f;
task-list.task-list-filename := filename;
#t
end function save-task-list;
Add this code to task-list.dylan.
The function save-task-list takes an instance of <task-list> as an argument, and optionally a filename. It then attempts to save the instance of <task-list> to the file specified by filename. It returns a boolean value that indicates whether the file was successfully saved or not. If filename is not passed as an argument to save-task-list (in the case where the user has chosen File > Save or clicked the Save button when working with a task list file that has previously been saved), then the task-list-filename slot of the <task-list> is used instead.
Like load-task-list, this function uses the Streams library to save information to a file. For full information about this library, please refer to the I/O and Networks Library Reference. It also uses the format function from the Format library, which is described in the same reference.
The file is opened for saving using the with-open-file macro (just like load-task-list, but in the opposite direction), A for loop is used to save each element in each task to the file. The format function then writes each element to the file, separated by a newline character. Note how the as method is used to convert the task-priority symbol to a string when saving each priority value: this is the reverse situation to load-task-list, where a method for as was used to convert the string to a symbol.
Once every element in the file has been saved, the task-list-modified slot of the <task-list> is reset to #f, and the task-list-filename slot of the <task-list> is set to the filename used by save-task-list. This last step is necessary to allow for the case where the user has chosen the File > Save As command to save the file under a different name.
Finally, save-task-list returns #t to indicate that the file has been successfully saved.