Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,19 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h
* `add todo` and `add event` take `--set-alarm`, either a duration like `10m`, which puts it that long before the DUE of a task (or before its DTSTART if it has none) or before the start of an event (`+10m` is after, as in iCalendar), or a timestamp. A number without a unit, like `15`, is minutes, as in most calendar software. The alarm displays the summary.
* A warning when the singular `--set-category`, `--add-category` or `--add-resource` is given a value with a comma in it, like `--set-category=boat,keyboard`, and when a plural option like `--set-categories` is given more than once with a comma in a value. Both give one category named `boat,keyboard`, while a single `--set-categories=boat,keyboard` gives two. The behaviour itself is unchanged (it is intended), but is now documented in the user guide.
* `plann interactive check-pinned` goes through the past week's events pinning tasks to the calendar (as made by the panic planning in `interactive manage-tasks`) and asks if each task was done. A done task is completed (with its subtasks), and its event is marked as confirmed; its other pins may be cancelled. If not done, the event is cancelled. It is also run first in `interactive manage-tasks`. https://github.com/pycalendar/plann/pull/89
* After the tasks in the plan of `check-for-panic --interactive-fix-timeline` (and `interactive manage-tasks`) are pinned, it offers to plan again, leaving out the tasks just pinned.

### Changed

* The plan that `check-for-panic --interactive-fix-timeline` (and `interactive manage-tasks`) opens in the editor now has a start and a duration per task, like `2026-11-24 10:00 +1h30m`, instead of a start and an end, so editing the start moves the task and keeps its length. All times are in one timezone, named at the top of the file, as are the times printed by `--print-timeline` and the list of tasks that will need to be procrastinated; they used to be in whatever timezone each event was stored in. Existing events are `#` comment lines, and a `#` in a task summary is no longer cut off.
* The `plann interactive` subcommands now have the same defaults as when `interactive manage-tasks` runs them, except `dismiss-panic --hours-per-day`, which `manage-tasks` runs with 24 and then 14. `check-due` looks 24 hours ahead (was 16) and goes through at most 16 tasks (was unlimited); `split-huge-tasks` and `split-high-pri-tasks` look 60 days and 640 tasks ahead (was 30 days and 32 tasks).
* A bare hour (one or two digits, 0-23) in a date or time argument, like `--set-dtstart=14`, means 14:00 today in the implicit timezone. It was taken as the 14th of the month, giving an all-day task. `--set-alarm` is the exception: there a number without a unit is minutes.

### Fixed

* A timestamp with an explicit UTC offset, like `plann select --event --start 2026-11-21T05:00+01:00`, crashed when expanding recurring events with `AttributeError: 'StaticTzInfo' object has no attribute 'normalize'`. https://github.com/niccokunzmann/python-recurring-ical-events/issues/311
* A line that could not be parsed in the plan of `check-for-panic --interactive-fix-timeline` (and `interactive manage-tasks`) crashed with an `AssertionError` and discarded the whole edit. The editor is now reopened with the error at the top.
* `plann select --sort-key DUE` (or any other date property, like `DTSTART`) crashed with `TypeError: '<' not supported between instances of 'vDDDTypes' and 'vDDDTypes'`, and a plain sort key missing on some of the items crashed too. Dates and timestamps now sort together (a date as midnight, a floating time in the implicit timezone), and items without the property come last, also with a reversed `-` sort key. A task with DTSTART and DURATION but no DUE now sorts on the DUE they give. https://github.com/pycalendar/plann/issues/65
* `plann select ... edit --set-dtend=...` on an event crashed with `TypeError: CalendarObjectResource.set_end() got an unexpected keyword argument 'check_dependent'`, so an event could not be given a new end time. It now moves the event, keeping its duration. `--set-dtend` on a task, `--set-due` on an event and either on a journal crashed too; they now give an error saying which one the item has.
* The `plann agenda --help` text now lists two runnable `plann select` commands giving the same events and tasks as `agenda`. In the task one, the `--sort-key '{PRIORITY:?0}'` template had no effect and `list --bottom-up` stood where `select --skip-parents` belongs, and the event one lacked the sort keys. It also pointed to a nonexistent USAGE.md instead of USER_GUIDE.md.
* `plann add -l LINE event` dropped the extra iCalendar lines; they are now added to the event, as they were to tasks and journals.
Expand Down
13 changes: 13 additions & 0 deletions TASK_MANAGEMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -395,3 +395,16 @@ The panic planning will try to figure out if it's still possible to perform all

TODO: write more about the panic planning algorithm.

#### Pinning tasks to the calendar

`plann select --todo check-for-panic --include-all-events --interactive-fix-timeline` (also run by `interactive manage-tasks`, for the next five days) opens the suggested timeline in an editor, one line per task:

```
# All times are in Europe/Oslo (CET = UTC+01:00).
...
2b5c0e1e-... 2026-11-24 10:00 +1h30m Write the report
# 2026-11-24 12:00 +1h Lunch
```

