system

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 16, 2025 License: Apache-2.0, Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package system provides utilities for message formatting and code highlighting.

Index

Constants

This section is empty.

Variables

View Source
var HighlightCode = func(language string, code string) (string, error) {

	lexer := lexers.Get(language)
	if lexer == nil {
		lexer = lexers.Analyse(code)
		if lexer == nil {
			lexer = lexers.Fallback
		}
	}

	style := styles.Get("monokai")
	if style == nil {
		style = styles.Fallback
	}

	formatter := formatters.Get("terminal256")
	if formatter == nil {
		formatter = formatters.Fallback
	}

	iterator, err := lexer.Tokenise(nil, code)
	if err != nil {
		return "", fmt.Errorf("error tokenizing code: %w", err)
	}

	// Format the code into a string buffer
	var buf bytes.Buffer
	err = formatter.Format(&buf, style, iterator)
	if err != nil {
		return "", fmt.Errorf("error formatting code: %w", err)
	}

	return buf.String(), nil
}
View Source
var TmuxCapturePane = func(paneId string, maxLines int) (string, error) {
	cmd := exec.Command("tmux", "capture-pane", "-p", "-t", paneId, "-S", fmt.Sprintf("-%d", maxLines))
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	err := cmd.Run()
	if err != nil {
		logger.Error("Failed to capture pane content from %s: %v, stderr: %s", paneId, err, stderr.String())
		return "", err
	}

	content := strings.TrimSpace(stdout.String())
	return content, nil
}

TmuxCapturePane gets the content of a specific pane by ID

View Source
var TmuxCurrentPaneId = func() (string, error) {
	tmuxPane := os.Getenv("TMUX_PANE")
	if tmuxPane == "" {
		return "", fmt.Errorf("TMUX_PANE environment variable not set")
	}

	return tmuxPane, nil
}
View Source
var TmuxPanesDetails = func(target string) ([]TmuxPaneDetails, error) {
	cmd := exec.Command("tmux", "list-panes", "-t", target, "-F", "#{pane_id},#{pane_active},#{pane_pid},#{pane_current_command},#{history_size},#{history_limit}")
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	err := cmd.Run()
	if err != nil {
		logger.Error("Failed to get tmux pane details for target %s %v, stderr: %s", target, err, stderr.String())
		return nil, err
	}

	output := strings.TrimSpace(stdout.String())
	if output == "" {
		return nil, fmt.Errorf("no pane details found for target %s", target)
	}

	lines := strings.Split(output, "\n")
	paneDetails := make([]TmuxPaneDetails, 0, len(lines))

	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}

		parts := strings.SplitN(line, ",", 6)
		if len(parts) < 5 {
			logger.Error("Invalid pane details format for line: %s", line)
			continue
		}

		id := parts[0]

		if strings.HasPrefix(target, "%") && id != target {
			continue
		}

		active, _ := strconv.Atoi(parts[1])
		pid, _ := strconv.Atoi(parts[2])
		historySize, _ := strconv.Atoi(parts[4])
		historyLimit, _ := strconv.Atoi(parts[5])
		currentCommandArgs := GetProcessArgs(pid)
		isSubShell := IsSubShell(parts[3])

		paneDetail := TmuxPaneDetails{
			Id:                 id,
			IsActive:           active,
			CurrentPid:         pid,
			CurrentCommand:     parts[3],
			CurrentCommandArgs: currentCommandArgs,
			HistorySize:        historySize,
			HistoryLimit:       historyLimit,
			IsSubShell:         isSubShell,
		}

		paneDetails = append(paneDetails, paneDetail)
	}

	return paneDetails, nil
}

TmuxPanesDetails gets details for all panes in a target window

View Source
var TmuxSendCommandToPane = func(paneId string, command string, autoenter bool) error {
	lines := strings.Split(command, "\n")
	for i, line := range lines {

		if line != "" {
			if !containsSpecialKey(line) {

				if strings.HasSuffix(line, ";") {
					line = line[:len(line)-1] + "\\;"
				}
				cmd := exec.Command("tmux", "send-keys", "-t", paneId, "-l", line)
				var stderr bytes.Buffer
				cmd.Stderr = &stderr
				err := cmd.Run()
				if err != nil {
					logger.Error("Failed to send command to pane %s: %v, stderr: %s", paneId, err, stderr.String())
					return fmt.Errorf("failed to send command to pane: %w", err)
				}

			} else {
				args := []string{"send-keys", "-t", paneId}
				processed := processLineWithSpecialKeys(line)
				args = append(args, processed...)
				cmd := exec.Command("tmux", args...)
				var stderr bytes.Buffer
				cmd.Stderr = &stderr
				err := cmd.Run()
				if err != nil {
					logger.Error("Failed to send command with special keys to pane %s: %v, stderr: %s", paneId, err, stderr.String())
					return fmt.Errorf("failed to send command with special keys to pane: %w", err)
				}
			}
		}

		if autoenter {
			if i < len(lines)-1 || (i == len(lines)-1 && line != "") {
				enterCmd := exec.Command("tmux", "send-keys", "-t", paneId, "Enter")
				err := enterCmd.Run()
				if err != nil {
					logger.Error("Failed to send Enter key to pane %s: %v", paneId, err)
					return fmt.Errorf("failed to send Enter key to pane: %w", err)
				}
			}
		}
	}
	return nil
}

