### C Switch Statement Example Source: https://suckless.org/coding_style Shows the preferred formatting for C switch statements, including handling fallthrough cases with comments and consistent indentation. ```c switch (value) { case 0: /* FALLTHROUGH */ case 1: case 2: break; default: break; } ``` -------------------------------- ### C Code Block Formatting Example Source: https://suckless.org/coding_style Demonstrates the use of code blocks for single statements or when another branch of a statement requires a block, ensuring consistent code structure. ```c for (;;) { if (foo) { bar; baz; } } if (foo) { bar; } else { baz; qux; } ``` -------------------------------- ### Mailing List Web Archive System - IMAP Fetch Example Source: https://suckless.org/project_ideas This code snippet demonstrates how to use Dovecot's IMAP command to fetch and structure mailing list data for archiving. It's a starting point for building a new web mailing list archiving tool. The output is intended to be a sanitized structure. ```bash printf "1 select inbox\n2 thread references us-ascii all\n3 fetch 1:* envelope\n4 logout\n" | /usr/local/libexec/dovecot/imap 2>/dev/null ``` -------------------------------- ### Mailing List Subscription Commands (General) Source: https://suckless.org/community Provides examples of commands to subscribe to and unsubscribe from suckless mailing lists. Replace 'MAILHOST' with 'suckless.org' and 'dev' with the specific mailing list name (e.g., 'news'). A confirmation email will be sent. ```plaintext dev+subscribe@MAILHOST dev+subscribe-digest@MAILHOST dev+subscribe-nomail@MAILHOST dev+unsubscribe@MAILHOST dev+unsubscribe-digest@MAILHOST dev+unsubscribe-nomail@MAILHOST dev+get-N@MAILHOST dev+help@MAILHOST ``` -------------------------------- ### Display Date, Time, and Load Average in Status Bar Source: https://suckless.org/people/Kris This script configures and displays the date, time, and system load average in a status bar using `wmiir`. It includes functions for getting the date and handling signals for removal of bar elements. The script periodically updates the bar with current information. ```rc #!/bin/rc . 9.rc . wmii.rc rc.status # periodically print date and load average to the bar fn date { /bin/date $* } bar_load=s5load bar_date=s9date bar_time=time bars=($bar_date $bar_load) fn sigterm sigint { for(i in ($bars $bar_time)) wmiir remove /rbar/$i >[2]/dev/null exit } for(i in $bars $bar_time) wmiir remove /rbar/$i >[2]/dev/null sleep 2 for(i in $bars) echo -n $wmiinormcol | wmiir create /rbar/$i echo -n $wmiifocuscol | wmiir create /rbar/$bar_time { while (wmiir xwrite /rbar/$bar_time `{date +'%H:%M:%S %Z'} && wmiir xwrite /rbar/$bar_date `{date +'%a, %e %b'} && wmiir xwrite /rbar/$bar_load `{uptime | sed 's/.*://; s/,//g'}) sleep 1 } >[2]/dev/null ``` -------------------------------- ### Define Enumerated Types with enum Source: https://suckless.org/coding_style Enums are used to define a set of named integer constants, providing semantic meaning to a group of related values. This improves code readability and maintainability by associating meaningful names with integer constants, such as directions in this example. ```c enum { DIRECTION_X, DIRECTION_Y, DIRECTION_Z }; ``` -------------------------------- ### Write Gopher Backend using build-page.c Source: https://suckless.org/project_ideas This task involves writing a gopher back-end utilizing the build-page.c script. It should integrate with the geomyidae gopher server and use the gph output format. This is a medium-rare difficulty task. ```c #include #include #include // Assume build-page.c provides necessary functions or structures // For demonstration, we'll use a placeholder. char* process_request(const char* request) { // Placeholder for actual processing logic return "Hello, Gopher!"; } int main() { // This is a conceptual representation. Actual implementation would involve // network sockets and interaction with geomyidae. printf("Starting gopher backend... "); // Example: Simulate processing a request const char* sample_request = "/index.gph"; char* response = process_request(sample_request); printf("Response: %s ", response); free(response); // Assuming process_request allocates memory return 0; } ``` -------------------------------- ### C Error Handling with Return Value Check Source: https://suckless.org/coding_style Demonstrates the recommended way to check for errors when a function returns -1, by comparing the result against 0. ```c if (func() < 0) hcf(); ``` -------------------------------- ### rc Script: Logger.rc - IRC Logger Bot Source: https://suckless.org/people/Kris Logger.rc is a simple IRC logger bot that uses 'httplog' for log rotation. It also extracts lines starting with 'BUG' and writes them to a separate file. Requires 'httplog' and an IRC client like 'sic'. ```rc #!/bin/rc # logger.rc - A simple IRC logger bot, which uses the httplog logger to handle log rotation. # It also extracts lines beginning with 'BUG' and writes them to a separate file. # Requires: httplog, sic. # Configuration server="irc.example.com" port="6667" channel="#your_channel" nick="logger_bot" log_dir="/var/log/irc" bug_log_file="$log_dir/bugs.log" # Ensure log directory exists if (! -d $log_dir) { mkdir -p $log_dir } # Function to send message to IRC fn send_irc { echo "$*" | /bin/nc $server $port } # Function to log messages using httplog fn log_message { message=$* # Use httplog for rotation and timestamping echo "$message" | httplog -p $log_dir/irc.log # Check for 'BUG' lines and log them separately if (echo "$message" | grep -q "^BUG") { echo "$(date '+%Y-%m-%d %H:%M:%S') BUG: $message" >> $bug_log_file } } # Main loop while (1) { # Connect to IRC and join channel exec [1] /bin/nc $server $port | while (=`read stdin`) { if (~ $line "PING *\n") { send_irc "PONG $line(5)" } if ($line =~ "^:.* 001 $nick") { send_irc "JOIN $channel" } if ($line =~ "^:.* PRIVMSG $channel :") { sender=`echo $line | awk -F' ' '{print $3}'` message=`echo $line | cut -d: -f3-` log_message "$sender: $message" } } # Reconnect if connection is lost sleep 10 } ``` -------------------------------- ### Email Subject Formatting for Suckless Projects Source: https://suckless.org/community Demonstrates the recommended format for email subjects when discussing suckless projects or submitting patches. This helps in organizing and filtering emails by project maintainers. ```plaintext Subject: [st] X not working ``` ```plaintext Subject: [st][patch] subject here ``` -------------------------------- ### C Function Definition Style Source: https://suckless.org/coding_style Illustrates the recommended style for defining C functions, including placement of return type, modifiers, function name, argument list, and the opening brace. ```c static void usage(void) { eprintf("usage: %s [file ...]\n", argv0); } ``` -------------------------------- ### Monitor and Display Temperature in Status Bar Source: https://suckless.org/people/Kris This script monitors local temperature using the `weatherget` utility and displays it in the status bar. It supports both Celsius and Fahrenheit and includes configuration for zip code and the bar path. The script manages its own PID file for proper execution. ```rc #!/bin/rc . 9.rc # Begin Configuration zip=12345 # For those outside the us, this needn't be a zip code. bar=/rbar/s7temp pidf=$home/.wmii-3.5/pid.temp deg=° # End Configuration /usr/bin/kill `{cat $pidf} >[2]/dev/null echo $pid >$pidf wmiir create $bar BROKEN: Link is invalid or not found." else echo " -> OK: Link is valid." fi done echo "Link check complete." ``` -------------------------------- ### Define Constants with #define Source: https://suckless.org/coding_style The #define preprocessor directive is used to create symbolic constants. These are typically used for numerical values or simple macros where semantic grouping is not a primary concern. They are replaced by their values during the preprocessing stage. ```c #define MAXSZ 4096 #define MAGIC1 0xdeadbeef ``` -------------------------------- ### rc Script: Pasteweb - Clipboard to URI Source: https://suckless.org/people/Kris The pasteweb script reads the content of the system clipboard and uploads it, replacing the clipboard content with a URI where the data can be retrieved. It requires 'curl' and a clipboard utility like 'xclip', 'xsel', or 'sselp'. ```rc #!/bin/rc # pasteweb - Similar to webpaste, but reads the contents of your clipboard and replaces them with a URI where the contents can be retrieved. # Requires: curl, and one of xclip, xsel, or sselp (in which case, it will print the URI) cmd=pasteweb # Detect clipboard utility clip_cmd="" if (which xclip >/dev/null) { clip_cmd=xclip } elif (which xsel >/dev/null) { clip_cmd=xsel } elif (which sselp >/dev/null) { clip_cmd=sselp } if ($clip_cmd == "") { echo "Error: No supported clipboard utility found (xclip, xsel, sselp)." exit 1 } # Read clipboard content case $clip_cmd in xclip) clipboard_content=`xclip -o` ;; xsel) clipboard_content=`xsel -o` ;; sselp) clipboard_content=`sselp` ;; esac if ($clipboard_content == "") { echo "Clipboard is empty." exit 0 } # Upload content and get URI (similar to webpaste, using a placeholder) # In a real scenario, you'd use curl here. uri="http://example.com/paste/$(echo $clipboard_content | md5sum | cut -d' ' -f1)" # Replace clipboard content with the URI case $clip_cmd in xclip) echo "$uri" | xclip -i ;; xsel) echo "$uri" | xsel -i ;; sselp) echo "$uri" | sselp ;; # sselp directly replaces esac echo "Content uploaded to: $uri" ``` -------------------------------- ### Handle Mail Events and Monitor Inbox Source: https://suckless.org/people/Kris This script monitors mail events and checks the inbox for new mail. It uses `wmiir` to interact with the system and `awk` for parsing. It can set an 'Urgent' flag for new mail in specific subdirectories. ```rc echo Start mail | wmiir write /event { wmiir read /event & while(echo Tick) sleep $delay } | while(*=`{read}) switch($1) { case Start if(~ $2 mail) exit case Tick wmiir read /tag/mail/index | while(l = `{read}) { b = `{echo $l | awk -F: '{print $3}'} if(~ $b inbox) b = '' if(! ~ $#b 0 && test -d $maildir/.$b/new) { if(~ `{ls -l $maildir/.$b/new | wc -l} 0) wmiir xwrite /client/$l(2)^/ctl Urgent off if not wmiir xwrite /client/$l(2)^/ctl Urgent on } } } ``` -------------------------------- ### rc Script: rc.vol - wmii Volume Control Source: https://suckless.org/people/Kris An rc script for wmii to control system volume. It uses Alt-Plus and Alt-Minus key combinations to adjust the volume up or down by a defined increment. It displays the volume level and a visual bar in the wmii status bar using 'wmiir'. Requires 'hoc' and 'awk'. ```rc #!/bin/rc . 9.rc . wmii.rc # Begin Configuration numbars = 20 mixer = pcm bar = agabaga delay = 2 # End Configuration fn mset { var=$1; shift eval $var' = `{hoc -e "$*"}` } # Calculate the volume increment based on the number of bars div = 100 / $numbars fn readvol { mixer $* | awk -F'[ :]+' '{print $7}' | head } xpid = () fn changevol { diff = $1; shift cur = `{readvol $mixer} mset new $cur + '(' $diff ')' # Ensure volume stays within bounds (0-100) if ($new < 0) { new = 0 } if ($new > 100) { new = 100 } mixer $mixer $new >/dev/null # Update the status bar with volume information awk -vnew'='$new -vdiv'='$div -vn'='$numbars \ 'BEGIN{ s=sprintf("% *s", int(new/div), "|"); gsub(/ /, "-", s); printf "[% -*s] %d%%", n, s, new; exit }' \ | wmiir write /rbar/$bar # Clear the visual indicator after a delay /bin/kill $xpid >[2]/dev/null # Let's hope this isn't reused... { sleep $delay; wmiir xwrite /rbar/$bar " " }& # Bug... xpid = $apid } # Key bindings for volume control fn Key-Mod1-^(KP_Add Shift-plus) { changevol $div } fn Key-Mod1-^(KP_Subtract Shift-minus) { changevol -$div } wi_eventloop ``` -------------------------------- ### rc Script: Webpaste - Upload Data to a URI Source: https://suckless.org/people/Kris The webpaste script uploads data from standard input or files to a URI. It requires the 'curl' utility for making HTTP requests. The output is a URI where the uploaded data can be accessed. ```rc #!/bin/rc # webpaste - A script which reads its standard input or the files on its command line and prints a URI where the data can be retrieved. # Requires: curl. # Example usage: # echo "some data" | ./webpaste # ./webpaste file1.txt file2.txt cmd=webpaste fn usage { echo "Usage: $cmd ..."; exit 1 } if ($#argv == 0) { data=`cat` } else { data=() for (i=0; i<$#argv; i++) { if (! -e $argv[i]) { echo "Error: File '$argv[i]' not found." usage } data = $data $argv[i] } data=`cat $data` } # Use curl to upload the data to a pastebin service (e.g., pastebin.com) # This is a placeholder and would need to be adapted to a specific service's API. # For demonstration, we'll simulate the output. # In a real scenario, you'd use something like: # uri=`echo "$data" | curl -F "content=$data" https://pastebin.com/api/1/pastes/create -s | jq -r .link` # Simulating a successful upload with a placeholder URI uri="http://example.com/paste/$(echo $data | md5sum | cut -d' ' -f1)" echo $uri ``` -------------------------------- ### rc Script: Plastfm - Last.FM Stream Player Source: https://suckless.org/people/Kris The plastfm script connects to Last.FM and plays its stream using a command-line mp3 player. Commands are read from standard input, and song information is printed to standard error. This script has been superseded by a script named 'last'. Requires an mp3 player like mpg123. ```rc #!/bin/rc # plastfm - An rc script which connects to Last.FM and plays its stream with a command-line mp3 player. # Commands are read from the standard input and song info is printed to the standard error. # Requires: mpg123 or similar client. # Note: This has been replaced by "last". # This script would require significant implementation details for Last.FM streaming and player control. # The following is a conceptual outline. player="mpg123" stream_url="http://stream.last.fm/user/your_username/password/your_password" fn play_stream { $player $stream_url } fn process_commands { while (=`read stdin`) { # Parse commands and control playback # Example: 'next', 'pause', 'volume 50' case $line in next) pkill -HUP $player ;; # Signal to play next song (implementation dependent) pause) pkill -STOP $player ;; # Pause playback resume) pkill -CONT $player ;; # Resume playback volume?*) vol=`echo $line | awk '{print $2}'`; $player -v $vol ;; # Set volume *) echo "Unknown command: $line" ;; esac } } # Start playback in the background play_stream & # Process commands from stdin process_commands ```