The columns are UID, start, duration and summary. There is no end time, so changing the start moves the task and keeps its length; change the duration to make it shorter or longer. Delete a line to leave a task off the calendar. Lines starting with `#` are existing events, shown for reference. All times are in one timezone, the one named at the top of the file (the `--implicit-timezone`, or else the local one). Each remaining line becomes a tentative event, a child of the task. A line that can't be parsed reopens the editor with the error at the top; delete all the task lines to get out without pinning anything. Afterwards you may plan again: the tasks just pinned are left out of the new suggestion.

2 changes: 1 addition & 1 deletion plann/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ def complete(ctx, **kwargs):
@click.option('--include-all-events/--no-extra-events', help='Include all events (and selected tasks)')
@click.option('--print-timeline/--no-print-timeline', help='Print a possible timeline')
@click.option('--fix-timeline/--no-fix-timeline', help='Make events from the tasks and pin them to the calendar')
@click.option('--interactive-fix-timeline/--no-interactive-fix-timeline', help='Make a suggested editable time table')
@click.option('--interactive-fix-timeline/--no-interactive-fix-timeline', help='Edit the suggested timeline (start and duration per task) and pin the tasks to the calendar')
@click.pass_context
def check_for_panic(ctx, **kwargs):
"""Check if we need to panic
Expand Down
125 changes: 84 additions & 41 deletions plann/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import click
import icalendar
from caldav.lib.error import ETagMismatchError, NotFoundError, PutError, ScheduleTagMismatchError
from dateutil import tz as dateutil_tz
from icalendar_searcher import Searcher

from plann.interactive import (
Expand All @@ -22,7 +23,6 @@
_mass_interactive_edit,
_mass_reprioritize,
_pdb_edit,
_strip_line,
interactive_split_task,
)
from plann.lib import (
Expand All @@ -45,7 +45,7 @@
childlike,
parentlike,
)
from plann.panic_planning import timeline_suggestion
from plann.panic_planning import format_pin_plan, parse_pin_plan, timeline_suggestion
from plann.template import Template
from plann.timespec import DURATION_RE, _ensure_ts, _now, parse_add_dur, parse_dt, parse_timespec, tz

Expand Down Expand Up @@ -81,7 +81,12 @@ def _sort_key_function(skey):
A leading ``-`` reverses the sort. A spec containing ``{`` is treated as
a template and compiled once here - not rebuilt on every comparison during
the sort (code review E2). ``get_duration()`` is special-cased; any other
spec is a plain icalendar component property name.
spec is a plain icalendar component property name; its dates and
timestamps are compared as timezone-aware timestamps (a date is
midnight, a floating time is in the implicit timezone), and items
without the property come last, also in a reversed sort (issue #65).
DTSTART, DUE, DTEND and DURATION are taken from the icalendar helper
properties, so a missing one is computed from the others if it can be.
"""
reverse = skey.startswith('-')
if reverse:
Expand All @@ -95,9 +100,38 @@ def fkey(obj):
return obj.get_duration()
else:
def fkey(obj):
return obj.icalendar_component.get(skey)
value = _sort_value(obj.icalendar_component, skey)
if value is None:
## sorts after every present value, whichever the direction
return (not reverse, 0)
if isinstance(value, datetime.date):
value = _ensure_ts(value)
return (reverse, value)
return reverse, fkey

## (component name, property) -> the icalendar helper property computing it,
## e.g. the DUE of a task with DTSTART and DURATION but no DUE line
_SORT_HELPERS = {
('VTODO', 'DTSTART'): 'start',
('VTODO', 'DUE'): 'end',
('VTODO', 'DURATION'): 'duration',
('VEVENT', 'DTSTART'): 'start',
('VEVENT', 'DTEND'): 'end',
('VEVENT', 'DURATION'): 'duration',
}

def _sort_value(comp, skey):
"""The decoded value of property ``skey`` of ``comp`` to sort on, or
None if it has none."""
helper = _SORT_HELPERS.get((comp.name, skey.upper()))
if helper:
try:
return getattr(comp, helper)
except (icalendar.IncompleteComponent, icalendar.InvalidCalendar):
pass
value = comp.get(skey)
return getattr(value, 'dt', value)