Functions

func Cosmetics

func Cosmetics(message string) string

Cosmetics processes a message string, applying terminal formatting to markdown code blocks (triple backticks, optionally with language) and inline code (single backticks). - Code blocks are highlighted using HighlightCode. - Inline code is rendered with a gray background and yellow text (ANSI codes). All other text is left as-is.

func EstimateTokenCount

func EstimateTokenCount(text string) int

EstimateTokenCount provides a rough estimation of token count for LLM context This is an approximation and not exact for all models

func GetOSDetails

func GetOSDetails() string

func GetProcessArgs

func GetProcessArgs(pid int) string

func IsShellCommand

func IsShellCommand(command string) bool

IsShellCommand checks if the given command is a shell

func IsSubShell

func IsSubShell(command string) bool

func PrintMapAsYAML

func PrintMapAsYAML(m map[string]interface{}, indent int)

printMapAsYAML prints a map[string]interface{} as YAML-like output with sorted keys

func SetMapValueByDotKey

func SetMapValueByDotKey(m map[string]interface{}, key string, value interface{})

setMapValueByDotKey sets a value in a map using dot notation keys

func StructToMap

func StructToMap(s interface{}, prefix string) map[string]interface{}

structToMap flattens a struct to a map[string]interface{} recursively

func TmuxAttachSession

func TmuxAttachSession(paneId string) error

AttachToTmuxSession attaches to an existing tmux session

func TmuxClearPane

func TmuxClearPane(paneId string) error

func TmuxCreateNewPane

func TmuxCreateNewPane(target string) (string, error)

TmuxCreateNewPane creates a new horizontal split pane in the specified window and returns its ID

func TmuxCreateSession

func TmuxCreateSession() (string, error)

CreateTmuxSession creates a new tmux session and returns the new pane id

func TmuxCurrentWindowTarget

func TmuxCurrentWindowTarget() (string, error)

Return current tmux window target with session id and window id

Types

type InfoFormatter

type InfoFormatter struct {
	// Color schemes
	HeaderColor  *color.Color
	LabelColor   *color.Color
	SuccessColor *color.Color
	WarningColor *color.Color
	ErrorColor   *color.Color
	NeutralColor *color.Color
}

InfoFormatter provides consistent formatting for TmuxAI information displays

func NewInfoFormatter

func NewInfoFormatter() *InfoFormatter

NewInfoFormatter creates a new formatter with default color schemes

func (*InfoFormatter) FormatBool

func (f *InfoFormatter) FormatBool(value bool) string

FormatBool formats boolean values with color

func (*InfoFormatter) FormatKeyValue

func (f *InfoFormatter) FormatKeyValue(key string, value interface{}) string

FormatKeyValue prints a key-value pair with consistent formatting

func (*InfoFormatter) FormatProgressBar

func (f *InfoFormatter) FormatProgressBar(percent float64, width int) string

FormatProgressBar generates a visual indicator for percentage values

func (*InfoFormatter) FormatSection

func (f *InfoFormatter) FormatSection(title string) string

FormatSection prints a section header

type TmuxPaneDetails

type TmuxPaneDetails struct {
	Id                 string
	CurrentPid         int
	CurrentCommand     string
	CurrentCommandArgs string
	Content            string
	Shell              string
	OS                 string
	LastLine           string
	IsActive           int
	IsTmuxAiPane       bool
	IsTmuxAiExecPane   bool
	IsPrepared         bool
	IsSubShell         bool
	HistorySize        int
	HistoryLimit       int
}

func (*TmuxPaneDetails) FormatInfo

func (p *TmuxPaneDetails) FormatInfo(f *InfoFormatter) string

func (*TmuxPaneDetails) Refresh

func (p *TmuxPaneDetails) Refresh(maxLines int)

func (*TmuxPaneDetails) String

func (p *TmuxPaneDetails) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL