Thanks to visit codestin.com
Credit goes to github.com

Skip to content

maorun/code-stats.nvim

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

51 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Code::Stats integration in lua

Homepage of Code::Stats (The free stats tracking service for programmers)

Installation

eg: vim-plug

Plug 'nvim-lua/plenary.nvim'
Plug('maorun/code-stats.nvim')

Usage

you must set the api-key either trough the setup or as an global variable

in vim:

let g:codestats_api_key = '<YOUR_KEY>'

or lua:

vim.g.codestats_api_key = '<YOUR_KEY>'

now setup the plugin

require('maorun.code-stats').setup({
    api_key = '<YOUR_API_KEY>', -- not necessary if global api key is set
    status_prefix = 'C:S ', -- the prefix of xp in statusline
    enhanced_statusline = false, -- Show XP, level and progress in statusline
    statusline_format = "%s%d (%d%% to L%d)", -- Format for enhanced statusline
    ignored_filetypes = {'markdown', 'text'}, -- filetypes to ignore from XP tracking
    logging = {
        enabled = false, -- Set to true to enable logging
        level = 'INFO', -- Log level: ERROR, WARN, INFO, DEBUG
        file_path = nil -- Optional custom log file path (defaults to vim data dir)
    },
    performance = {
        typing_debounce_ms = 500, -- Debounce time for TextChangedI events (ms)
        xp_batch_delay_ms = 100, -- Batch delay for XP processing (ms)
        cache_timeout_s = 1, -- Language detection cache timeout (seconds)
    }
})

Statusline

with require('maorun.code-stats').currentXp() you can get the current xp of the buffer

vim.opt.statusline=vim.opt.statusline + "%{luaeval(\"require('maorun.code-stats').currentXp()\")} "

Enhanced Statusline

You can enable an enhanced statusline that shows XP, level, and progress to the next level:

require('maorun.code-stats').setup({
    api_key = '<YOUR_API_KEY>',
    enhanced_statusline = true,  -- Enable enhanced display
    statusline_format = "%s%d (%d%% to L%d)"  -- Optional: customize format
})

The enhanced statusline displays:

  • Current XP for the active language
  • Current level (calculated from XP)
  • Progress percentage to the next level
  • Next level number

Format placeholders:

  • %s - Status prefix (default: "C:S ")
  • First %d - Current XP
  • Second %d - Progress percentage (0-100)
  • Third %d - Next level number

Example output: C:S 250 (25% to L3) (250 XP, 25% progress to level 3)

You can also use the enhanced function directly:

vim.opt.statusline=vim.opt.statusline + "%{luaeval(\"require('maorun.code-stats').currentXpEnhanced()\")} "

Level Calculation: Levels are calculated using the formula Level = floor(sqrt(XP / 100)) + 1, where each level requires progressively more XP.

User Commands

The plugin provides several user commands to access XP information:

:CodeStatsXP

Shows XP for the currently detected language at cursor position.

:CodeStatsAll

Shows XP for all tracked languages, sorted by XP amount (highest first).

:CodeStatsLang <language>

Shows XP for a specific language. Supports tab completion with tracked languages.

:CodeStatsXpSend

Manually send all pending XP to Code::Stats immediately. This command provides:

  • Immediate transmission of all tracked XP data
  • Success confirmation when XP is sent successfully
  • Error messages if transmission fails (network issues, invalid API key, etc.)

:CodeStatsProfile

Displays your Code::Stats profile information from the server, including:

  • Username
  • Total XP across all languages
  • Current level
  • Top languages with XP amounts
  • Error messages if retrieval fails (network issues, invalid API key, etc.)

:CodeStatsLog [action]

Manage logging functionality:

  • :CodeStatsLog status - Show current logging status and log file location
  • :CodeStatsLog path - Show log file path
  • :CodeStatsLog clear - Clear the log file

:CodeStatsDaily [YYYY-MM-DD]

Show daily XP statistics for a specific date or today if no date provided:

  • Displays total XP and level for the day
  • Shows XP breakdown by programming language
  • Useful for tracking daily coding productivity

:CodeStatsWeekly [YYYY-MM-DD]

Show weekly XP statistics for the week containing the specified date or current week:

  • Displays total XP and level for the week (Monday to Sunday)
  • Shows XP breakdown by programming language
  • Helps identify weekly coding patterns

:CodeStatsMonthly [YYYY-MM]

Show monthly XP statistics for a specific month or current month:

  • Displays total XP and level for the month
  • Shows XP breakdown by programming language
  • Great for monthly progress reviews

Example usage:

:CodeStatsXP                " Show current language XP
:CodeStatsAll               " Show all languages with XP
:CodeStatsLang lua          " Show XP for Lua specifically
:CodeStatsXpSend            " Send all pending XP immediately
:CodeStatsProfile           " Show your Code::Stats profile from server
:CodeStatsLog status        " Show logging status
:CodeStatsDaily             " Show today's XP statistics
:CodeStatsDaily 2024-08-15  " Show XP for specific date
:CodeStatsWeekly            " Show current week's XP statistics
:CodeStatsMonthly           " Show current month's XP statistics
:CodeStatsMonthly 2024-07   " Show XP for July 2024

Personal Statistics