def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=None, warn_on_missing_uid=True, sort_key=[], skip_parents=None, skip_children=None, limit=None, offset=None, freebusyhack=None, pinned_tasks=None, **kwargs_):
"""
select/search/filter tasks/events, for listing/editing/deleting, etc
Expand Down Expand Up @@ -362,6 +396,39 @@ def _edit(ctx, cancel=None, interactive_ical=False, interactive_relations=False,
## OPTIMIZE TODO: only save objects that actually have been edited
obj.save()

def _display_timezone():
return tz.implicit_timezone or dateutil_tz.tzlocal()

def _timeline_entries(possible_timeline, timeline_start):
"""(uid, begin, end, summary) for the future items of the timeline,
uid is None for things that are already events"""
ret = []
for (foo, next) in zip(possible_timeline, possible_timeline[1:]):
if 'begin' in foo and 'obj' in foo and not isinstance(foo['obj'], str):
if _ensure_ts(foo['begin'])>timeline_start:
obj = foo['obj']
uid = str(obj.icalendar_component['UID']) if isinstance(obj, caldav.Todo) else None
ret.append((uid, foo['begin'], next['begin'], _summary(obj)))
return ret

def _interactive_fix_timeline(ctx, possible_timeline, timeline_start):
"""Lets the user edit the suggested plan and pins the tasks in it to
the calendar. Returns the number of events added."""
tzinfo = _display_timezone()
text = format_pin_plan(_timeline_entries(possible_timeline, timeline_start), tzinfo)
while True:
text = _editor(text)
try:
plan = parse_pin_plan(text, tzinfo)
break
except ValueError as e:
text = "\n".join([f"# ERROR: {e}"] + [x for x in text.split("\n") if not x.startswith("# ERROR: ")])
for (uid, begin, end, summary) in plan:
event = _add_event(ctx, summary=summary, timespec=(begin, end), set_status='TENTATIVE', first_calendar=True, set_parent=[uid])
## so a new plan won't suggest the task again
ctx.obj['objs'].append(event)
return len(plan)

def _check_for_panic(ctx, hours_per_day, output=True, print_timeline=True, fix_timeline=False, interactive_fix_timeline=False, timeline_start=None, timeline_end=None, include_all_events=False):
if not timeline_start:
timeline_start = _now()
Expand All @@ -384,54 +451,30 @@ def summary(obj):
return _summary(obj)

if (print_timeline):
tzinfo = _display_timezone()
click.echo("Calculated timeline suggestion:")
for foo in possible_timeline:
if 'begin' in foo:
click.echo(f"{foo['begin']:%FT%H:%M %Z} {summary(foo.get('obj'))}")
click.echo(f"{foo['begin'].astimezone(tzinfo):%FT%H:%M %Z} {summary(foo.get('obj'))}")

if output:
click.echo()
click.echo("THESE TASKS WILL NEED TO BE PROCRASTINATED:")
for foo in possible_timeline:
if 'begin' in foo and 'obj' in foo and not isinstance(foo['obj'], str):
if _ensure_ts(foo['begin'])<timeline_start:
click.echo(f"{foo['obj'].get_due():%FT%H%M %Z} {foo['obj'].icalendar_component.get('PRIORITY', 0)} {_summary(foo['obj'])}")

if fix_timeline or interactive_fix_timeline:
output = [] ## for interactive
for i in range(len(possible_timeline)-1):
foo = possible_timeline[i]
next = possible_timeline[i+1]
if 'begin' in foo and 'obj' in foo and not isinstance(foo['obj'], str):
if _ensure_ts(foo['begin'])>timeline_start:
obj = foo['obj']
if isinstance(obj, caldav.Todo):
comp = obj.icalendar_component
if fix_timeline:
## TODO: copy other attributes?
_add_event(ctx, summary=_summary(obj), timespec=(foo['begin'], next['begin']), set_status='TENTATIVE', first_calendar=True, set_parent=[comp['UID']])
elif interactive_fix_timeline:
output.append(f"{comp['UID']:37} {foo['begin']} - {next['begin']}: {_summary(obj)}")
elif interactive_fix_timeline:
output.append(f"{' '*37} {foo['begin']} - {next['begin']}: {_summary(obj)}")
due = _ensure_ts(foo['obj'].get_due()).astimezone(_display_timezone())
click.echo(f"{due:%FT%H%M %Z} {foo['obj'].icalendar_component.get('PRIORITY', 0)} {_summary(foo['obj'])}")

if fix_timeline:
for (uid, begin, end, summary) in _timeline_entries(possible_timeline, timeline_start):
if uid:
## TODO: copy other attributes?
_add_event(ctx, summary=summary, timespec=(begin, end), set_status='TENTATIVE', first_calendar=True, set_parent=[uid])
if interactive_fix_timeline:
pinned_re = re.compile("^(.+?) +(.+?) - (.+?): (.+)$")
fixed_timeline = _editor("""\
# Lines not starting with UID are already events and cannot be changed as for now
# Delete things you don't want on the calendar
# You may also change the suggested times and even the summary
# There are no collision control if you change the suggested times
""" + "\n".join(output))
for line in fixed_timeline.split('\n'):
if line.startswith(' '*16):
continue
line = _strip_line(line)
if not line:
continue
parsed = pinned_re.match(line)
assert parsed ## TODO: print a friendly error message and probably even continue execution
(uid, begin, end, summary) = parsed.groups()
_add_event(ctx, summary=summary, timespec=f"{begin} {end}", set_status='TENTATIVE', first_calendar=True, set_parent=[uid])
while (_interactive_fix_timeline(ctx, possible_timeline, timeline_start) and
click.confirm("Plan again, with the events just added?", default=False)):
possible_timeline = timeline_suggestion(ctx, hours_per_day=hours_per_day, timeline_end=timeline_end)

return possible_timeline

Expand Down
Loading
Loading