pre-refactor

This commit is contained in:
Rasmus Wejlgaard 2025-11-07 21:37:34 +00:00
commit 6b88066b20
5 changed files with 1927 additions and 0 deletions

29
go.mod Normal file
View file

@ -0,0 +1,29 @@
module github.com/rwejlgaard/org
go 1.25.3
require (
github.com/alecthomas/chroma/v2 v2.20.0 // indirect
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/bubbles v0.21.0 // indirect
github.com/charmbracelet/bubbletea v1.3.10 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
github.com/charmbracelet/lipgloss v1.1.0 // indirect
github.com/charmbracelet/x/ansi v0.10.1 // indirect
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/dlclark/regexp2 v1.11.5 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sys v0.36.0 // indirect
golang.org/x/text v0.3.8 // indirect
)

49
go.sum Normal file
View file

@ -0,0 +1,49 @@
github.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NTz+9sGw=
github.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=
github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=

49
main.go Normal file
View file

@ -0,0 +1,49 @@
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
)
func main() {
var filePath string
flag.StringVar(&filePath, "file", "", "Path to org file (default: ./todo.org)")
flag.StringVar(&filePath, "f", "", "Path to org file (shorthand)")
flag.Parse()
// Check for positional argument first
if filePath == "" && len(flag.Args()) > 0 {
filePath = flag.Args()[0]
}
// Default to ./todo.org if no file specified
if filePath == "" {
cwd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting current directory: %v\n", err)
os.Exit(1)
}
filePath = filepath.Join(cwd, "todo.org")
}
// Parse the org file
orgFile, err := ParseOrgFile(filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing org file: %v\n", err)
os.Exit(1)
}
// Run the UI
if err := runUI(orgFile); err != nil {
fmt.Fprintf(os.Stderr, "Error running UI: %v\n", err)
os.Exit(1)
}
// Save on exit
if err := orgFile.Save(); err != nil {
fmt.Fprintf(os.Stderr, "Error saving file: %v\n", err)
os.Exit(1)
}
}

443
org.go Normal file
View file

@ -0,0 +1,443 @@
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
"time"
)
// TodoState represents the state of a todo item
type TodoState string
const (
StateTODO TodoState = "TODO"
StatePROG TodoState = "PROG"
StateBLOCK TodoState = "BLOCK"
StateDONE TodoState = "DONE"
StateNone TodoState = ""
)
// ClockEntry represents a single clock entry
type ClockEntry struct {
Start time.Time
End *time.Time // nil if currently clocked in
}
// Item represents a single org-mode item (heading)
type Item struct {
Level int // Heading level (number of *)
State TodoState // TODO, PROG, BLOCK, DONE, or empty
Title string // The main title text
Scheduled *time.Time
Deadline *time.Time
Notes []string // Notes/content under the heading
Children []*Item // Sub-items
Folded bool // Whether the item is folded (hides notes and children)
ClockEntries []ClockEntry // Clock in/out entries
}
// OrgFile represents a parsed org-mode file
type OrgFile struct {
Path string
Items []*Item
}
// Parser patterns
var (
headingPattern = regexp.MustCompile(`^(\*+)\s+(?:(TODO|PROG|BLOCK|DONE)\s+)?(.+)$`)
scheduledPattern = regexp.MustCompile(`SCHEDULED:\s*<([^>]+)>`)
deadlinePattern = regexp.MustCompile(`DEADLINE:\s*<([^>]+)>`)
clockPattern = regexp.MustCompile(`CLOCK:\s*\[([^\]]+)\](?:--\[([^\]]+)\])?`)
drawerStart = regexp.MustCompile(`^\s*:LOGBOOK:\s*$`)
drawerEnd = regexp.MustCompile(`^\s*:END:\s*$`)
codeBlockStart = regexp.MustCompile(`^\s*#\+BEGIN_SRC`)
codeBlockEnd = regexp.MustCompile(`^\s*#\+END_SRC`)
)
// ParseOrgFile reads and parses an org-mode file
func ParseOrgFile(path string) (*OrgFile, error) {
file, err := os.Open(path)
if err != nil {
// If file doesn't exist, return empty org file
if os.IsNotExist(err) {
return &OrgFile{Path: path, Items: []*Item{}}, nil
}
return nil, err
}
defer file.Close()
orgFile := &OrgFile{Path: path, Items: []*Item{}}
scanner := bufio.NewScanner(file)
var currentItem *Item
var itemStack []*Item // Stack to track parent items
var inCodeBlock bool
var inLogbookDrawer bool
for scanner.Scan() {
line := scanner.Text()
// Check for drawer boundaries
if drawerStart.MatchString(line) {
inLogbookDrawer = true
if currentItem != nil {
currentItem.Notes = append(currentItem.Notes, line)
}
continue
}
if drawerEnd.MatchString(line) && inLogbookDrawer {
inLogbookDrawer = false
if currentItem != nil {
currentItem.Notes = append(currentItem.Notes, line)
}
continue
}
// Check for code block boundaries
if codeBlockStart.MatchString(line) {
inCodeBlock = true
if currentItem != nil {
currentItem.Notes = append(currentItem.Notes, line)
}
continue
}
if codeBlockEnd.MatchString(line) {
inCodeBlock = false
if currentItem != nil {
currentItem.Notes = append(currentItem.Notes, line)
}
continue
}
// If in code block, add line to notes
if inCodeBlock {
if currentItem != nil {
currentItem.Notes = append(currentItem.Notes, line)
}
continue
}
// Try to match heading
if matches := headingPattern.FindStringSubmatch(line); matches != nil {
level := len(matches[1])
state := TodoState(matches[2])
title := matches[3]
item := &Item{
Level: level,
State: state,
Title: title,
Notes: []string{},
Children: []*Item{},
}
// Find parent based on level
for len(itemStack) > 0 && itemStack[len(itemStack)-1].Level >= level {
itemStack = itemStack[:len(itemStack)-1]
}
if len(itemStack) == 0 {
// Top-level item
orgFile.Items = append(orgFile.Items, item)
} else {
// Child item
parent := itemStack[len(itemStack)-1]
parent.Children = append(parent.Children, item)
}
itemStack = append(itemStack, item)
currentItem = item
} else if currentItem != nil {
// This is content under the current item
trimmed := strings.TrimSpace(line)
// Check for SCHEDULED
if matches := scheduledPattern.FindStringSubmatch(line); matches != nil {
if t, err := parseOrgDate(matches[1]); err == nil {
currentItem.Scheduled = &t
}
}
// Check for DEADLINE
if matches := deadlinePattern.FindStringSubmatch(line); matches != nil {
if t, err := parseOrgDate(matches[1]); err == nil {
currentItem.Deadline = &t
}
}
// Check for CLOCK (can be inside or outside drawer)
if matches := clockPattern.FindStringSubmatch(line); matches != nil {
if startTime, err := parseClockTimestamp(matches[1]); err == nil {
entry := ClockEntry{Start: startTime}
if len(matches) > 2 && matches[2] != "" {
if endTime, err := parseClockTimestamp(matches[2]); err == nil {
entry.End = &endTime
}
}
currentItem.ClockEntries = append(currentItem.ClockEntries, entry)
}
}
// Add all lines as notes (including scheduling lines and drawer content for proper serialization)
if trimmed != "" || len(currentItem.Notes) > 0 {
currentItem.Notes = append(currentItem.Notes, line)
}
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return orgFile, nil
}
// parseOrgDate parses org-mode date format
func parseOrgDate(dateStr string) (time.Time, error) {
// Org-mode format: 2024-01-15 Mon 10:00
formats := []string{
"2006-01-02 Mon 15:04",
"2006-01-02 Mon",
"2006-01-02",
}
for _, format := range formats {
if t, err := time.Parse(format, dateStr); err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("unable to parse date: %s", dateStr)
}
// parseClockTimestamp parses org-mode clock timestamp format
func parseClockTimestamp(timestampStr string) (time.Time, error) {
// Org-mode clock format: [2024-01-15 Mon 10:00]
formats := []string{
"2006-01-02 Mon 15:04",
"2006-01-02 Mon 15:04:05",
}
for _, format := range formats {
if t, err := time.Parse(format, timestampStr); err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("unable to parse clock timestamp: %s", timestampStr)
}
// formatClockTimestamp formats a time as org-mode clock timestamp
func formatClockTimestamp(t time.Time) string {
return t.Format("2006-01-02 Mon 15:04")
}
// formatOrgDate formats a time as org-mode date
func formatOrgDate(t time.Time) string {
return t.Format("2006-01-02 Mon")
}
// Save writes the org file back to disk
func (of *OrgFile) Save() error {
file, err := os.Create(of.Path)
if err != nil {
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
defer writer.Flush()
for _, item := range of.Items {
if err := writeItem(writer, item); err != nil {
return err
}
}
return nil
}
// writeItem recursively writes an item and its children
func writeItem(writer *bufio.Writer, item *Item) error {
// Write heading
stars := strings.Repeat("*", item.Level)
line := stars
if item.State != StateNone {
line += " " + string(item.State)
}
line += " " + item.Title + "\n"
if _, err := writer.WriteString(line); err != nil {
return err
}
// Write scheduling info if not already in notes
hasScheduled := false
hasDeadline := false
hasLogbook := false
for _, note := range item.Notes {
if strings.Contains(note, "SCHEDULED:") {
hasScheduled = true
}
if strings.Contains(note, "DEADLINE:") {
hasDeadline = true
}
if strings.Contains(note, ":LOGBOOK:") {
hasLogbook = true
}
}
if item.Scheduled != nil && !hasScheduled {
scheduledLine := fmt.Sprintf("SCHEDULED: <%s>\n", formatOrgDate(*item.Scheduled))
if _, err := writer.WriteString(scheduledLine); err != nil {
return err
}
}
if item.Deadline != nil && !hasDeadline {
deadlineLine := fmt.Sprintf("DEADLINE: <%s>\n", formatOrgDate(*item.Deadline))
if _, err := writer.WriteString(deadlineLine); err != nil {
return err
}
}
// Write clock entries in :LOGBOOK: drawer if not already in notes
if len(item.ClockEntries) > 0 && !hasLogbook {
if _, err := writer.WriteString(":LOGBOOK:\n"); err != nil {
return err
}
for _, entry := range item.ClockEntries {
clockLine := fmt.Sprintf("CLOCK: [%s]", formatClockTimestamp(entry.Start))
if entry.End != nil {
clockLine += fmt.Sprintf("--[%s]", formatClockTimestamp(*entry.End))
}
clockLine += "\n"
if _, err := writer.WriteString(clockLine); err != nil {
return err
}
}
if _, err := writer.WriteString(":END:\n"); err != nil {
return err
}
}
// Write notes
for _, note := range item.Notes {
if _, err := writer.WriteString(note + "\n"); err != nil {
return err
}
}
// Write children
for _, child := range item.Children {
if err := writeItem(writer, child); err != nil {
return err
}
}
return nil
}
// GetAllItems returns a flattened list of all items (for UI display)
// Respects folding - folded items don't show their children
func (of *OrgFile) GetAllItems() []*Item {
var items []*Item
var flatten func([]*Item)
flatten = func(list []*Item) {
for _, item := range list {
items = append(items, item)
if !item.Folded {
flatten(item.Children)
}
}
}
flatten(of.Items)
return items
}
// ToggleFold toggles the folded state of an item
func (item *Item) ToggleFold() {
item.Folded = !item.Folded
}
// CycleState cycles through todo states
func (item *Item) CycleState() {
switch item.State {
case StateNone:
item.State = StateTODO
case StateTODO:
item.State = StatePROG
case StatePROG:
item.State = StateBLOCK
case StateBLOCK:
item.State = StateDONE
case StateDONE:
item.State = StateNone
}
}
// ClockIn starts a new clock entry
func (item *Item) ClockIn() bool {
// Check if already clocked in
if item.IsClockedIn() {
return false
}
entry := ClockEntry{
Start: time.Now(),
End: nil,
}
item.ClockEntries = append(item.ClockEntries, entry)
return true
}
// ClockOut ends the current clock entry
func (item *Item) ClockOut() bool {
// Find the most recent open clock entry
for i := len(item.ClockEntries) - 1; i >= 0; i-- {
if item.ClockEntries[i].End == nil {
now := time.Now()
item.ClockEntries[i].End = &now
return true
}
}
return false
}
// IsClockedIn returns true if there's an active clock entry
func (item *Item) IsClockedIn() bool {
for _, entry := range item.ClockEntries {
if entry.End == nil {
return true
}
}
return false
}
// GetCurrentClockDuration returns the duration of the current clock entry
func (item *Item) GetCurrentClockDuration() time.Duration {
for _, entry := range item.ClockEntries {
if entry.End == nil {
return time.Since(entry.Start)
}
}
return 0
}
// GetTotalClockDuration returns the total duration of all clock entries
func (item *Item) GetTotalClockDuration() time.Duration {
var total time.Duration
for _, entry := range item.ClockEntries {
if entry.End != nil {
// Completed clock entry
total += entry.End.Sub(entry.Start)
} else {
// Currently clocked in
total += time.Since(entry.Start)
}
}
return total
}

1357
ui.go Normal file

File diff suppressed because it is too large Load diff