The plugin now includes comprehensive personal statistics tracking that allows you to view your coding activity over time. This feature automatically tracks XP with timestamps and provides insights into your daily, weekly, and monthly coding patterns.

Features

  • Historical Tracking: All XP gains are automatically recorded with timestamps for historical analysis
  • Time-based Analytics: View statistics by day, week, or month
  • Language Breakdown: See which programming languages you've been using most
  • Level Progression: Track level advancement over time
  • Data Retention: Historical data is kept for 90 days to prevent excessive storage growth
  • Backward Compatibility: Existing XP tracking continues to work unchanged

How It Works

The statistics system works alongside the existing XP tracking:

  1. Automatic Recording: Every time you gain XP, the plugin automatically records the timestamp and language
  2. Separate Storage: Historical data is stored in a separate file (code-stats-history.json) to maintain compatibility
  3. Aggregated Views: Statistics commands aggregate historical data to show totals by time period
  4. Level Calculations: Uses the same level formula as the main XP system (Level = floor(sqrt(XP / 100)) + 1)

Use Cases

  • Daily Reviews: Check how productive your coding day was
  • Weekly Planning: Identify which days of the week you're most productive
  • Monthly Reports: Track progress toward coding goals
  • Language Analysis: Discover which languages you're spending most time on
  • Motivation: See your coding consistency and improvement over time

Ignoring File Types

You can exclude specific file types from XP tracking by specifying them in the ignored_filetypes configuration option:

require('maorun.code-stats').setup({
    api_key = '<YOUR_API_KEY>',
    ignored_filetypes = {
        'markdown',    -- Don't track XP for markdown files
        'text',        -- Don't track XP for text files  
        'gitcommit',   -- Don't track XP for git commit messages
        'log'          -- Don't track XP for log files
    }
})

Changes to the ignored file types take effect immediately without requiring a restart of the editor.

Logging and Error Handling

The plugin includes comprehensive logging and error handling features to help track plugin activity and diagnose issues.

Enabling Logging

To enable logging, configure the plugin with logging options:

require('maorun.code-stats').setup({
    api_key = '<YOUR_API_KEY>',
    logging = {
        enabled = true,           -- Enable logging
        level = 'INFO',          -- Log level: ERROR, WARN, INFO, DEBUG
        file_path = nil          -- Optional: custom log file path
    }
})

Log Levels

  • ERROR: Critical errors that prevent functionality
  • WARN: Warning messages for non-critical issues
  • INFO: General information about plugin operations
  • DEBUG: Detailed debugging information

Log File Location

By default, the log file is stored at {vim.fn.stdpath("data")}/code-stats.log. You can specify a custom location using the file_path option.

Performance Optimization

The plugin is optimized for minimal performance impact during typing. Key optimizations include:

Event Optimization

  • No per-character tracking: XP is tracked on InsertLeave (when exiting insert mode) and debounced TextChangedI events
  • Smart debouncing: Continuous typing only triggers XP tracking after a configurable delay (default: 500ms)
  • Batched processing: XP additions are batched and processed together to reduce overhead

Language Detection Caching

  • Smart caching: Language detection results are cached for up to 1 second (configurable)
  • Position-aware: Cache is invalidated when cursor moves significantly (>5 lines or >10 columns)
  • Fast path optimization: Files without embedded languages skip expensive TreeSitter operations

Configurable Performance Settings

You can fine-tune the performance behavior:

require('maorun.code-stats').setup({
    api_key = '<YOUR_API_KEY>',
    performance = {
        typing_debounce_ms = 500, -- How long to wait after typing stops before tracking XP
        xp_batch_delay_ms = 100,  -- How long to batch XP additions before processing
        cache_timeout_s = 1,      -- How long to cache language detection results
    }
})

Performance Settings Explained

  • typing_debounce_ms: Controls the delay for TextChangedI events. Lower values = more responsive XP tracking but higher CPU usage. Higher values = less responsive but better performance.
  • xp_batch_delay_ms: Controls how long XP additions are batched before processing (level calculations, notifications). Lower values = more responsive notifications but higher overhead.
  • cache_timeout_s: Controls how long language detection results are cached. Lower values = more accurate language detection for rapidly changing contexts but higher CPU usage.

Recommended values:

  • Fast systems: typing_debounce_ms = 300, xp_batch_delay_ms = 50, cache_timeout_s = 1
  • Default (balanced): typing_debounce_ms = 500, xp_batch_delay_ms = 100, cache_timeout_s = 1
  • Slower systems: typing_debounce_ms = 1000, xp_batch_delay_ms = 200, cache_timeout_s = 2

Managing Logs

Use the :CodeStatsLog command to manage logging:

:CodeStatsLog status        " Show logging status and file location
:CodeStatsLog path          " Show log file path
:CodeStatsLog clear         " Clear the log file

Error Messages

The plugin provides clear, user-friendly error messages for common issues:

  • Configuration problems (missing API key, invalid URL)
  • Network connectivity issues
  • File I/O errors for XP persistence
  • JSON parsing errors

Error messages are displayed in the statusline and through notifications, with detailed information logged to the log file when logging is enabled.

Troubleshooting

atm. the filetype is used as language because i don't know how to get the language on actual input

(eg. CSS in HTML)

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •