trinket-blog/static/rss.xml

3152 lines
222 KiB
XML
Raw Permalink Normal View History

2023-12-19 18:02:34 +00:00
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<atom:link href="https://blog.trinket.icu/rss.xml" rel="self" type="application/rss+xml"/>
<title>Trinket Blog</title>
2023-12-19 18:02:34 +00:00
<link>https://blog.trinket.icu</link>
<description>Trinket Blog - My tech ramblings about everything under the sun.</description>
2023-12-19 18:02:34 +00:00
<language>en-us</language>
2024-04-09 19:09:52 +00:00
<copyright>© 2024 Shav Kinderlehrer</copyright>
<pubDate>Tue, 09 Apr 2024 19:00:00 GMT</pubDate>
2023-12-19 18:02:34 +00:00
<generator>jsonfeed-to-rss 3.0.7 (https://github.com/bcomnes/jsonfeed-to-rss#readme)</generator>
<docs>http://www.rssboard.org/rss-specification</docs>
<image>
<url>https://blog.trinket.icu/favicon.ico</url>
<link>https://blog.trinket.icu</link>
<title>Trinket Blog</title>
2023-12-19 18:02:34 +00:00
</image>
2024-04-09 19:09:52 +00:00
<item>
<title>Updated URL Shortener</title>
<link>https://blog.trinket.icu/articles/updated-url-shortener</link>
2024-04-09 19:09:52 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>Lately, I've been interested in improving my URL shortener hosted at https://trkt.in. So I did!
I present.. Chela!
I named Chela off of the small claw on crabs because it's like the little claw compared to the big one. Ok, I admit the name is vague but I think it's cute.
I built Chela in Rust using Axum as a server framework. It runs off of a Postgres database. It's very simple by design and also very fast. Using curl, I get a response in around a millisecond typically.
In my previous iteration of this project, I rather lazily generated IDs by hashing the URLs and then taking the first four or so letters. It was ugly and at increasing risk of collision.
In this new iteration, I'm using Sqids to generate IDs. It's better, faster (I think), and it looks prettier.
For example,
https://trkt.in/2614aab104d
https://trkt.in/WX
These both link to the same website (my previous blog post), but one of them is a whole lot easier to remember.
Also, this new version supports the + feature from bit.ly, where if you put a plus sign at the end of a URL it will show you what it links to. Try it!
I made the Docker image for Chela as small as I could without going off the deep end. The Chela binary is around 5Mb, and the full Docker image is just about 14Mb not including the Postgres dependency.
If you're interested, feel free to check it out here: https://trkt.in/oz.
</description>
<content:encoded><![CDATA[<p>Lately, I've been interested in improving my URL shortener hosted at <a href="https://trkt.in">https://trkt.in</a>. So I did!</p>
<p>I present.. <strong>Chela!</strong></p>
<p>I named Chela off of the small claw on crabs because it's like the little claw compared to the big one. Ok, I admit the name is vague but I think it's cute.</p>
<p>I built Chela in Rust using Axum as a server framework. It runs off of a Postgres database. It's very simple by design and also very fast. Using <code>curl</code>, I get a response in around a millisecond typically.</p>
<p>In my previous iteration of this project, I rather lazily generated IDs by hashing the URLs and then taking the first four or so letters. It was ugly and at increasing risk of collision.</p>
<p>In this new iteration, I'm using <a href="https://sqids.org/">Sqids</a> to generate IDs. It's better, faster (I think), and it looks prettier.</p>
<p>For example,</p>
<ul>
<li><a href="https://trkt.in/2614aab104d">https://trkt.in/2614aab104d</a></li>
<li><a href="https://trkt.in/WX">https://trkt.in/WX</a></li>
</ul>
<p>These both link to the same website (my previous blog post), but one of them is a whole lot easier to remember.</p>
<p>Also, this new version supports the <code>+</code> feature from bit.ly, where if you put a plus sign at the end of a URL it will show you what it links to. Try it!</p>
<p>I made the Docker image for Chela as small as I could without going off the deep end. The Chela binary is around 5Mb, and the full Docker image is just about 14Mb not including the Postgres dependency.</p>
<p>If you're interested, feel free to check it out here: <a href="https://trkt.in/oz">https://trkt.in/oz</a>.</p>
]]></content:encoded>
<guid isPermaLink="false">updated-url-shortener</guid>
<pubDate>Tue, 09 Apr 2024 19:00:00 GMT</pubDate>
</item>
2023-12-19 18:02:34 +00:00
<item>
<title>Writing a URL Shortener</title>
<link>https://blog.trinket.icu/articles/writing-a-url-shortener</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>The concept of a URL shortener is a rather silly one in definition. We take a place on the internet, and then we obfuscate it; hide it behind another layer and present that to people.
In practice however, it makes a good amount of sense.
Say I have this really long URL, https://blog.trinket.icu/articles/writing-a-url-shortener. I want to share it with my friend- only there's no way they'd remember that entire link if I told it to them in person.
I present, https://trkt.in/2614aab104d.
Ok, granted 2614aab104d is arguably harder to remember than the former link, but it's the thought that counts.
Now, you may be wondering 'why would you make a URL shortener when there's already tons of existing free ones'
If you're a programmer/maker then the answer should be obvious:
'Why would I use an existing closed-source product when I can make my own worse version of it?'
Now, obviously that isn't true for every product and every person, but with something as simple as a URL shortener I couldn't resist the challenge.
How a URL shortener works
A URL shortener is simply a website that takes in an arbitrary ID and redirects the client to the original website.
The ID
In most URL shorteners, any path after the TLD is considered to be the ID.
Consider this link:
https://trkt.in/2614aab104d
{ TLD }[ ID ]
In this case, 2614aab104d is the ID. It can be anything that is valid in a URL. So most restrict the ID to alphanumeric and hyphen or underscore characters.
For trkt.in, the ID can either be custom or auto generated. Every ID must be unique.
My current method for auto generation is to hash the URL using the md5 algorithm and take the first eleven characters. That means that every auto generated trkt link will be exactly eighteen characters long (not including the protocol https:// characters).
I arrived at eleven character long IDs using this python script:
import sys
import hashlib
ID_LEN = 11
ITERS = 5000000
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
passed = 0
failed = 0
hashes = set()
for i in range(0, ITERS):
i = str(i)
hash = hashlib.md5(i.encode())
hash = hash.hexdigest()[:ID_LEN]
if hash in hashes:
print(&amp;quot;\x1b[31m&amp;quot;, end=&amp;quot;&amp;quot;)
eprint(f&amp;quot;{i} - {hash}&amp;quot;)
failed += 1
else:
print(&amp;quot;\x1b[32m&amp;quot;, end=&amp;quot;&amp;quot;)
print(f&amp;quot;{i} - {hash}&amp;quot;)
passed += 1
print(&amp;quot;\x1b[0m&amp;quot;, end=&amp;quot;&amp;quot;)
eprint(&amp;quot;\x1b[0m&amp;quot;, end=&amp;quot;&amp;quot;)
hashes.add(hash)
eprint(f&amp;quot;PASS: {str(passed).zfill(7)}&amp;quot;)
eprint(f&amp;quot;FAIL: {str(failed).zfill(7)}&amp;quot;)
eprint(f&amp;quot;TOTAL: {ITERS}&amp;quot;)
eprint(f&amp;quot;PERCENT: {(passed / lines) * ITERS}% passed {(failed / ITERS) * 100}% failed&amp;quot;)
Running this will calculate the collision rate when slicing the first ten characters of the hash. Eleven is the shortest slice I could take that had a 0% collision rate among both 5M iterations and the top 1M websites dataset.
However, five million is a lot more links than this site will ever see, so switching to a smaller hash function that can produce an ID in the range of 3-7 characters would probably be much better in the long run.
Alternatively, I could do as most other URL shorteners do and simply aggressively iterate over every permutation of as few characters as possible.
aaa, aab, aac..
Both are valid approaches, but I have chosen to opt for the hash approach as it will catch duplicate entries easier and keep one site from having too many entries in the database.
The Database
The database is a very simple Postgres table.
postgres=# \d urls
Table &amp;quot;public.urls&amp;quot;
Column | Type | Collation | Nullable | Default
--------+-------------------------+-----------+----------+---------
id | text | | not null |
url | character varying(2048) | | not null |
Indexes:
&amp;quot;urls_id_key&amp;quot; UNIQUE CONSTRAINT, btree (id)
When a client tries to fetch our example link https://trkt.in/2614aab104d, the server checks to see if the database has a row with the ID 2614aab104d, if it does, it issues a 301 redirect and that's the end of that. If it doesn't, it returns a simple 404.
In Use
Here's what happens when I cURL a valid trkt.in link:
$ curl -v https://trkt.in/2614aab104d
&amp;gt; GET /2614aab104d HTTP/1.1
&amp;gt; Host: trkt.in
&amp;gt; User-Agent: curl/8.1.2
&amp;gt; Accept: */*
&amp;gt;
&amp;lt; HTTP/1.1 301 Moved Permanently
&amp;lt; Server: nginx/1.18.0 (Ubuntu)
&amp;lt; Date: Sun, 15 Oct 2023 20:57:37 GMT
&amp;lt; Content-Type: text/html
&amp;lt; Content-Length: 250
&amp;lt; Connection: keep-alive
&amp;lt; Location: https://blog.trinket.icu/articles/writing-a-url-shortener
&amp;lt; Cache-Control: max-age=120
&amp;lt; X-Message: Okay I Like It, Picasso
&amp;lt;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;trkt&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;p&amp;gt;redirecting to &amp;lt;a href=&amp;quot;https://blog.trinket.icu/articles/writing-a-url-shortener&amp;quot;&amp;gt;https://blog.trinket.icu/articles/writing-a-url-shortener&amp;lt;/a&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
It's really that simple.
Currently, trkt.in is a private URL shortener, I don't have the money to host a free service like that, and I'm not willing to monetize it.
However, the sourcecode is available at trkt.in/source. Feel free to selfhost your own instance.
The server is build as an Nginx proxy to a BunJS server.
</description>
<content:encoded><![CDATA[<p>The concept of a URL shortener is a rather silly one in definition. We take a place on the internet, and then we obfuscate it; hide it behind another layer and present that to people.</p>
<p>In practice however, it makes a good amount of sense.</p>
<p>Say I have this really long URL, <a href="https://blog.trinket.icu/articles/writing-a-url-shortener">https://blog.trinket.icu/articles/writing-a-url-shortener</a>. I want to share it with my friend- only there's no way they'd remember that entire link if I told it to them in person.</p>
<p>I present, <a href="https://trkt.in/2614aab104d">https://trkt.in/2614aab104d</a>.</p>
<blockquote>
<p>Ok, granted <code>2614aab104d</code> is arguably harder to remember than the former link, but it's the thought that counts.</p>
</blockquote>
<p>Now, you may be wondering <em>'why would you make a URL shortener when there's already tons of existing free ones'</em></p>
<p>If you're a programmer/maker then the answer should be obvious:
<em>'Why would I use an existing closed-source product when I can make my own worse version of it?'</em></p>
<p>Now, obviously that isn't true for every product and every person, but with something as simple as a URL shortener I couldn't resist the challenge.</p>
<h2>How a URL shortener works</h2>
<p>A URL shortener is simply a website that takes in an arbitrary ID and redirects the client to the original website.</p>
<h3>The ID</h3>
<p>In most URL shorteners, any path after the TLD is considered to be the ID.</p>
<p>Consider this link:</p>
<pre><code>https://trkt.in/2614aab104d
{ TLD }[ ID ]
</code></pre>
<p>In this case, <code>2614aab104d</code> is the ID. It can be anything that is valid in a URL. So most restrict the ID to alphanumeric and hyphen or underscore characters.</p>
<p>For <a href="https://trkt.in">trkt.in</a>, the ID can either be custom or auto generated. Every ID must be unique.</p>
<p>My current method for auto generation is to hash the URL using the md5 algorithm and take the first eleven characters. That means that every auto generated trkt link will be exactly eighteen characters long (not including the protocol <code>https://</code> characters).</p>
<p>I arrived at eleven character long IDs using this python script:</p>
<pre><code class="language-py">import sys
import hashlib
ID_LEN = 11
ITERS = 5000000
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
passed = 0
failed = 0
hashes = set()
for i in range(0, ITERS):
i = str(i)
hash = hashlib.md5(i.encode())
hash = hash.hexdigest()[:ID_LEN]
if hash in hashes:
print(&quot;\x1b[31m&quot;, end=&quot;&quot;)
eprint(f&quot;{i} - {hash}&quot;)
failed += 1
else:
print(&quot;\x1b[32m&quot;, end=&quot;&quot;)
print(f&quot;{i} - {hash}&quot;)
passed += 1
print(&quot;\x1b[0m&quot;, end=&quot;&quot;)
eprint(&quot;\x1b[0m&quot;, end=&quot;&quot;)
hashes.add(hash)
eprint(f&quot;PASS: {str(passed).zfill(7)}&quot;)
eprint(f&quot;FAIL: {str(failed).zfill(7)}&quot;)
eprint(f&quot;TOTAL: {ITERS}&quot;)
eprint(f&quot;PERCENT: {(passed / lines) * ITERS}% passed {(failed / ITERS) * 100}% failed&quot;)
</code></pre>
<p>Running this will calculate the collision rate when slicing the first ten characters of the hash. Eleven is the shortest slice I could take that had a 0% collision rate among both 5M iterations and the top 1M websites dataset.</p>
<p>However, five million is a lot more links than this site will ever see, so switching to a smaller hash function that can produce an ID in the range of 3-7 characters would probably be much better in the long run.</p>
<p>Alternatively, I could do as most other URL shorteners do and simply aggressively iterate over every permutation of as few characters as possible.</p>
<blockquote>
<p><code>aaa</code>, <code>aab</code>, <code>aac</code>..</p>
</blockquote>
<p>Both are valid approaches, but I have chosen to opt for the hash approach as it will catch duplicate entries easier and keep one site from having too many entries in the database.</p>
<h3>The Database</h3>
<p>The database is a very simple Postgres table.</p>
<pre><code>postgres=# \d urls
Table &quot;public.urls&quot;
Column | Type | Collation | Nullable | Default
--------+-------------------------+-----------+----------+---------
id | text | | not null |
url | character varying(2048) | | not null |
Indexes:
&quot;urls_id_key&quot; UNIQUE CONSTRAINT, btree (id)
</code></pre>
<p>When a client tries to fetch our example link <code>https://trkt.in/2614aab104d</code>, the server checks to see if the database has a row with the ID <code>2614aab104d</code>, if it does, it issues a 301 redirect and that's the end of that. If it doesn't, it returns a simple 404.</p>
<h3>In Use</h3>
<p>Here's what happens when I cURL a valid trkt.in link:</p>
<pre><code class="language-bash">$ curl -v https://trkt.in/2614aab104d
&gt; GET /2614aab104d HTTP/1.1
&gt; Host: trkt.in
&gt; User-Agent: curl/8.1.2
&gt; Accept: */*
&gt;
&lt; HTTP/1.1 301 Moved Permanently
&lt; Server: nginx/1.18.0 (Ubuntu)
&lt; Date: Sun, 15 Oct 2023 20:57:37 GMT
&lt; Content-Type: text/html
&lt; Content-Length: 250
&lt; Connection: keep-alive
&lt; Location: https://blog.trinket.icu/articles/writing-a-url-shortener
&lt; Cache-Control: max-age=120
&lt; X-Message: Okay I Like It, Picasso
&lt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;trkt&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;redirecting to &lt;a href=&quot;https://blog.trinket.icu/articles/writing-a-url-shortener&quot;&gt;https://blog.trinket.icu/articles/writing-a-url-shortener&lt;/a&gt;&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>It's really that simple.</p>
<p>Currently, trkt.in is a private URL shortener, I don't have the money to host a free service like that, and I'm not willing to monetize it.</p>
<p>However, the sourcecode is available at <a href="https://trkt.in/source">trkt.in/source</a>. Feel free to selfhost your own instance.</p>
<p>The server is build as an Nginx proxy to a BunJS server.</p>
]]></content:encoded>
<guid isPermaLink="false">writing-a-url-shortener</guid>
<pubDate>Sun, 15 Oct 2023 19:00:00 GMT</pubDate>
</item>
<item>
<title>Journaling as a Programmer</title>
<link>https://blog.trinket.icu/articles/journaling-as-a-programmer</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>warning⚠
Some of the plain-text code blocks may be incorrectly formatted, if they are, I apologize profusely and curse the semantics of spaces versus tabs
History
Over the course of my life, I've had on-and-off attempts at starting a journaling habit. Some were semi-successful, lasting around a month of daily writing. In the end though, I always broke down and let the habit deteriorate.
Lately, I've tried a different approach to journaling that I'm hopeful about.
Previously, if I were to write an entry I'd take the time to write a long entry that was well formatted. I was writing essays. I'm not sure why I did that, but it gave me the misconception that journaling was a chore, not a therapeutic exercise.
With that revelation, I decided to take a new approach to journaling. Rather than block out times to write long, detailed recounts of my day, maybe I could make small rapid notes that were well organized. That way I'd still be able to read through my past entries cohesively, but writing the entries would be a lot more natural for me.
I also decided to switch from physical paper journaling to files on my laptop. While there is a lovely aspect to paper that makes the experience different, I find that it makes me think harder about what I'm writing. Since it's a lot harder to go back and change pen-and-ink than it is to delete some letters on a laptop, I spend a lot more time stressing about what I write on paper. It's harder for me to get into a word-dump flow state.
The system
My basic organization scheme is as follows:
|-- 2023/
| |-- 08/
| |-- 2023-08-27.txt
| |-- 2023-08-28.txt
| |-- 2023-08-29.txt
| |-- 2023-08-30.txt
| |-- 2023-08-31.txt
| |-- 09/
| |-- 2023-09-01.txt
The path for any given day would be YEAR/MONTH/DATE.txt.
I find that this structure works well for me as everything is nicely grouped up, not too nested, and doesn't have much file-clutter.
Individual files
Now, the structure of the files is good, but if I'm going to be making small, rapid additions over the course of the day the files should also be organized.
To start out, each file has a small header that looks like this:
=============
August 2023
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 XX 29 30 31
Monday
=============
Enclosed in ============= I put a small calendar for the month (with the current day replaced by XX), and the current day of the week.
This small header keeps a nice common structure between the files, and is very aesthetic in my opinion. It ties files together, and looks good in the process.
Now, for each individual entry, I put a small prefix with the time to keep them separate.
It looks like this:
* At 10:18
A quick note about a shower thought I just had.
When all tied together, it makes a surprisingly cohesive format. Something that I can read through later and understand what past me was thinking.
Here's what a typical journal entry for a full day could look like:
=============
August 2023
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
XX 28 29 30 31
Sunday
=============
* At 14:31
If cats had opposable thumbs I could probably teach mine to play chess.
* At 15:39
Just getting back, going to get dinner at a resturant.They make eh food but
good ice cream. I'm subtly trying to cut back on dairy though, so sadly I'll
probably just get a sorbet or similar.
* At 18:16
I think maybe I'll write a blog article about this system. Or maybe I'll
rewrite a project in Tcl, Perl, or closure- some language that I'm interested
in learning.
* At 22:17
About to sign off for the night.
I'm liking this journaling, it makes my brain wind down in a good way.
Time to unpack, unwind, and get ready to sleep.
Automation
Like the lazy programmer I am, I quickly spotted an opportunity to abstract away the repetitive parts of this system.
I spent an afternoon whipping up journal.sh, a small zsh script that can handle all the templating for me.
I'll link the full script at the end of this post, but first I want to go over some snippets from it.
#setup header
if [ ! -f &amp;quot;$file&amp;quot; ]; then
mkdir -p $(dirname &amp;quot;$file&amp;quot;) 2&amp;gt; /dev/null
printf &amp;quot;%0.s=&amp;quot; {1..13} &amp;gt;&amp;gt; $file
printf &amp;quot;\n&amp;quot; &amp;gt;&amp;gt; $file
cal -h &amp;quot;$month&amp;quot; &amp;quot;$year&amp;quot; | sed &amp;quot;0,/$daynum/{s//XX/}&amp;quot; &amp;gt;&amp;gt; $file
truncate -s -1 $file
printf &amp;quot;\n$day\n&amp;quot; &amp;gt;&amp;gt; $file
printf &amp;quot;%0.s=&amp;quot; {1..13} &amp;gt;&amp;gt; $file
printf &amp;quot;\n&amp;quot; &amp;gt;&amp;gt; $file
change_status=&amp;quot;Created&amp;quot;
fi
if ! grep -xq &amp;quot;$nowtime&amp;quot; &amp;quot;$file&amp;quot;; then
printf &amp;quot;\n* At $nowtime\n&amp;quot; &amp;gt;&amp;gt; $file
fi
$EDITOR $file
This is the section that does all the template heavy-lifting. First, it creates the file if it doesn't exist, then it uses cal and sed to generate a little calendar header with the current day marked.
Then, it does a check with grep to see if $nowtime (the current hour:minute) is already on a line in the file. If it isn't it adds it.
Then, it opens the file in your $EDITOR
That's really all there is to it.
journal.sh has a few tricks, however.
GNU date has a -d flag that lets you describe a relative time. Something like date +%m -d &amp;quot;last month&amp;quot; will print the number for last month. journal.sh utilizes this feature as much as possible.
This is how it sets all the needed date values:
nowtime=$(date &amp;quot;+%H:%M&amp;quot;) || exit
day=$(date &amp;quot;+%A&amp;quot; -d &amp;quot;$*&amp;quot;) || exit
daynum=$(date &amp;quot;+%e&amp;quot; -d &amp;quot;$*&amp;quot;) || exit
month=$(date &amp;quot;+%m&amp;quot; -d &amp;quot;$*&amp;quot;) || exit
year=$(date &amp;quot;+%Y&amp;quot; -d &amp;quot;$*&amp;quot;) || exit
date=$(date &amp;quot;+%Y-%m-%d&amp;quot; -d &amp;quot;$*&amp;quot;) || exit
date_path=$(date &amp;quot;+%Y/%m&amp;quot; -d &amp;quot;$*&amp;quot;) || exit
journal_prefix=~/journal
file=&amp;quot;$journal_prefix/$date_path/$date.txt&amp;quot;
The -d &amp;quot;$* will expand to all arguments passed to the script. That means I can do something like ./journal.sh yesterday to open my entry from a day ago.
Git integration
In the interest of keeping my entries safe, journal.sh will automatically save my work when I close the file.
Here's the code for that:
printf &amp;quot;Save in git? [Y|n]: &amp;quot;
read yn
case $yn in
Y|y| )
git add &amp;quot;$file&amp;quot;
git commit -S -m &amp;quot;$change_status entry for $date at $nowtime&amp;quot; -m &amp;quot;$(randomart.py --ascii &amp;quot;$file&amp;quot;)&amp;quot;
esac
First, I'll get prompted to save the file, and then it will add it and commit the file for me.
I've added a few small features to this commit though. Firstly, using the -S flag will have git use PGP to sign all my journal entry commits. This just proves that I am the one who wrote them (or at least the one who added them to this git repository).
Then, git will use randomart.py to generate a little piece of ascii art based off of the hash of my journal entry. This doesn't really add anything to the project, but I like it nonetheless. In the end, running git log looks something like this:
commit 81e10dd3c80d2f4e31c0d7049d8ca2ab1b0adc84 (HEAD -&amp;gt; main)
Author: Shav Kinderlehrer &amp;lt;shav@trinket.icu&amp;gt;
Date: Mon Aug 28 13:52:07 2023 -0400
Edited entry for 2023-08-28 at 13:50
/--[randomart.py]--\
| .*. *... !! |
| =~*|
| . .=*|
|. . ..=. . |
| .%=% . |
| *= %E== |
| *===~_.= |
| .%=.%~=!.* .|
| .=.%~***.*= |
\---[BLAKE2b/64]---/
commit 51dde788717b34ca86e45fa32c5c59eb946b739e
Author: Shav Kinderlehrer &amp;lt;shav@trinket.icu&amp;gt;
Date: Mon Aug 28 10:56:38 2023 -0400
Edited entry for 2023-08-28 at 10:50
/--[randomart.py]--\
| *!..R* *. |
| =%.=%* .= . |
| . . =. .. =.. |
| .* ==.. .==**.|
|. . %==. **R= .|
| . . .=% .~.. |
| ... ..*. **. |
| =*.*%. |
| *=*=.**... |
\---[BLAKE2b/64]---/
That's all folks!
This new method has been working really well for me so far, I'm really hopeful that this is endgame for me, and I can really make the habit stick.
One last note
As a small personal challenge, I've been trying to keep all my entries to a strict maximum width of 80 characters. I find that this looks better, and is easier to read.
Here's a link to journal.sh
If you prefer the raw file for curl
</description>
<content:encoded><![CDATA[<h2>warning⚠</h2>
<p><em>Some of the plain-text code blocks may be incorrectly formatted, if they are, I apologize profusely and curse the semantics of spaces versus tabs</em></p>
<h2>History</h2>
<p>Over the course of my life, I've had on-and-off attempts at starting a journaling habit. Some were semi-successful, lasting around a month of daily writing. In the end though, I always broke down and let the habit deteriorate.</p>
<p>Lately, I've tried a different approach to journaling that I'm hopeful about.
Previously, if I were to write an entry I'd take the time to write a long entry that was well formatted. I was writing essays. I'm not sure why I did that, but it gave me the misconception that journaling was a chore, not a therapeutic exercise.</p>
<p>With that revelation, I decided to take a new approach to journaling. Rather than block out times to write long, detailed recounts of my day, maybe I could make small rapid notes that were well organized. That way I'd still be able to read through my past entries cohesively, but writing the entries would be a lot more natural for me.</p>
<p>I also decided to switch from physical paper journaling to files on my laptop. While there is a lovely aspect to paper that makes the experience different, I find that it makes me think harder about what I'm writing. Since it's a lot harder to go back and change pen-and-ink than it is to delete some letters on a laptop, I spend a lot more time stressing about what I write on paper. It's harder for me to get into a word-dump flow state.</p>
<h2>The system</h2>
<p>My basic organization scheme is as follows:</p>
<pre><code class="language-plain">|-- 2023/
| |-- 08/
| |-- 2023-08-27.txt
| |-- 2023-08-28.txt
| |-- 2023-08-29.txt
| |-- 2023-08-30.txt
| |-- 2023-08-31.txt
| |-- 09/
| |-- 2023-09-01.txt
</code></pre>
<p>The path for any given day would be <code>YEAR/MONTH/DATE.txt</code>.</p>
<p>I find that this structure works well for me as everything is nicely grouped up, not too nested, and doesn't have much file-clutter.</p>
<h3>Individual files</h3>
<p>Now, the structure of the files is good, but if I'm going to be making small, rapid additions over the course of the day the files should also be organized.</p>
<p>To start out, each file has a small header that looks like this:</p>
<pre><code class="language-plain">=============
August 2023
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 XX 29 30 31
Monday
=============
</code></pre>
<p>Enclosed in <code>=============</code> I put a small calendar for the month (with the current day replaced by <code>XX</code>), and the current day of the week.</p>
<p>This small header keeps a nice common structure between the files, and is very aesthetic in my opinion. It ties files together, and looks good in the process.</p>
<p>Now, for each individual entry, I put a small prefix with the time to keep them separate.</p>
<p>It looks like this:</p>
<pre><code class="language-plain">* At 10:18
A quick note about a shower thought I just had.
</code></pre>
<p>When all tied together, it makes a surprisingly cohesive format. Something that I can read through later and understand what past me was thinking.</p>
<p>Here's what a typical journal entry for a full day could look like:</p>
<pre><code class="language-plain">=============
August 2023
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
XX 28 29 30 31
Sunday
=============
* At 14:31
If cats had opposable thumbs I could probably teach mine to play chess.
* At 15:39
Just getting back, going to get dinner at a resturant.They make eh food but
good ice cream. I'm subtly trying to cut back on dairy though, so sadly I'll
probably just get a sorbet or similar.
* At 18:16
I think maybe I'll write a blog article about this system. Or maybe I'll
rewrite a project in Tcl, Perl, or closure- some language that I'm interested
in learning.
* At 22:17
About to sign off for the night.
I'm liking this journaling, it makes my brain wind down in a good way.
Time to unpack, unwind, and get ready to sleep.
</code></pre>
<h2>Automation</h2>
<p>Like the lazy programmer I am, I quickly spotted an opportunity to abstract away the repetitive parts of this system.</p>
<p>I spent an afternoon whipping up <code>journal.sh</code>, a small <code>zsh</code> script that can handle all the templating for me.</p>
<p>I'll link the full script at the end of this post, but first I want to go over some snippets from it.</p>
<pre><code class="language-bash">#setup header
if [ ! -f &quot;$file&quot; ]; then
mkdir -p $(dirname &quot;$file&quot;) 2&gt; /dev/null
printf &quot;%0.s=&quot; {1..13} &gt;&gt; $file
printf &quot;\n&quot; &gt;&gt; $file
cal -h &quot;$month&quot; &quot;$year&quot; | sed &quot;0,/$daynum/{s//XX/}&quot; &gt;&gt; $file
truncate -s -1 $file
printf &quot;\n$day\n&quot; &gt;&gt; $file
printf &quot;%0.s=&quot; {1..13} &gt;&gt; $file
printf &quot;\n&quot; &gt;&gt; $file
change_status=&quot;Created&quot;
fi
if ! grep -xq &quot;$nowtime&quot; &quot;$file&quot;; then
printf &quot;\n* At $nowtime\n&quot; &gt;&gt; $file
fi
$EDITOR $file
</code></pre>
<p>This is the section that does all the template heavy-lifting. First, it creates the file if it doesn't exist, then it uses <code>cal</code> and <code>sed</code> to generate a little calendar header with the current day marked.</p>
<p>Then, it does a check with <code>grep</code> to see if <code>$nowtime</code> (the current hour:minute) is already on a line in the file. If it isn't it adds it.</p>
<p>Then, it opens the file in your <code>$EDITOR</code></p>
<p>That's really all there is to it.</p>
<p><code>journal.sh</code> has a few tricks, however.
GNU <code>date</code> has a <code>-d</code> flag that lets you describe a relative time. Something like <code>date +%m -d &quot;last month&quot;</code> will print the number for last month. <code>journal.sh</code> utilizes this feature as much as possible.</p>
<p>This is how it sets all the needed date values:</p>
<pre><code class="language-bash">nowtime=$(date &quot;+%H:%M&quot;) || exit
day=$(date &quot;+%A&quot; -d &quot;$*&quot;) || exit
daynum=$(date &quot;+%e&quot; -d &quot;$*&quot;) || exit
month=$(date &quot;+%m&quot; -d &quot;$*&quot;) || exit
year=$(date &quot;+%Y&quot; -d &quot;$*&quot;) || exit
date=$(date &quot;+%Y-%m-%d&quot; -d &quot;$*&quot;) || exit
date_path=$(date &quot;+%Y/%m&quot; -d &quot;$*&quot;) || exit
journal_prefix=~/journal
file=&quot;$journal_prefix/$date_path/$date.txt&quot;
</code></pre>
<p>The <code>-d &quot;$*</code> will expand to all arguments passed to the script. That means I can do something like <code>./journal.sh yesterday</code> to open my entry from a day ago.</p>
<h3>Git integration</h3>
<p>In the interest of keeping my entries safe, <code>journal.sh</code> will automatically save my work when I close the file.</p>
<p>Here's the code for that:</p>
<pre><code class="language-bash">printf &quot;Save in git? [Y|n]: &quot;
read yn
case $yn in
Y|y| )
git add &quot;$file&quot;
git commit -S -m &quot;$change_status entry for $date at $nowtime&quot; -m &quot;$(randomart.py --ascii &quot;$file&quot;)&quot;
esac
</code></pre>
<p>First, I'll get prompted to save the file, and then it will add it and commit the file for me.</p>
<p>I've added a few small features to this commit though. Firstly, using the <code>-S</code> flag will have git use PGP to sign all my journal entry commits. This just proves that I am the one who wrote them (or at least the one who added them to this git repository).</p>
<p>Then, git will use <a href="https://github.com/ansemjo/randomart"><code>randomart.py</code></a> to generate a little piece of ascii art based off of the hash of my journal entry. This doesn't really add anything to the project, but I like it nonetheless. In the end, running <code>git log</code> looks something like this:</p>
<pre><code class="language-plain">commit 81e10dd3c80d2f4e31c0d7049d8ca2ab1b0adc84 (HEAD -&gt; main)
Author: Shav Kinderlehrer &lt;shav@trinket.icu&gt;
Date: Mon Aug 28 13:52:07 2023 -0400
Edited entry for 2023-08-28 at 13:50
/--[randomart.py]--\
| .*. *... !! |
| =~*|
| . .=*|
|. . ..=. . |
| .%=% . |
| *= %E== |
| *===~_.= |
| .%=.%~=!.* .|
| .=.%~***.*= |
\---[BLAKE2b/64]---/
commit 51dde788717b34ca86e45fa32c5c59eb946b739e
Author: Shav Kinderlehrer &lt;shav@trinket.icu&gt;
Date: Mon Aug 28 10:56:38 2023 -0400
Edited entry for 2023-08-28 at 10:50
/--[randomart.py]--\
| *!..R* *. |
| =%.=%* .= . |
| . . =. .. =.. |
| .* ==.. .==**.|
|. . %==. **R= .|
| . . .=% .~.. |
| ... ..*. **. |
| =*.*%. |
| *=*=.**... |
\---[BLAKE2b/64]---/
</code></pre>
<h2>That's all folks!</h2>
<p>This new method has been working really well for me so far, I'm really hopeful that this is endgame for me, and I can really make the habit stick.</p>
<h3>One last note</h3>
<p>As a small personal challenge, I've been trying to keep all my entries to a strict maximum width of 80 characters. I find that this looks better, and is easier to read.</p>
<p><a href="https://git.trinket.icu/scripts.git/tree/journal.sh">Here's a link to <code>journal.sh</code></a></p>
<p><a href="https://git.trinket.icu/scripts.git/plain/journal.sh">If you prefer the raw file for curl</a></p>
]]></content:encoded>
<guid isPermaLink="false">journaling-as-a-programmer</guid>
<pubDate>Mon, 28 Aug 2023 19:00:00 GMT</pubDate>
</item>
<item>
<title>All the Manpages</title>
<link>https://blog.trinket.icu/articles/all-the-manpages</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>I think manpages are neat. I use them a lot to find my way around new programs and especially when programming in C.
Another thing I like are books. I like big hefty textbooks I can flip through. I have a lot of obscure no starch press books. For me, having a physical book to read through helps me learn new things a lot better than watching a video, or reading something off a screen does.
Well, why not bring the two together?
My (admittedly half-assed) attempts to find a physical bound printout of manpages yielded only this amazon listing for an eye-watering $395.
Screw it I thought, I'll do it myself
I present to you mantobook.sh, my bad solution to this.
Mantobook
Mantobook works by going through every manpage on your computer section, by section and converting each individual page into an html file. Mantobook tries to use pandoc, but if that fails it'll just resort to good ol' groff + a little sed to clean things up.
After that, it combines every single manpage html file into one big html file for each section (this uses a lot of ram).
At that point I'll have 9 folders filled with individual files like man/1/ls.html, man/1/kak.html, or man/4/null.html and another folder with really big files like man/1.html, man/2.html, etc. Those are one big html file with every manpage in that section. Mantobook also separates intro pages if those exist and put them at the front of the generated section page.
Finally, the last optional part is to combine all 9 section files into one big mega-man-book.html. I did that and converted that to pdf using pandoc again.
I did my best to have the script do as much as possible in parallel since thousands and thousands of files are getting moved around and written to.
Running the full program takes about 40 minutes and crashes every other program on my computer. Completely worth it in my opinion.
Well, now I've got this big ol' pdf, who do I throw money at to print and bind it for me?
From digital to physical
It turns out- no one.
Not only is the pdf in excess of 160,000 pages, most book publishers refuse to print single copies of anything over ~840 pages. I don't know what 160,000 / 840 is, but that's a lot of volumes.
Ok, so we just print it all out and then bind it no?
Except, I don't have 160k pages of paper, and I don't think it's fair to waste all that on a hobby project.
Conclusion
Maybe someday I'll write a program to randomly select 840 pages worth of manpages and make a book out of just those. Then I'll get it printed/bound and be able to brag about how I have a book.
In the meantime, you can checkout the script I wrote here. If github lets me, I'll also push all my manpages as html files so you can see those too.
This was a fun little side-questy adventure!
</description>
<content:encoded><![CDATA[<p>I think manpages are neat. I use them a lot to find my way around new programs and especially when programming in C.</p>
<p>Another thing I like are books. I like big hefty textbooks I can flip through. I have a lot of obscure <a href="https://nostarch.com/">no starch press</a> books. For me, having a physical book to read through helps me learn new things a lot better than watching a video, or reading something off a screen does.</p>
<p>Well, why not bring the two together?</p>
<p>My (admittedly half-assed) attempts to find a physical bound printout of manpages yielded only <a href="https://www.amazon.com/Linux-Man-Essential-Pages/dp/188817272X">this amazon listing for an eye-watering $395</a>.</p>
<p><em>Screw it</em> I thought, <em>I'll do it myself</em></p>
<p>I present to you <code>mantobook.sh</code>, my bad solution to this.</p>
<h2>Mantobook</h2>
<p>Mantobook works by going through every manpage on your computer section, by section and converting each individual page into an <code>html</code> file. Mantobook tries to use <a href="https://pandoc.org/"><code>pandoc</code></a>, but if that fails it'll just resort to good ol' <code>groff</code> + a little <code>sed</code> to clean things up.</p>
<p>After that, it combines every single manpage html file into one big html file for each section (this uses a lot of ram).</p>
<p>At that point I'll have 9 folders filled with individual files like <code>man/1/ls.html</code>, <code>man/1/kak.html</code>, or <code>man/4/null.html</code> and another folder with really big files like <code>man/1.html</code>, <code>man/2.html</code>, etc. Those are one big <code>html</code> file with every manpage in that section. Mantobook also separates intro pages if those exist and put them at the front of the generated section page.</p>
<p>Finally, the last optional part is to combine all 9 section files into one big mega-man-book.html. I did that and converted <em>that</em> to pdf using <code>pandoc</code> again.</p>
<p>I did my best to have the script do as much as possible in parallel since thousands and thousands of files are getting moved around and written to.</p>
<p>Running the full program takes about 40 minutes and crashes every other program on my computer. Completely worth it in my opinion.</p>
<p>Well, now I've got this big ol' pdf, who do I throw money at to print and bind it for me?</p>
<h2>From digital to physical</h2>
<p>It turns out- no one.</p>
<p>Not only is the pdf in excess of 160,000 pages, most book publishers refuse to print single copies of anything over ~840 pages. I don't know what 160,000 / 840 is, but that's a lot of volumes.</p>
<p>Ok, so we just print it all out and then bind it no?</p>
<p>Except, I don't have 160k pages of paper, and I don't think it's fair to waste all that on a hobby project.</p>
<h2>Conclusion</h2>
<p>Maybe someday I'll write a program to randomly select 840 pages worth of manpages and make a book out of just those. Then I'll get it printed/bound and be able to brag about how I have a book.
In the meantime, you can checkout the script I wrote <a href="https://github.com/secondary-smiles/mantobook">here</a>. If github lets me, I'll also push all my manpages as html files so you can see those too.</p>
<p>This was a fun little side-questy adventure!</p>
]]></content:encoded>
<guid isPermaLink="false">all-the-manpages</guid>
<pubDate>Tue, 06 Jun 2023 19:00:00 GMT</pubDate>
</item>
<item>
<title>Writing Your First Kakoune Config (kakrc)</title>
<link>https://blog.trinket.icu/articles/writing-your-first-kakrc</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>
⚠️️ this guide is written as of Kakoune v2022.10.31, future versions may not be compatible with parts of this guide anymore ⚠️
When I first started seriously learning to program, I used a mixture of text-editors and IDE's and really whatever I could get my hands on. I didn't quite know what I was doing.
A rough timeline of me first using text editors
I used Atom (rest in peace, you were loved by some).
I saw someone using Sublime Text and thought it looked very pretty.
Sublime costs money. Never-mind I'm broke.
What's this, Brackets is gorgeous (this is something I maintain to this day. Brackets is the most beautiful text editor but no one knows it).
Oh, Brackets is unmaintained and doesn't work with new frameworks very well :[ EDIT: It is now maintained again, go check it out
Maybe I want to be an iOS developer? omg it takes seven hours to install Xcode (5 of those are just opening the app)
Never-mind, Swift isn't fun anymore, and Xcode serves no other purpose to me.
Woah, this guy in this one YouTube tutorial is using the terminal to edit. How is that even possible?
Oh! It must be Nano. Team Nano!
Wait.. this looks different and there's no syntax highlighting :[
Never-mind, not team Nano anymore.
Ohhh it was Vim. Let's open it up, can't be too hard to use right?
One vim-quitting-induced OS reinstall later
Ok, let's not do that.
What's this hot new thing? VSCode? I've used Visual Studio before, but idk what this is. Let's try it, why not.
And there I was, yet another VSCode dev.
To be clear, there's absolutely nothing wrong with this. The themes are great, the editor runs smoothly (for me), extensions do all the hard work, it's a mostly good experience.
But something in me yearned for more, I needed something new.
To Vim, Neovim, etc.
A video by ThePrimeagen on YouTube was the final catalyst for me, watching him duck and weave through files, never touching the mouse and editing at the speed of thought was inspiring.
I set out to learn Vim.
I quickly switched to Neovim, but eventually gave up and returned to VSCode
I wasn't quite ready for the world of configuration and text file customization. My sudden introduction to it scared me away.
Eventually, I stumbled across Helix configuring Helix is dead-simple. In fact, here's my Helix config right here:
theme = &amp;quot;everforest_dark&amp;quot;
[editor]
middle-click-paste = false
line-number = &amp;quot;relative&amp;quot;
auto-save = true
auto-format = false
bufferline = &amp;quot;always&amp;quot;
color-modes = true
shell = [&amp;quot;zsh&amp;quot;, &amp;quot;-c&amp;quot;]
[editor.statusline]
mode.normal = &amp;quot;NORMAL&amp;quot;
mode.insert = &amp;quot;INSERT&amp;quot;
mode.select = &amp;quot;SELECT&amp;quot;
left = [&amp;quot;mode&amp;quot;, &amp;quot;file-name&amp;quot;, &amp;quot;version-control&amp;quot;]
center = [&amp;quot;spinner&amp;quot;, &amp;quot;position-percentage&amp;quot;, &amp;quot;file-encoding&amp;quot;]
right = [&amp;quot;diagnostics&amp;quot;, &amp;quot;primary-selection-length&amp;quot;, &amp;quot;position&amp;quot;, &amp;quot;file-type&amp;quot;]
[editor.lsp]
auto-signature-help = false
display-signature-help-docs = false
# Remaps
[keys.normal]
A-F = &amp;quot;:fmt&amp;quot;
esc = [&amp;quot;collapse_selection&amp;quot;, &amp;quot;keep_primary_selection&amp;quot;, &amp;quot;:w&amp;quot;]
C-r = [&amp;quot;:reload&amp;quot;]
&amp;quot;{&amp;quot; = &amp;quot;goto_prev_paragraph&amp;quot;
&amp;quot;}&amp;quot; = &amp;quot;goto_next_paragraph&amp;quot;
[keys.normal.space]
space = &amp;quot;goto_next_buffer&amp;quot;
m = &amp;quot;goto_previous_buffer&amp;quot;
q = &amp;quot;:buffer-close&amp;quot;
[keys.select]
&amp;quot;{&amp;quot; = &amp;quot;goto_prev_paragraph&amp;quot;
&amp;quot;}&amp;quot; = &amp;quot;goto_next_paragraph&amp;quot;
[keys.insert]
A-F = &amp;quot;:fmt&amp;quot;
esc = [&amp;quot;normal_mode&amp;quot;, &amp;quot;:w&amp;quot;]
Not very complicated, all things considered
I used Helix for a while, I really liked it a lot.
Eventually, I got good at the keybindings and was a whizz at getting through files just like I had dreamt of.
But the 'batteries included' nature of Helix eventually got to me. It did nearly everything I needed, but the lack of customization via plugins really killed it for me eventually.
Not to mention, the beta software state meant that Helix had a lot of little quirks and bugs that sometimes made using it a pain in the ass.
To Kakoune
I knew Kakoune was the inspiring editor for Helix, and I really did love the keybindings for Helix, so I decided to give it a try.
Well, it was damn good!
Using Kakoune was a much smoother experience, Kakoune was obviously more mature, thought out, and performance-wise I could feel noticeable lag going back to Helix.
The only problem; configuration.
Eventually, I figured it out. I used a combination of other people's config files, trial and error, and reading some of the source code for Kakoune, but eventually I understood the configuration layout well enough to write a config file of my own that serves me well.
Small disclaimer
This guide is for those who already know keybindings in Kakoune, and want a nice configuration file. I'm not going to be going over actually using the editor in detail.
Writing a nice configuration file
Here's what Kakoune looks like by default
pretty damn ugly if I do say so myself
Here's what my current config looks like
That's a marked improvement for me at least
Step-by-step
The basic-basics
When ran, kak will search for the autoload folder(s) and recursively load all .kak files in it. The autoload dir is usually ~/.config/kak/autoload/. Then, kak will search for a kakrc file in your configuration folder (usually ~/.config/kak/kakrc), and load it up.
Let's set that up
mkdir -p ~/.config/kak
kak ~/.config/kak/kakrc
yes, we're using Kakoune to edit it's own config
Tips
Kakoune has a lot of detailed documentation, it's just not very easy to read.
The :doc command gives instant access to every article, it's just not super easy to find what you're for. All the actual docs files can be found on GitHub here
Color scheme
Obviously, the most important thing about a text-editor is it's themes. Let's get something nice going for Kakoune.
In Kakoune, the colorscheme command set's the terminal. You can type :colorscheme and &amp;lt;tab&amp;gt; around to find something you like.
kakrc
colorscheme gruvbox-dark
that should make things nicer
You can reload your kakrc by running :source kakrc. When that doesn't work, just :wq and open it right back up, no biggie.
How's the new color-scheme look?
Let's take a quick detour to talk about scopes
Scopes
global/
First, :doc scopes
According to the docs, there's three options for scopes.
global, buffer, and window
Global
The global scope refers to every linked instance of kak currently running (you can spawn new 'linked' instances of Kakoune with the :new command). Changes you make to the global scope will be available everywhere. If you edit your kakrc, changes will only be available in new session from then on.
Buffer
A buffer is in most cases, just the raw file that is opened. Kakoune has a neat feature called :new that I won't get into, but it allows multiple instances of the same file to be edited at the same time which is wicked cool.
Objects in the buffer scope will affect every instance of that file open in kak
Window
The window scope is the logical subset of the buffer scope. Where the window scope affects all instances of kak with that buffer open, window refers to this instance of this buffer open.
Make sure you understand this to the best of your abilities, scopes are very handy in Kakoune
Line numbers
Something very useful in any sort of text editor is line numbers, fortunately Kakoune offers line numbers as a builtin feature.
Kakoune offers most visual customization through the add-highlightercommand, the docs are at :doc highlighters.
Syntax
add-highlighter [-override] &amp;lt;path&amp;gt;/&amp;lt;name&amp;gt; &amp;lt;type&amp;gt; &amp;lt;parameters&amp;gt; ...
In Kakoune, you can think of highlighters as literal unique objects in the editor, each highlighter is a unique instance with it's own unique scope.
Here's how to add line numbers to Kakoune
add-highlighter global/ number-lines
Let's go over that word-by-word
add-highlighter - the root command to add 'highlighters' to the editor
global/ - the scope of this command
number-lines - the builtin highlighter to apply to the Kakoune look
But wait, did you notice that global has a trailing /?
That's actually another very neat feature of Kakoune.
In kak each highlighter is it's own unique object with it's own ID. This means that the alternate command remove-highlighter exists, you'll see how useful this can be later in this article.
How to use remove-highlighter is an exercise left to the reader for now (:doc is your friend).
Great, but what about /?
In Kakoune, you can set the name of a highlighter , or just let kak pick one for you automagically.
Setting a custom name in Kakoune is what the / is for. For example, here's the equivalent command but with a custom name:
add-highlighter global/number-lines-highlighter number-lines
In this case, our highlighter will be named number-lines-highlighter and that allows us to refer to it in the future.
Unless you know you'll need to refer to a highlighter, I recommend letting Kakoune pick names for you since it will eliminate the risk of accidental name collision.
The trailing / is how you tell Kakoune to pick a name for you.
Getting gnarly
In Kakoune, some highlighters have optional arguments that can be passed to them.
The :docs will always explain this.
Here's the options for number-lines:
-relative
show line numbers relative to the main cursor line
-hlcursor
highlight the cursor line with a separate face
-separator &amp;lt;separator text&amp;gt;
specify a string to separate the line numbers column from the rest of the buffer (default is '|')
-cursor-separator &amp;lt;separator text&amp;gt;
identical to -separator but applies only to the line of the cursor (default is the same value passed to -separator)
-min-digits &amp;lt;num&amp;gt;
always reserve room for at least num digits, so text doesnt jump around as lines are added or removed (default is 2)
Let's apply some of those;
add-highlighter global/ number-lines -hlcursor -relative -separator &amp;quot; &amp;quot; -cursor-separator &amp;quot; |&amp;quot;
Try adding each of those flags one at a time to see what happens. After that you can customize it to your liking.
Going deeper
To read a much more extensive and informative article on highlighters, see here
Matching braces
kak has another useful feature and that's to highlight matching brackets, braces, parentheses, quotes, etc.
The command is
add-highlighter global/ show-matching
Here's a before-and-after to illustrate what that does:
Before
After
Notice how the other bracket was highlighted blue in the second photo.
This feature can be super useful in large codebases, or situations where there's nested blocks in your code.
Pit Stop
Ok, here's our kakrc so far
# custom theme
colorscheme gruvbox-dark
## highlighting
# display line numbers
add-highlighter global/ number-lines -hlcursor -relative -separator &amp;quot; &amp;quot; -cursor-separator &amp;quot; |&amp;quot;
# show matching symbols
add-highlighter global/ show-matching
pretty simple so far
Set-option
:doc options
Syntax
set-option [-add|-remove] &amp;lt;scope&amp;gt; &amp;lt;name&amp;gt; &amp;lt;values&amp;gt;...
Tab-width
Most settings in kak can be accessed though the set-options command.
For example, I like my tabs to be 2 spaces wide, so I'm going to add that to my config like this:
#command #scope #name #value
set-option global tabstop 2
set-option global indentwidth 2
Options don't get names in kak, that's why there's no / after the globalscope.
Scroll-off
In Kakoune, you can specify a margin around the cursor. This is useful because it lets you see the text around a cursor even when editing text at the edges of the window.
# always keep eight lines and three columns displayed around the cursor
set-option global scrolloff 8,3
Keybindings
:doc mapping
The map command is really quite simple. You tell it key a, and keys b and then whenever you type key a, Kakoune will just pretend you typed keys b instead. A bit like an alias.
Syntax
map [switches] &amp;lt;scope&amp;gt; &amp;lt;mode&amp;gt; &amp;lt;key&amp;gt; &amp;lt;keys&amp;gt;
Everything here should be straightforwards except possibly &amp;lt;mode&amp;gt;. I'm not going to get into modes here, since those are something you should already understand if you know vim/kak keybindings.
Here are the modes defined in :doc mapping
insert
insert mode
normal
normal mode
prompt
prompts, such as when entering a command through :, or a regex through /
menu
mode entered when a menu is displayed with the 'menu' command
user
mode entered when the user prefix is hit (default: '&amp;lt;space&amp;gt;')
goto
mode entered when the goto key is hit (default: 'g')
view
mode entered when the view key is hit (default: 'v')
object
mode entered when an object selection is triggered (e.g. '&amp;lt;a-i&amp;gt;')
normal mode maps
qwe
Normally, to navigate word-by-word you'd use the w, b, and e keys to move around. However, I find it more convenient to remap the b to q. That way the keys are qwe and are next to each other on my keyboard.
Here's how to do that
# remap b to q
map global normal q b
# variations of b
map global normal Q B
map global normal &amp;lt;a-q&amp;gt; &amp;lt;a-b&amp;gt;
map global normal &amp;lt;a-Q&amp;gt; &amp;lt;a-B&amp;gt;
Kakoune doesn't have a select mode like Vim or Helix, so we only need to map from normal mode.
Clear selection on&amp;lt;esc&amp;gt;
In kak, pressing &amp;lt;esc&amp;gt; doesn't clear any highlighted text or collapse cursors which doesn't feel intuitive to me. Let's fix that;
# unselect on &amp;lt;esc&amp;gt;
map global normal &amp;lt;esc&amp;gt; &amp;quot;;,&amp;quot;
; un-highlights text, and , gets rid of multiple cursors.
Auto-comment lines
I like to map &amp;lt;c-v&amp;gt; (control+v) to the :comment-line command in Kakoune. This lets me toggle lines really quickly when debugging or refactoring code.
# comment lines
map global normal &amp;lt;c-v&amp;gt; &amp;quot;:comment-line&amp;lt;ret&amp;gt;&amp;quot;
&amp;lt;ret&amp;gt; tells Kakoune to execute the commadn
Normally, I'd map &amp;lt;c-c&amp;gt; to this, but in Kakoune certain key-mappings don't work because of compatibility features (i think), and control+c is one of them. More info here.
user mode maps
user mode is really neat, it allows you to setup a little menu of commands that you access by typing &amp;lt;space&amp;gt; and then the mapping.
Buffer control
Some utilities for navigating buffers
map -docstring &amp;quot;close current buffer&amp;quot; global user b &amp;quot;: db&amp;lt;ret&amp;gt;&amp;quot;
map -docstring &amp;quot;goto previous buffer&amp;quot; global user n &amp;quot;: bp&amp;lt;ret&amp;gt;&amp;quot;
map -docstring &amp;quot;goto next buffer&amp;quot; global user m &amp;quot;: bn&amp;lt;ret&amp;gt;&amp;quot;
-docstring is just the help-text shown for the mapping in the menu
Now, by typing &amp;lt;space&amp;gt;m, &amp;lt;space&amp;gt;n, and &amp;lt;space&amp;gt;b I can go one buffer forwards, back, and close the current buffer respectively.
The more astute among you may have noticed that the commands in that mapping have a space separating the : colon and the actual command. In older versions Kakoune we did this when we didn't want the command saved in the history (access the history by typing : and pressing the up/down arrows). Current and future versions of Kakoune do this automatically, so we don't need to worry about the &amp;lt;space&amp;gt;.
Some more misc. mappings
# fancy insert newline
map -docstring &amp;quot;insert newline above&amp;quot; global user [ &amp;quot;O&amp;lt;esc&amp;gt;j&amp;quot;
map -docstring &amp;quot;insert newline below&amp;quot; global user ] &amp;quot;o&amp;lt;esc&amp;gt;k&amp;quot;
# spellcheck (requires aspell)
map -docstring &amp;quot;check document for spelling&amp;quot; global user w &amp;quot;: spell&amp;lt;ret&amp;gt;&amp;quot;
map -docstring &amp;quot;clear document spelling&amp;quot; global user q &amp;quot;: spell-clear&amp;lt;ret&amp;gt;&amp;quot;
And one more
# copy to system pboard [MAC ONLY]
map -docstring &amp;quot;copy to system pboard&amp;quot; global user y &amp;quot;&amp;lt;a-|&amp;gt; pbcopy&amp;lt;ret&amp;gt;&amp;quot;
&amp;lt;a-|&amp;gt; - the pipe-to command
pbcopy - a shell tool available on macs to manipulate the clipboard
Insert mode autosave
I like it when text-editors autosave. Neovim has this awesome autosave plugin that prints a little log message each time it saves and I want to implement something similar to that as a map.
First, the most basic
map -docstring &amp;quot;save current buffer&amp;quot; global user s &amp;quot;: w&amp;lt;ret&amp;gt;&amp;quot;
But there's no log :(
Also, later we're going to make this something that happens automatically when the user presses &amp;lt;esc&amp;gt; in insert mode.
So let's take a really quick detour to the define-command command, essentially functions in kak.
Custom commands
:doc commands declaring-new-commands
New commands can be defined using the define-command command:
define-command [&amp;lt;switches&amp;gt;] &amp;lt;command_name&amp;gt; &amp;lt;commands&amp;gt;
commands is a string containing the commands to execute, and switches can be any combination of the following parameters:
-params &amp;lt;num&amp;gt;
the command accepts a num parameter, which can be either a number, or of the form &amp;lt;min&amp;gt;..&amp;lt;max&amp;gt;, with both &amp;lt;min&amp;gt; and &amp;lt;max&amp;gt; omittable
-override
allow the new command to replace an existing one with the same name
-hidden
do not show the command in command name completions
-docstring
define the documentation string for the command
-menu
-file-completion
-client-completion
-buffer-completion
-command-completion
-shell-completion
-shell-script-completion
-shell-script-candidates
old-style command completion specification, function as-if the switch and its eventual parameter was passed to the complete-command command (See Configuring command completion)
The use of those switches is discouraged in favor of the complete-command command.
Using shell expansion allows defining complex commands or accessing Kakoune's state:
# create a directory for current buffer if it does not exist
define-command mkdir %{ nop %sh{ mkdir -p $(dirname $kak_buffile) } }
Overall, it's a lot like map. Define a command name, and then some other commands that will be ran.
Save-buffer
Here's my save-buffer command:
define-command save-buffer -docstring &amp;quot;save current buffer and show info&amp;quot; %{
write
info &amp;quot;file saved at %sh{date}&amp;quot;
}
write - save the current buffer (the same thing as :w)
info - infologs a little snipped to the user, try:info &amp;quot;hello, world!&amp;quot;` to see for yourself.
'file saved at %sh{date}' - kak will first expand %sh{date} into the output of the date shell command, and then interpolate that with file saved at before passing it to the info command.
The reason we don't need the : in the %{} block is that Kakoune treats the commands there as just that - commands.
The map command simulates those actual keypresses, so we need to tell the editor to go to prompt mode.
A more complicated example
# open tutor (needs curl)
define-command trampoline -docstring &amp;quot;open a tutorial&amp;quot; %{
evaluate-commands %sh{
tramp_file=$(mktemp -t &amp;quot;kakoune-trampoline.XXXXXXXX&amp;quot;)
echo &amp;quot;edit -fifo $tramp_file *TRAMPOLINE*&amp;quot;
curl -s https://raw.githubusercontent.com/mawww/kakoune/master/contrib/TRAMPOLINE -o &amp;quot;$tramp_file&amp;quot;
}
}
found on the Kakoune forums
Figuring out how this works is an exercise left to the reader.
Plugins
The main reason I switched from Helix to Kakoune was plugins. Helix does not yet have support for plugins, where Kakoune has an incredible ecosystem. Albeit a much smaller one than Vim/Neovim, but personally, I think kak extensions are much easier to write,
In Kakoune, any .kak files in the ~/.config/kak/autoload directory will be loaded, so one way to install extensions is to just clone git repos there.
However
Kakoune has an extremely well made package manager that I highly recommend.
It's called plug.kak.
According to the site there's a few ways to install it, but here's how I like to do it:
mkdir -p $HOME/.config/kak/plugins
git clone https://github.com/andreyorst/plug.kak.git $HOME/.config/kak/plugins/plug.kak
Before we start using it, you should go read the README on the tool's GitHub.
Initializing plug.kak
plug.kak has to be loaded by plug.kak! Kinda trippy I know.
Here's the line to do that:
source &amp;quot;%val{config}/plugins/plug.kak/rc/plug.kak&amp;quot;
plug &amp;quot;andreyorst/plug.kak&amp;quot; noload
This should go before your other plugins in your kakrc.
source just tells kak where to find plug.kak
plug is a special command that plug.kak provides that tells it to make that plugin available to Kakoune, among other things.
Loading plugins
Whenever you add a plugin, you need to reload your kakrc, then you can run the :plug-install command. Read the plug.kak README for a better explanation of all this.
Our first plugin - more themes
I like Gruvbox, I do, but I don't quite like running it 24/7, the colors hurt my eyes. Luckily, the amazing anhsirk0 made a huge collection of amazing themes for Kakoune. Here's the repo for that GitHub.
Unfortunately, the structure of that repo makes it not work super well with plug.kak. Luckily, I made a fork of it that preserves all the themes and makes it work with plug. Link here.
Now, let's get it 'installed'.
# themes
plug &amp;quot;secondary-smiles/kakoune-themes&amp;quot; theme config %{
colorscheme pastel
}
Woah, there's a lot going on there.
plug &amp;quot;secondary-smiles/kakoune-themes&amp;quot; - plug.kak will automagically search github for a plugin if you just provide a username/repo string.
theme - this tells plug.kak that this extension is actually a pack of themes, or just one theme. It will treat the files differently because of that.
config - this is some Kakscript that will be ran only once plug.kak has loaded this extension.
%{ colorscheme pastel } - this will be run once plug.kak loads the extension, it works in a pair with the config keyword. (blocks in Kakoune are defined with %[optional directive]{}).
Well, try and reload your config now, see what you think!
Oh, we should probably remove that colorscheme gruvbox-dark from earlier too, we don't need two themes racing each-other to be dominant in the editor.
Auto-pairs
I might be the weird one out, but I really like auto-pairs when typing. That's where typing a matched character like (, [, &amp;lt;, etc. the editor automatically inserts the opposite character (), ], &amp;gt;, etc.).
Luckily, a plugin exists for just that!
# autopairs
plug &amp;quot;alexherbo2/auto-pairs.kak&amp;quot; config %{
enable-auto-pairs
}
enable-auto-pairs is a command provided by auto-pairs.kak. You can, of course, disable it with :disable-auto-pairs.
Fuzzy-finder
Having a builtin file picker is really useful in any editor. fzf.kak is a really superb implementation of this with a lot of customization abilities.
# fzf
plug &amp;quot;andreyorst/fzf.kak&amp;quot; config %{
require-module fzf
require-module fzf-grep
require-module fzf-file
} defer fzf %{
set-option global fzf_highlight_command &amp;quot;lat -r {}&amp;quot;
} defer fzf-file %{
set-option global fzf_file_command &amp;quot;fd . --no-ignore-vcs&amp;quot;
} defer fzf-grep %{
set-option global fzf_grep_command &amp;quot;fd&amp;quot;
}
If you read the plug.kak README, you'd already understand this.
Let's go over it anyways though.
fzf.kak provides several modules to further customize the plugin.
In the first config block, we require those modules so that they get loaded.
Then, we use the defer &amp;lt;module-name&amp;gt; block to run more commands only after that module is loaded by plug.kak. In this case, I'm using lat (shameless plug) as my default file viewer, and fd as my grepper.
I also like to set &amp;lt;space&amp;gt;f to enter fuzzy-finder mode:
map -docstring &amp;quot;open fzf&amp;quot; global user f &amp;quot;: fzf-mode&amp;lt;ret&amp;gt;&amp;quot;
Powerline
The default Kakoune status-bar leaves a lot to be desired. This plugin adds a lot more customizability.
Read the README for more info on customization
plug &amp;quot;andreyorst/powerline.kak&amp;quot; defer kakoune-themes %{
powerline-theme pastel
} defer powerline %{
powerline-format global &amp;quot;git lsp bufname filetype mode_info lsp line_column position&amp;quot;
set-option global powerline_separator_thin &amp;quot;&amp;quot;
set-option global powerline_separator &amp;quot;&amp;quot;
} config %{
powerline-start
}
Enhanced selection
In Helix, pressing x will select the entire line. Subsequent x's will keep expanding the selection line-by-line. In Kakoune, Subsequent x's do nothing.
byline.kak does exactly that.
In fact, pressing &amp;lt;shift&amp;gt;x will shrink the selection by a line! Very useful.
plug &amp;quot;evanrelf/byline.kak&amp;quot; config %{
require-module &amp;quot;byline&amp;quot;
}
Luar
Some Kakoune plugins are written in Lua, this plugin will allow those ones to run. Adding this plugin is a nice future-proof against plugins randomly break because you forgot this one.
plug &amp;quot;gustavo-hms/luar&amp;quot; %{
require-module luar
}
LSP I
Kakoune has autocomplete out-of-the-box, but now that LSP's are standard, it makes a lot of sense to use them.
There's an extension for that!
plug &amp;quot;kak-lsp/kak-lsp&amp;quot; do %{
cargo install --locked --force --path .
# optional: if you want to use specific language servers
# mkdir -p ~/.config/kak-lsp
# cp -n kak-lsp.toml ~/.config/kak-lsp/
}
The do directive tells plug.kak to run those shell commands only when first installing the plugin.
However, kak-lsp requires a bit more configuration to work properly.
First, read the kak-lsp README (always read the README for everything).
Before finishing lsp, let's learn about hooks;
Hooks
:doc hooks
Hooks in kak are like Events in Javascript, or autocmd in Vim/Neovim.
Basically, you give Kakoune some commands to run, and a trigger. When kak detects that trigger happening, it'll run your commands.
Autosave
Let's finally finish that autosave feature we were working on.
Here's a simple hook to do that:
hook global ModeChange pop:insert:.* %{
save-buffer
}
ModeChange - the hook for whenever the user goes from user to insert or any combination of other modes
ModeChange accepts a string formatted as [push|pop]:&amp;lt;old mode&amp;gt;:&amp;lt;new mode&amp;gt;
pop:insert:.* - this is the filter for the ModeChange hook, let's go over that
pop - this is the kind of mode-change. The options here are pop, push, and .*.
pop - refers to moving out of a mode and into the next one.
push - pushing a command into a mode, for example, pressing &amp;lt;alt&amp;gt;; escapes normal mode for a single command.
.* - wildcard for all
insert - the from mode, or the mode that we're leaving.
.* - the to mode, or the mode that we're going to. This is set to any, as we want to save anytime we exit insert mode
save-buffer - our custom command to save the buffer and log the time.
Soft-wrap in markdown files
Another hook I have enabled is soft-wrapping text in .md files. I find that it makes it a lot easier to edit text (not code) when I can see everything at once and don't have to horizontally-scroll.
hook global WinSetOption filetype=markdown %{
add-highlighter -override global/markdown-wrap wrap -word
hook -once -always window WinSetOption filetype=.* %{
remove-highlighter global/markdown-wrap
}
}
Yeah, you can nest hooks 😎
Figuring out what the nested hook does is an exercise left to the reader.
Lsp II
If you read the kak-lsp README, then this part is going to make a lot of sense.
While it's possible to just blindly enable kak-lsp for everything, I prefer so set hooks for the specific filetypes that I want to be editing.
hook global WinSetOption filetype=(rust|javascript|typescript|c) %{
lsp-enable-window
lsp-inlay-diagnostics-enable global
}
## enable syntax highlighting for each lang
# c
hook global WinSetOption filetype=c %{
hook window -group semantic-tokens BufReload .* lsp-semantic-tokens
hook window -group semantic-tokens NormalIdle .* lsp-semantic-tokens
hook window -group semantic-tokens InsertIdle .* lsp-semantic-tokens
hook -once -always window WinSetOption filetype=.* %{
remove-hooks window semantic-tokens
}
}
# rust
hook global WinSetOption filetype=rust %{
hook window -group semantic-tokens BufReload .* lsp-semantic-tokens
hook window -group semantic-tokens NormalIdle .* lsp-semantic-tokens
hook window -group semantic-tokens InsertIdle .* lsp-semantic-tokens
hook -once -always window WinSetOption filetype=.* %{
remove-hooks window semantic-tokens
}
}
# typescript
hook global WinSetOption filetype=typescript %{
hook window -group semantic-tokens BufReload .* lsp-semantic-tokens
hook window -group semantic-tokens NormalIdle .* lsp-semantic-tokens
hook window -group semantic-tokens InsertIdle .* lsp-semantic-tokens
hook -once -always window WinSetOption filetype=.* %{
remove-hooks window semantic-tokens
}
}
# javascript
hook global WinSetOption filetype=javascript %{
hook window -group semantic-tokens BufReload .* lsp-semantic-tokens
hook window -group semantic-tokens NormalIdle .* lsp-semantic-tokens
hook window -group semantic-tokens InsertIdle .* lsp-semantic-tokens
hook -once -always window WinSetOption filetype=.* %{
remove-hooks window semantic-tokens
}
}
If you read the comments, you'll also notice that we enabled better syntax highlighting for each of those filetypes as well.
I also like to set a mapping to user mode to let me access the lsp menu really quickly:
map -docstring &amp;quot;open lsp&amp;quot; global user l &amp;quot;: enter-user-mode lsp&amp;lt;ret&amp;gt;&amp;quot;
Some extensions create their own special menus like the one that &amp;lt;space&amp;gt; creates. We access those with the :enter-user-mode command.
Now, &amp;lt;space&amp;gt;lf will perform lsp-assisted formatting!
Tab completion
I don't like the &amp;lt;c-n&amp;gt;, &amp;lt;c-p&amp;gt; convention for selecting autocomplete items.
This is the recommended hook (according to the Kakoune wiki) for enabling &amp;lt;tab&amp;gt; and &amp;lt;shift&amp;gt;&amp;lt;tab&amp;gt; selections.
# tabs for autocomplete
hook global InsertCompletionShow .* %{
try %{
# this command temporarily removes cursors preceded by whitespace;
# if there are no cursors left, it raises an error, does not
# continue to execute the mapping commands, and the error is eaten
# by the `try` command so no warning appears.
execute-keys -draft 'h&amp;lt;a-K&amp;gt;\h&amp;lt;ret&amp;gt;'
map window insert &amp;lt;tab&amp;gt; &amp;lt;c-n&amp;gt;
map window insert &amp;lt;s-tab&amp;gt; &amp;lt;c-p&amp;gt;
hook -once -always window InsertCompletionHide .* %{
unmap window insert &amp;lt;tab&amp;gt; &amp;lt;c-n&amp;gt;
unmap window insert &amp;lt;s-tab&amp;gt; &amp;lt;c-p&amp;gt;
}
}
}
LSP III
To learn more about creating custom completion tools in Kakoune see here.
Goodbye clippy
You probably noticed that clippy appears a lot in Kakoune
╭──╮
│ │
@ @ ╭
││ ││ │
││ ││ ╯
│╰─╯│
╰───╯
this mf
Well, a not-so-secret easter egg in Kakoune is that it's possible to change the assistant!
Here's how to remove clippy altogether
set-option global ui_options terminal_assistant=none
Available options are clippy, dilbert, cat, and none. Try setting each of those, something interesting might happen ;D
Wrapping up
My current, mostly up-to-date kakrc can be found on my github .dots.
Kakoune is an incredible editor, I've really never had this much fun in a text editor, and for me it just feels so good using a punk-rock editor.
This article isn't an introduction to terminal-editors, but if you're interested in the field, YouTube is a great starting place.
Also check out the Kakoune Forums for infinite kak tips and tricks.
Thanks for reading!
</description>
<content:encoded><![CDATA[<blockquote>
<p><strong>⚠️️ this guide is written as of Kakoune v2022.10.31, future versions may not be compatible with parts of this guide anymore ⚠️</strong></p>
</blockquote>
<p>When I first started seriously learning to program, I used a mixture of text-editors and IDE's and really whatever I could get my hands on. I didn't quite know what I was doing.</p>
<h2>A rough timeline of me first using text editors</h2>
<ul>
<li>I used <a href="https://atom.io">Atom</a> <em>(rest in peace, you were loved by some)</em>.</li>
<li>I saw someone using <a href="https://www.sublimetext.com/">Sublime Text</a> and thought it looked very pretty.</li>
<li>Sublime costs money. Never-mind I'm broke.</li>
<li>What's this, <a href="https://brackets.io/">Brackets</a> is <em>gorgeous</em> (this is something I maintain to this day. Brackets is the most beautiful text editor but no one knows it).</li>
<li>Oh, Brackets is unmaintained and doesn't work with new frameworks very well :[ <code>EDIT: It is now maintained again, go check it out</code></li>
<li>Maybe I want to be an iOS developer? omg it takes seven hours to install <a href="https://developer.apple.com/xcode/">Xcode</a> (5 of those are just opening the app)</li>
<li>Never-mind, <a href="https://www.swift.org/">Swift</a> isn't fun anymore, and Xcode serves no other purpose to me.</li>
<li>Woah, this guy in this one YouTube tutorial is using <em>the terminal</em> to edit. How is that even possible?</li>
<li>Oh! It must be <a href="https://www.nano-editor.org/">Nano</a>. Team Nano!</li>
<li>Wait.. this looks different and there's no syntax highlighting :[</li>
<li>Never-mind, not team Nano anymore.</li>
<li>Ohhh it was <a href="https://www.vim.org/">Vim</a>. Let's open it up, can't be too hard to use right?</li>
<li><em>One vim-quitting-induced OS reinstall later</em></li>
<li>Ok, let's not do that.</li>
<li>What's this hot new thing? <a href="https://code.visualstudio.com/">VSCode</a>? I've used <a href="https://visualstudio.microsoft.com/">Visual Studio</a> before, but idk what this is. Let's try it, why not.</li>
</ul>
<p>And there I was, yet another VSCode dev.
To be clear, there's absolutely nothing wrong with this. The themes are great, the editor runs smoothly (for me), extensions do all the hard work, it's a mostly good experience.
But something in me yearned for more, I needed something new.</p>
<h2>To <a href="https://www.vim.org/">Vim</a>, <a href="https://neovim.io">Neovim</a>, etc.</h2>
<p>A video by <a href="https://www.youtube.com/@ThePrimeagen">ThePrimeagen</a> on YouTube was the final catalyst for me, watching him duck and weave through files, never touching the mouse and editing at the speed of thought was inspiring.</p>
<ul>
<li>I set out to learn Vim.</li>
<li>I quickly switched to <a href="https://neovim.io/">Neovim</a>, but eventually gave up and returned to VSCode
I wasn't quite ready for the world of configuration and text file customization. My sudden introduction to it scared me away.</li>
</ul>
<p>Eventually, I stumbled across <a href="https://helix-editor.com/">Helix</a> configuring Helix is dead-simple. In fact, here's my Helix config right here:</p>
<pre><code class="language-toml">theme = &quot;everforest_dark&quot;
[editor]
middle-click-paste = false
line-number = &quot;relative&quot;
auto-save = true
auto-format = false
bufferline = &quot;always&quot;
color-modes = true
shell = [&quot;zsh&quot;, &quot;-c&quot;]
[editor.statusline]
mode.normal = &quot;NORMAL&quot;
mode.insert = &quot;INSERT&quot;
mode.select = &quot;SELECT&quot;
left = [&quot;mode&quot;, &quot;file-name&quot;, &quot;version-control&quot;]
center = [&quot;spinner&quot;, &quot;position-percentage&quot;, &quot;file-encoding&quot;]
right = [&quot;diagnostics&quot;, &quot;primary-selection-length&quot;, &quot;position&quot;, &quot;file-type&quot;]
[editor.lsp]
auto-signature-help = false
display-signature-help-docs = false
# Remaps
[keys.normal]
A-F = &quot;:fmt&quot;
esc = [&quot;collapse_selection&quot;, &quot;keep_primary_selection&quot;, &quot;:w&quot;]
C-r = [&quot;:reload&quot;]
&quot;{&quot; = &quot;goto_prev_paragraph&quot;
&quot;}&quot; = &quot;goto_next_paragraph&quot;
[keys.normal.space]
space = &quot;goto_next_buffer&quot;
m = &quot;goto_previous_buffer&quot;
q = &quot;:buffer-close&quot;
[keys.select]
&quot;{&quot; = &quot;goto_prev_paragraph&quot;
&quot;}&quot; = &quot;goto_next_paragraph&quot;
[keys.insert]
A-F = &quot;:fmt&quot;
esc = [&quot;normal_mode&quot;, &quot;:w&quot;]
</code></pre>
<blockquote>
<p>Not very complicated, all things considered</p>
</blockquote>
<p>I used Helix for a while, I really liked it a lot.
Eventually, I got good at the keybindings and was a whizz at getting through files just like I had dreamt of.
But the 'batteries included' nature of Helix eventually got to me. It did nearly everything I needed, but the lack of customization via plugins really killed it for me eventually.
Not to mention, the beta software state meant that Helix had a lot of little quirks and bugs that sometimes made using it a pain in the ass.</p>
<h2>To <a href="https://kakoune.org/">Kakoune</a></h2>
<p>I knew <a href="https://kakoune.org/">Kakoune</a> was the inspiring editor for Helix, and I really did love the keybindings for Helix, so I decided to give it a try.
Well, it was damn good!
Using Kakoune was a much smoother experience, Kakoune was obviously more mature, thought out, and performance-wise I could feel noticeable lag going back to Helix.
The only problem; configuration.
Eventually, I figured it out. I used a combination of other people's config files, trial and error, and reading some of the source code for Kakoune, but eventually I understood the configuration layout well enough to write a config file of my own that serves me well.</p>
<h2>Small disclaimer</h2>
<p>This guide is for those who already know keybindings in Kakoune, and want a nice configuration file. I'm not going to be going over actually using the editor in detail.</p>
<h2>Writing a nice configuration file</h2>
<p>Here's what Kakoune looks like by default
<img src="https://i.imgur.com/DArA8Jy.png" alt="default kakrc"></p>
<blockquote>
<p>pretty damn ugly if I do say so myself</p>
</blockquote>
<p>Here's what my current config looks like
<img src="https://i.imgur.com/h3wlERq.png" alt="default kakrc"></p>
<blockquote>
<p>That's a marked improvement for me at least</p>
</blockquote>
<h2>Step-by-step</h2>
<h3>The basic-basics</h3>
<p>When ran, <code>kak</code> will search for the autoload folder(s) and recursively load all <code>.kak</code> files in it. The <code>autoload</code> dir is usually <code>~/.config/kak/autoload/</code>. Then, <code>kak</code> will search for a <code>kakrc</code> file in your configuration folder (usually <code>~/.config/kak/kakrc</code>), and load it up.</p>
<p>Let's set that up</p>
<pre><code class="language-bash">mkdir -p ~/.config/kak
kak ~/.config/kak/kakrc
</code></pre>
<blockquote>
<p>yes, we're using Kakoune to edit it's own config</p>
</blockquote>
<h3>Tips</h3>
<p>Kakoune has a lot of detailed documentation, it's just not very easy to read.
The <code>:doc</code> command gives instant access to every article, it's just not super easy to find what you're for. All the actual docs files can be found on GitHub <a href="https://github.com/mawww/kakoune/tree/master/doc">here</a></p>
<h3>Color scheme</h3>
<p>Obviously, the most important thing about a text-editor is it's themes. Let's get something nice going for Kakoune.</p>
<p>In Kakoune, the <code>colorscheme</code> command set's the terminal. You can type <code>:colorscheme </code> and <code>&lt;tab&gt;</code> around to find something you like.</p>
<p><code>kakrc</code></p>
<pre><code class="language-vim">colorscheme gruvbox-dark
</code></pre>
<blockquote>
<p>that should make things nicer</p>
</blockquote>
<p>You can reload your <code>kakrc</code> by running <code>:source kakrc</code>. When that doesn't work, just <code>:wq</code> and open it right back up, no biggie.
<em>How's the new color-scheme look?</em></p>
<p><strong>Let's take a quick detour to talk about scopes</strong></p>
<h3>Scopes</h3>
<blockquote>
<p><code>global/</code></p>
</blockquote>
<p>First, <code>:doc scopes</code></p>
<p>According to the docs, there's three options for scopes.
<code>global</code>, <code>buffer</code>, and <code>window</code></p>
<h5>Global</h5>
<p>The <code>global</code> scope refers to every linked instance of <code>kak</code> currently running (you can spawn new 'linked' instances of Kakoune with the <code>:new</code> command). Changes you make to the <code>global</code> scope will be available everywhere. If you edit your <code>kakrc</code>, changes will only be available in new session from then on.</p>
<h5>Buffer</h5>
<p>A buffer is in most cases, just the raw file that is opened. Kakoune has a neat feature called <code>:new</code> that I won't get into, but it allows multiple instances of the same file to be edited at the same time which is wicked cool.
Objects in the <code>buffer</code> scope will affect every instance of that file open in <code>kak</code></p>
<h5>Window</h5>
<p>The <code>window</code> scope is the logical subset of the <code>buffer</code> scope. Where the <code>window</code> scope affects all instances of <code>kak</code> with that buffer open, <code>window</code> refers to <em>this</em> instance of <em>this</em> buffer open.</p>
<p>Make sure you understand this to the best of your abilities, <code>scopes</code> are <em>very</em> handy in Kakoune</p>
<h3>Line numbers</h3>
<p>Something very useful in any sort of text editor is line numbers, fortunately Kakoune offers line numbers as a builtin feature.</p>
<p>Kakoune offers most visual customization through the <code>add-highlighter</code>command, the docs are at <code>:doc highlighters</code>.</p>
<h4>Syntax</h4>
<p><code>add-highlighter [-override] &lt;path&gt;/&lt;name&gt; &lt;type&gt; &lt;parameters&gt; ...</code></p>
<p>In Kakoune, you can think of highlighters as literal unique objects in the editor, each highlighter is a unique instance with it's own unique scope.</p>
<p>Here's how to add line numbers to Kakoune</p>
<pre><code class="language-vim">add-highlighter global/ number-lines
</code></pre>
<p>Let's go over that word-by-word</p>
<ul>
<li><code>add-highlighter</code> - the root command to add 'highlighters' to the editor</li>
<li><code>global/</code> - the scope of this command</li>
<li><code>number-lines</code> - the builtin highlighter to apply to the Kakoune look</li>
</ul>
<p>But wait, did you notice that <code>global</code> has a trailing <code>/</code>?
That's actually another very neat feature of Kakoune.</p>
<p>In <code>kak</code> each <code>highlighter</code> is it's own unique object with it's own ID. This means that the alternate command <code>remove-highlighter</code> exists, you'll see how useful this can be later in this article.
How to use <code>remove-highlighter</code> is an exercise left to the reader for now (<code>:doc</code> is your friend).</p>
<h4>Great, but what about <code>/</code>?</h4>
<p>In Kakoune, you can set the name of a <code>highlighter</code> , or just let <code>kak</code> pick one for you automagically.
Setting a custom name in Kakoune is what the <code>/</code> is for. For example, here's the equivalent command but with a custom name:</p>
<pre><code class="language-vim">add-highlighter global/number-lines-highlighter number-lines
</code></pre>
<p>In this case, our highlighter will be named <code>number-lines-highlighter</code> and that allows us to refer to it in the future.
Unless you know you'll need to refer to a <code>highlighter</code>, I recommend letting Kakoune pick names for you since it will eliminate the risk of accidental name collision.</p>
<p>The trailing <code>/</code> is how you tell Kakoune to pick a name for you.</p>
<h4>Getting gnarly</h4>
<p>In Kakoune, some <code>highlighters</code> have optional arguments that can be passed to them.
The <code>:docs</code> will always explain this.
Here's the options for <code>number-lines</code>:</p>
<pre><code class="language-text">-relative
show line numbers relative to the main cursor line
-hlcursor
highlight the cursor line with a separate face
-separator &lt;separator text&gt;
specify a string to separate the line numbers column from the rest of the buffer (default is '|')
-cursor-separator &lt;separator text&gt;
identical to -separator but applies only to the line of the cursor (default is the same value passed to -separator)
-min-digits &lt;num&gt;
always reserve room for at least num digits, so text doesnt jump around as lines are added or removed (default is 2)
</code></pre>
<p>Let's apply some of those;</p>
<pre><code class="language-vim">add-highlighter global/ number-lines -hlcursor -relative -separator &quot; &quot; -cursor-separator &quot; |&quot;
</code></pre>
<p>Try adding each of those flags one at a time to see what happens. After that you can customize it to your liking.</p>
<h4>Going deeper</h4>
<p>To read a much more extensive and informative article on <code>highlighters</code>, see <a href="https://zork.net/~st/jottings/Intro_to_Kakoune_highlighters.html">here</a></p>
<h3>Matching braces</h3>
<p><code>kak</code> has another useful feature and that's to highlight matching brackets, braces, parentheses, quotes, etc.</p>
<p>The command is</p>
<pre><code class="language-vim">add-highlighter global/ show-matching
</code></pre>
<p>Here's a before-and-after to illustrate what that does:</p>
<p><strong>Before</strong></p>
<p><img src="https://i.imgur.com/oZotdaR.png" alt="show-matching-before"></p>
<p><strong>After</strong></p>
<p><img src="https://i.imgur.com/5A6A4XY.png" alt="show-matching-before"></p>
<p>Notice how the other bracket was highlighted blue in the second photo.
This feature can be super useful in large codebases, or situations where there's nested blocks in your code.</p>
<h3>Pit Stop</h3>
<p>Ok, here's our <code>kakrc</code> so far</p>
<pre><code class="language-vim"># custom theme
colorscheme gruvbox-dark
## highlighting
# display line numbers
add-highlighter global/ number-lines -hlcursor -relative -separator &quot; &quot; -cursor-separator &quot; |&quot;
# show matching symbols
add-highlighter global/ show-matching
</code></pre>
<blockquote>
<p>pretty simple so far</p>
</blockquote>
<h3>Set-option</h3>
<p><code>:doc options</code></p>
<h4>Syntax</h4>
<p><code>set-option [-add|-remove] &lt;scope&gt; &lt;name&gt; &lt;values&gt;...</code></p>
<h4>Tab-width</h4>
<p>Most settings in <code>kak</code> can be accessed though the <code>set-options</code> command.
For example, I like my tabs to be 2 spaces wide, so I'm going to add that to my config like this:</p>
<pre><code class="language-vim">#command #scope #name #value
set-option global tabstop 2
set-option global indentwidth 2
</code></pre>
<blockquote>
<p>Options don't get names in <code>kak</code>, that's why there's no <code>/</code> after the <code>global</code>scope.</p>
</blockquote>
<h4>Scroll-off</h4>
<p>In Kakoune, you can specify a margin around the cursor. This is useful because it lets you see the text around a cursor even when editing text at the edges of the window.</p>
<pre><code class="language-vim"># always keep eight lines and three columns displayed around the cursor
set-option global scrolloff 8,3
</code></pre>
<h3>Keybindings</h3>
<p><code>:doc mapping</code></p>
<p>The <code>map</code> command is really quite simple. You tell it <code>key a</code>, and <code>keys b</code> and then whenever you type <code>key a</code>, Kakoune will just pretend you typed <code>keys b</code> instead. A bit like an alias.</p>
<h4>Syntax</h4>
<p><code>map [switches] &lt;scope&gt; &lt;mode&gt; &lt;key&gt; &lt;keys&gt;</code></p>
<p>Everything here should be straightforwards except possibly <code>&lt;mode&gt;</code>. I'm not going to get into <code>modes</code> here, since those are something you should already understand if you know <code>vim/kak</code> keybindings.</p>
<p>Here are the modes defined in <code>:doc mapping</code></p>
<pre><code class="language-text">insert
insert mode
normal
normal mode
prompt
prompts, such as when entering a command through :, or a regex through /
menu
mode entered when a menu is displayed with the 'menu' command
user
mode entered when the user prefix is hit (default: '&lt;space&gt;')
goto
mode entered when the goto key is hit (default: 'g')
view
mode entered when the view key is hit (default: 'v')
object
mode entered when an object selection is triggered (e.g. '&lt;a-i&gt;')
</code></pre>
<h4><code>normal</code> mode maps</h4>
<h5><code>qwe</code></h5>
<p>Normally, to navigate word-by-word you'd use the <code>w</code>, <code>b</code>, and <code>e</code> keys to move around. However, I find it more convenient to remap the <code>b</code> to <code>q</code>. That way the keys are <code>qwe</code> and are next to each other on my keyboard.
Here's how to do that</p>
<pre><code class="language-vim"># remap b to q
map global normal q b
# variations of b
map global normal Q B
map global normal &lt;a-q&gt; &lt;a-b&gt;
map global normal &lt;a-Q&gt; &lt;a-B&gt;
</code></pre>
<p>Kakoune doesn't have a <code>select</code> mode like Vim or Helix, so we only need to map from <code>normal</code> mode.</p>
<h5>Clear selection on<code>&lt;esc&gt;</code></h5>
<p>In <code>kak</code>, pressing <code>&lt;esc&gt;</code> doesn't clear any highlighted text or collapse cursors which doesn't feel intuitive to me. Let's fix that;</p>
<pre><code class="language-vim"># unselect on &lt;esc&gt;
map global normal &lt;esc&gt; &quot;;,&quot;
</code></pre>
<p><code>;</code> un-highlights text, and <code>,</code> gets rid of multiple cursors.</p>
<h5>Auto-comment lines</h5>
<p>I like to map <code>&lt;c-v&gt;</code> (control+v) to the <code>:comment-line</code> command in Kakoune. This lets me toggle lines really quickly when debugging or refactoring code.</p>
<pre><code class="language-vim"># comment lines
map global normal &lt;c-v&gt; &quot;:comment-line&lt;ret&gt;&quot;
</code></pre>
<blockquote>
<p><code>&lt;ret&gt;</code> tells Kakoune to execute the commadn</p>
</blockquote>
<p>Normally, I'd map <code>&lt;c-c&gt;</code> to this, but in Kakoune certain key-mappings don't work because of compatibility features (i think), and control+c is one of them. More info <a href="https://github.com/mawww/kakoune/issues/797#issuecomment-649494417">here</a>.</p>
<h4><code>user</code> mode maps</h4>
<p><code>user</code> mode is really neat, it allows you to setup a little menu of commands that you access by typing <code>&lt;space&gt;</code> and then the mapping.</p>
<h5>Buffer control</h5>
<p>Some utilities for navigating buffers</p>
<pre><code class="language-vim">map -docstring &quot;close current buffer&quot; global user b &quot;: db&lt;ret&gt;&quot;
map -docstring &quot;goto previous buffer&quot; global user n &quot;: bp&lt;ret&gt;&quot;
map -docstring &quot;goto next buffer&quot; global user m &quot;: bn&lt;ret&gt;&quot;
</code></pre>
<blockquote>
<p><code>-docstring</code> is just the help-text shown for the mapping in the menu</p>
</blockquote>
<p>Now, by typing <code>&lt;space&gt;m</code>, <code>&lt;space&gt;n</code>, and <code>&lt;space&gt;b</code> I can go one buffer forwards, back, and close the current buffer respectively.</p>
<p>The more astute among you may have noticed that the commands in that mapping have a space separating the <code>:</code> colon and the actual command. In older versions Kakoune we did this when we didn't want the command saved in the history (access the history by typing <code>:</code> and pressing the up/down arrows). Current and future versions of Kakoune do this automatically, so we don't need to worry about the <code>&lt;space&gt;</code>.</p>
<h5>Some more misc. mappings</h5>
<pre><code class="language-vim"># fancy insert newline
map -docstring &quot;insert newline above&quot; global user [ &quot;O&lt;esc&gt;j&quot;
map -docstring &quot;insert newline below&quot; global user ] &quot;o&lt;esc&gt;k&quot;
# spellcheck (requires aspell)
map -docstring &quot;check document for spelling&quot; global user w &quot;: spell&lt;ret&gt;&quot;
map -docstring &quot;clear document spelling&quot; global user q &quot;: spell-clear&lt;ret&gt;&quot;
</code></pre>
<h5>And one more</h5>
<pre><code class="language-vim"># copy to system pboard [MAC ONLY]
map -docstring &quot;copy to system pboard&quot; global user y &quot;&lt;a-|&gt; pbcopy&lt;ret&gt;&quot;
</code></pre>
<ul>
<li><code>&lt;a-|&gt;</code> - the <em>pipe-to</em> command</li>
<li><code>pbcopy</code> - a shell tool available on macs to manipulate the clipboard</li>
</ul>
<h4>Insert mode autosave</h4>
<p>I like it when text-editors autosave. Neovim has this awesome autosave plugin that prints a little log message each time it saves and I want to implement something similar to that as a <code>map</code>.</p>
<p>First, the most basic</p>
<pre><code class="language-vim">map -docstring &quot;save current buffer&quot; global user s &quot;: w&lt;ret&gt;&quot;
</code></pre>
<p>But there's no log :(
Also, later we're going to make this something that happens automatically when the user presses <code>&lt;esc&gt;</code> in <code>insert</code> mode.</p>
<p>So let's take a really quick detour to the <code>define-command</code> command, essentially functions in <code>kak</code>.</p>
<h3>Custom commands</h3>
<p><code>:doc commands declaring-new-commands</code></p>
<pre><code class="language-text">New commands can be defined using the define-command command:
define-command [&lt;switches&gt;] &lt;command_name&gt; &lt;commands&gt;
commands is a string containing the commands to execute, and switches can be any combination of the following parameters:
-params &lt;num&gt;
the command accepts a num parameter, which can be either a number, or of the form &lt;min&gt;..&lt;max&gt;, with both &lt;min&gt; and &lt;max&gt; omittable
-override
allow the new command to replace an existing one with the same name
-hidden
do not show the command in command name completions
-docstring
define the documentation string for the command
-menu
-file-completion
-client-completion
-buffer-completion
-command-completion
-shell-completion
-shell-script-completion
-shell-script-candidates
old-style command completion specification, function as-if the switch and its eventual parameter was passed to the complete-command command (See Configuring command completion)
The use of those switches is discouraged in favor of the complete-command command.
Using shell expansion allows defining complex commands or accessing Kakoune's state:
# create a directory for current buffer if it does not exist
define-command mkdir %{ nop %sh{ mkdir -p $(dirname $kak_buffile) } }
</code></pre>
<p>Overall, it's a lot like <code>map</code>. Define a command name, and then some other commands that will be ran.</p>
<h4>Save-buffer</h4>
<p>Here's my <code>save-buffer</code> command:</p>
<pre><code class="language-vim">define-command save-buffer -docstring &quot;save current buffer and show info&quot; %{
write
info &quot;file saved at %sh{date}&quot;
}
</code></pre>
<ul>
<li><code>write</code> - save the current buffer (the same thing as <code>:w</code>)</li>
<li><code>info - </code>info<code>logs a little snipped to the user, try</code>:info &quot;hello, world!&quot;` to see for yourself.</li>
<li><code>'file saved at %sh{date}'</code> - <code>kak</code> will first expand <code>%sh{date}</code> into the output of the <code>date</code> shell command, and then interpolate that with <code>file saved at </code> before passing it to the <code>info</code> command.</li>
</ul>
<p>The reason we don't need the <code>:</code> in the <code>%{}</code> block is that Kakoune treats the commands there as just that - commands.
The <code>map</code> command simulates those actual keypresses, so we need to tell the editor to go to <code>prompt</code> mode.</p>
<h4>A more complicated example</h4>
<pre><code class="language-vim"># open tutor (needs curl)
define-command trampoline -docstring &quot;open a tutorial&quot; %{
evaluate-commands %sh{
tramp_file=$(mktemp -t &quot;kakoune-trampoline.XXXXXXXX&quot;)
echo &quot;edit -fifo $tramp_file *TRAMPOLINE*&quot;
curl -s https://raw.githubusercontent.com/mawww/kakoune/master/contrib/TRAMPOLINE -o &quot;$tramp_file&quot;
}
}
</code></pre>
<blockquote>
<p>found on the <a href="https://discuss.kakoune.com/">Kakoune forums</a></p>
</blockquote>
<p>Figuring out how this works is an exercise left to the reader.</p>
<h3>Plugins</h3>
<p>The main reason I switched from Helix to Kakoune was plugins. Helix does not yet have support for plugins, where Kakoune has an incredible ecosystem. Albeit a much smaller one than Vim/Neovim, but personally, I think <code>kak</code> extensions are much easier to write,</p>
<p>In Kakoune, any <code>.kak</code> files in the <code>~/.config/kak/autoload</code> directory will be loaded, so one way to install extensions is to just clone git repos there.</p>
<p><strong>However</strong></p>
<p>Kakoune has an extremely well made package manager that I highly recommend.
It's called <a href="https://github.com/andreyorst/plug.kak">plug.kak</a>.</p>
<p>According to the site there's a few ways to install it, but here's how I like to do it:</p>
<pre><code class="language-bash">mkdir -p $HOME/.config/kak/plugins
git clone https://github.com/andreyorst/plug.kak.git $HOME/.config/kak/plugins/plug.kak
</code></pre>
<p>Before we start using it, you should go read the <code>README</code> on the tool's <a href="https://github.com/andreyorst/plug.kak">GitHub</a>.</p>
<h4>Initializing <code>plug.kak</code></h4>
<p><code>plug.kak</code> has to be loaded by <code>plug.kak</code>! Kinda trippy I know.
Here's the line to do that:</p>
<pre><code class="language-vim">source &quot;%val{config}/plugins/plug.kak/rc/plug.kak&quot;
plug &quot;andreyorst/plug.kak&quot; noload
</code></pre>
<p>This should go before your other plugins in your <code>kakrc</code>.</p>
<ul>
<li><code>source</code> just tells <code>kak</code> where to find <code>plug.kak</code></li>
<li><code>plug</code> is a special command that <code>plug.kak</code> provides that tells it to make that plugin available to Kakoune, among other things.</li>
</ul>
<h4>Loading plugins</h4>
<p>Whenever you add a plugin, you need to reload your <code>kakrc</code>, then you can run the <code>:plug-install</code> command. Read the <code>plug.kak</code> <a href="https://github.com/andreyorst/plug.kak">README</a> for a better explanation of all this.</p>
<h4>Our first plugin - more themes</h4>
<p>I like Gruvbox, I do, but I don't quite like running it 24/7, the colors hurt my eyes. Luckily, the amazing <code>anhsirk0</code> made a huge collection of amazing themes for Kakoune. Here's the repo for that <a href="https://github.com/anhsirk0/kakoune-themes">GitHub</a>.
Unfortunately, the structure of that repo makes it not work super well with <code>plug.kak</code>. Luckily, I made a fork of it that preserves all the themes and makes it work with <code>plug</code>. <a href="https://github.com/secondary-smiles/kakoune-themes">Link here</a>.</p>
<p>Now, let's get it 'installed'.</p>
<pre><code class="language-vim"># themes
plug &quot;secondary-smiles/kakoune-themes&quot; theme config %{
colorscheme pastel
}
</code></pre>
<blockquote>
<p>Woah, there's a lot going on there.</p>
</blockquote>
<ul>
<li><code>plug &quot;secondary-smiles/kakoune-themes&quot;</code> - <code>plug.kak</code> will automagically search github for a plugin if you just provide a <em>username/repo</em> string.</li>
<li><code>theme</code> - this tells <code>plug.kak</code> that this extension is actually a pack of themes, or just one theme. It will treat the files differently because of that.</li>
<li><code>config</code> - this is some <code>Kakscript</code> that will be ran only once <code>plug.kak</code> has loaded this extension.</li>
<li><code>%{ colorscheme pastel }</code> - this will be run once <code>plug.kak</code> loads the extension, it works in a pair with the <code>config</code> keyword. (blocks in Kakoune are defined with <code>%[optional directive]{}</code>).</li>
</ul>
<p>Well, try and reload your config now, see what you think!</p>
<p>Oh, we should probably remove that <code>colorscheme gruvbox-dark</code> from earlier too, we don't need two themes racing each-other to be dominant in the editor.</p>
<h4>Auto-pairs</h4>
<p>I might be the weird one out, but I really like auto-pairs when typing. That's where typing a matched character like <code>(</code>, <code>[</code>, <code>&lt;</code>, etc. the editor automatically inserts the opposite character (<code>)</code>, <code>]</code>, <code>&gt;</code>, etc.).
Luckily, a plugin exists for just that!</p>
<pre><code class="language-vim"># autopairs
plug &quot;alexherbo2/auto-pairs.kak&quot; config %{
enable-auto-pairs
}
</code></pre>
<p><code>enable-auto-pairs</code> is a command provided by <code>auto-pairs.kak</code>. You can, of course, disable it with <code>:disable-auto-pairs</code>.</p>
<h4>Fuzzy-finder</h4>
<p>Having a builtin file picker is really useful in any editor. <a href="https://github.com/andreyorst/fzf.kak"><code>fzf.kak</code></a> is a really superb implementation of this with a lot of customization abilities.</p>
<pre><code class="language-vim"># fzf
plug &quot;andreyorst/fzf.kak&quot; config %{
require-module fzf
require-module fzf-grep
require-module fzf-file
} defer fzf %{
set-option global fzf_highlight_command &quot;lat -r {}&quot;
} defer fzf-file %{
set-option global fzf_file_command &quot;fd . --no-ignore-vcs&quot;
} defer fzf-grep %{
set-option global fzf_grep_command &quot;fd&quot;
}
</code></pre>
<p>If you read the <code>plug.kak</code> <code>README</code>, you'd already understand this.
Let's go over it anyways though.</p>
<p><code>fzf.kak</code> provides several modules to further customize the plugin.</p>
<p>In the first <code>config</code> block, we <code>require</code> those modules so that they get loaded.</p>
<p>Then, we use the <code>defer &lt;module-name&gt;</code> block to run more commands only <em>after</em> that module is loaded by <code>plug.kak</code>. In this case, I'm using <a href="https://github.com/secondary-smiles/lat"><code>lat</code></a> (<em>shameless plug</em>) as my default file viewer, and <a href="https://github.com/sharkdp/fd"><code>fd</code></a> as my grepper.</p>
<p>I also like to set <code>&lt;space&gt;f</code> to enter fuzzy-finder mode:</p>
<pre><code class="language-vim">map -docstring &quot;open fzf&quot; global user f &quot;: fzf-mode&lt;ret&gt;&quot;
</code></pre>
<h4>Powerline</h4>
<p>The default Kakoune status-bar leaves a lot to be desired. This plugin adds a lot more customizability.</p>
<p>Read the <a href="https://github.com/andreyorst/powerline.kak">README</a> for more info on customization</p>
<pre><code class="language-vim">plug &quot;andreyorst/powerline.kak&quot; defer kakoune-themes %{
powerline-theme pastel
} defer powerline %{
powerline-format global &quot;git lsp bufname filetype mode_info lsp line_column position&quot;
set-option global powerline_separator_thin &quot;&quot;
set-option global powerline_separator &quot;&quot;
} config %{
powerline-start
}
</code></pre>
<h4>Enhanced selection</h4>
<p>In Helix, pressing <code>x</code> will select the entire line. Subsequent <code>x</code>'s will keep expanding the selection line-by-line. In Kakoune, Subsequent <code>x</code>'s do nothing.</p>
<p><a href="https://github.com/evanrelf/byline.kak">byline.kak</a> does exactly that.</p>
<p>In fact, pressing <code>&lt;shift&gt;x</code> will shrink the selection by a line! Very useful.</p>
<pre><code class="language-vim">plug &quot;evanrelf/byline.kak&quot; config %{
require-module &quot;byline&quot;
}
</code></pre>
<h4>Luar</h4>
<p>Some Kakoune plugins are written in Lua, this plugin will allow those ones to run. Adding this plugin is a nice future-proof against plugins randomly break because you forgot this one.</p>
<pre><code class="language-vim">plug &quot;gustavo-hms/luar&quot; %{
require-module luar
}
</code></pre>
<h4>LSP I</h4>
<p>Kakoune has autocomplete out-of-the-box, but now that LSP's are standard, it makes a lot of sense to use them.</p>
<p>There's an extension for that!</p>
<pre><code class="language-vim">plug &quot;kak-lsp/kak-lsp&quot; do %{
cargo install --locked --force --path .
# optional: if you want to use specific language servers
# mkdir -p ~/.config/kak-lsp
# cp -n kak-lsp.toml ~/.config/kak-lsp/
}
</code></pre>
<ul>
<li>The <code>do</code> directive tells <code>plug.kak</code> to run those shell commands only when first installing the plugin.</li>
</ul>
<p>However, <code>kak-lsp</code> requires a bit more configuration to work properly.</p>
<p>First, read the <code>kak-lsp</code> <a href="https://github.com/kak-lsp/kak-lsp">README</a> (always read the README for everything).</p>
<p>Before finishing <code>lsp</code>, let's learn about <code>hooks</code>;</p>
<h3>Hooks</h3>
<p><code>:doc hooks</code></p>
<p>Hooks in <code>kak</code> are like Events in Javascript, or <code>autocmd</code> in Vim/Neovim.
Basically, you give Kakoune some commands to run, and a trigger. When <code>kak</code> detects that trigger happening, it'll run your commands.</p>
<h4>Autosave</h4>
<p>Let's finally finish that autosave feature we were working on.</p>
<p>Here's a simple hook to do that:</p>
<pre><code class="language-vim">hook global ModeChange pop:insert:.* %{
save-buffer
}
</code></pre>
<ul>
<li><code>ModeChange</code> - the hook for whenever the user goes from <code>user</code> to <code>insert</code> or any combination of other modes</li>
<li><code>ModeChange</code> accepts a string formatted as <code>[push|pop]:&lt;old mode&gt;:&lt;new mode&gt;</code></li>
<li><code>pop:insert:.*</code> - this is the filter for the <code>ModeChange</code> hook, let's go over that
<ul>
<li><code>pop</code> - this is the <em>kind</em> of mode-change. The options here are <code>pop</code>, <code>push</code>, and <code>.*</code>.
<ul>
<li><code>pop</code> - refers to moving out of a mode and into the next one.</li>
<li><code>push</code> - <em>push</em>ing a command into a mode, for example, pressing <code>&lt;alt&gt;;</code> escapes <code>normal</code> mode for a single command.</li>
<li><code>.*</code> - wildcard for all</li>
</ul>
</li>
<li><code>insert</code> - the <strong>from</strong> mode, or the mode that we're leaving.</li>
<li><code>.*</code> - the <strong>to</strong> mode, or the mode that we're going to. This is set to <em>any</em>, as we want to save anytime we exit <code>insert</code> mode</li>
</ul>
</li>
<li><code>save-buffer</code> - our custom command to save the buffer and log the time.</li>
</ul>
<h4>Soft-wrap in markdown files</h4>
<p>Another hook I have enabled is soft-wrapping text in <code>.md</code> files. I find that it makes it a lot easier to edit text (not code) when I can see everything at once and don't have to horizontally-scroll.</p>
<pre><code class="language-vim">hook global WinSetOption filetype=markdown %{
add-highlighter -override global/markdown-wrap wrap -word
hook -once -always window WinSetOption filetype=.* %{
remove-highlighter global/markdown-wrap
}
}
</code></pre>
<blockquote>
<p>Yeah, you can nest <code>hooks</code> 😎</p>
</blockquote>
<p>Figuring out what the nested <code>hook</code> does is an exercise left to the reader.</p>
<h4>Lsp II</h4>
<p>If you read the <code>kak-lsp</code> <a href="https://github.com/kak-lsp/kak-lsp">README</a>, then this part is going to make a lot of sense.</p>
<p>While it's possible to just blindly enable <code>kak-lsp</code> for everything, I prefer so set hooks for the specific filetypes that I want to be editing.</p>
<pre><code class="language-vim">hook global WinSetOption filetype=(rust|javascript|typescript|c) %{
lsp-enable-window
lsp-inlay-diagnostics-enable global
}
## enable syntax highlighting for each lang
# c
hook global WinSetOption filetype=c %{
hook window -group semantic-tokens BufReload .* lsp-semantic-tokens
hook window -group semantic-tokens NormalIdle .* lsp-semantic-tokens
hook window -group semantic-tokens InsertIdle .* lsp-semantic-tokens
hook -once -always window WinSetOption filetype=.* %{
remove-hooks window semantic-tokens
}
}
# rust
hook global WinSetOption filetype=rust %{
hook window -group semantic-tokens BufReload .* lsp-semantic-tokens
hook window -group semantic-tokens NormalIdle .* lsp-semantic-tokens
hook window -group semantic-tokens InsertIdle .* lsp-semantic-tokens
hook -once -always window WinSetOption filetype=.* %{
remove-hooks window semantic-tokens
}
}
# typescript
hook global WinSetOption filetype=typescript %{
hook window -group semantic-tokens BufReload .* lsp-semantic-tokens
hook window -group semantic-tokens NormalIdle .* lsp-semantic-tokens
hook window -group semantic-tokens InsertIdle .* lsp-semantic-tokens
hook -once -always window WinSetOption filetype=.* %{
remove-hooks window semantic-tokens
}
}
# javascript
hook global WinSetOption filetype=javascript %{
hook window -group semantic-tokens BufReload .* lsp-semantic-tokens
hook window -group semantic-tokens NormalIdle .* lsp-semantic-tokens
hook window -group semantic-tokens InsertIdle .* lsp-semantic-tokens
hook -once -always window WinSetOption filetype=.* %{
remove-hooks window semantic-tokens
}
}
</code></pre>
<blockquote>
<p>If you read the comments, you'll also notice that we enabled better syntax highlighting for each of those filetypes as well.</p>
</blockquote>
<p>I also like to set a mapping to <code>user</code> mode to let me access the <code>lsp</code> menu really quickly:</p>
<pre><code class="language-vim">map -docstring &quot;open lsp&quot; global user l &quot;: enter-user-mode lsp&lt;ret&gt;&quot;
</code></pre>
<ul>
<li>Some extensions create their own special menus like the one that <code>&lt;space&gt;</code> creates. We access those with the <code>:enter-user-mode</code> command.</li>
<li>Now, <code>&lt;space&gt;lf</code> will perform lsp-assisted formatting!</li>
</ul>
<h4>Tab completion</h4>
<p>I don't like the <code>&lt;c-n&gt;</code>, <code>&lt;c-p&gt;</code> convention for selecting autocomplete items.
This is the recommended hook (according to the Kakoune wiki) for enabling <code>&lt;tab&gt;</code> and <code>&lt;shift&gt;&lt;tab&gt;</code> selections.</p>
<pre><code class="language-vim"># tabs for autocomplete
hook global InsertCompletionShow .* %{
try %{
# this command temporarily removes cursors preceded by whitespace;
# if there are no cursors left, it raises an error, does not
# continue to execute the mapping commands, and the error is eaten
# by the `try` command so no warning appears.
execute-keys -draft 'h&lt;a-K&gt;\h&lt;ret&gt;'
map window insert &lt;tab&gt; &lt;c-n&gt;
map window insert &lt;s-tab&gt; &lt;c-p&gt;
hook -once -always window InsertCompletionHide .* %{
unmap window insert &lt;tab&gt; &lt;c-n&gt;
unmap window insert &lt;s-tab&gt; &lt;c-p&gt;
}
}
}
</code></pre>
<h4>LSP III</h4>
<p>To learn more about creating custom completion tools in Kakoune see <a href="https://zork.net/~st/jottings/Intro_to_Kakoune_completions.html">here</a>.</p>
<h3>Goodbye clippy</h3>
<p>You probably noticed that clippy appears a lot in Kakoune</p>
<pre><code class="language-text">╭──╮
│ │
@ @ ╭
││ ││ │
││ ││ ╯
│╰─╯│
╰───╯
</code></pre>
<blockquote>
<p>this mf</p>
</blockquote>
<p>Well, a not-so-secret easter egg in Kakoune is that it's possible to change the assistant!</p>
<p>Here's how to remove clippy altogether</p>
<pre><code class="language-vim">set-option global ui_options terminal_assistant=none
</code></pre>
<blockquote>
<p>Available options are <code>clippy</code>, <code>dilbert</code>, <code>cat</code>, and <code>none</code>. Try setting each of those, something interesting might happen ;D</p>
</blockquote>
<h2>Wrapping up</h2>
<p>My current, mostly up-to-date <code>kakrc</code> can be found on my github <a href="https://github.com/secondary-smiles/.dots/blob/main/pkg/kakoune/kakrc">.dots</a>.</p>
<p>Kakoune is an incredible editor, I've really never had this much fun in a text editor, and for me it just feels so good using a <a href="https://zork.net/~st/jottings/kakoune-a-punk-rock-text-editor.html">punk-rock editor</a>.</p>
<p>This article isn't an introduction to terminal-editors, but if you're interested in the field, YouTube is a great starting place.</p>
<p>Also check out the <a href="https://discuss.kakoune.com/">Kakoune Forums</a> for infinite <code>kak</code> tips and tricks.</p>
<p>Thanks for reading!</p>
]]></content:encoded>
<guid isPermaLink="false">writing-your-first-kakrc</guid>
<pubDate>Sat, 22 Apr 2023 19:00:00 GMT</pubDate>
</item>
<item>
<title>Creating The Curio</title>
<link>https://blog.trinket.icu/articles/creating-the-curio</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>TL;DR I made a thing. Here's the direct link, and here's the github repo for it.
The Problem
For a while now, I've had a habit of scrolling through two websites fairly often. One was the Urban Dictionary, and the other ThisWebsiteWillSelfDestruct. I found that browsing both was a more enjoyable experience than any conventional social media I'd tried. Simply relaxing, and reading endless amounts of wordplay on the Urban Dictionary, or messages thrown into the void with ThisWebsiteWillSelfDestruct was endlessly entertaining.
However, I was unsatisfied. I preferred reading the genuine messages on ThisWebsiteWillSelfDestruct, but the word, type, definition format of the Urban Dictionary had my heart.
The Solution
I couldn't find an alternative that I liked (although one probably exists somewhere in the void), so I made The Curio(curio.lightblog.dev). I tried to copy the minimal feel of this website, so visiting it should feel familiar to this one.
The Process
I don't do much web development, lightblog.dev had been by far my largest endeavor yet when I decided to start working on The Curio. In the end, I chose to use Firebase as a backend-as-a-service since it covers databases, authentication, and cloud functions pretty simply. For me this was invaluable, as I don't have the confidence that as a one-man team I'd be able to build a secure backend. I chose Sveltekit as a front-end for two reasons; Firstly, I already know how to use Svelte (this website is made exclusively in svelte), and secondly, Sveltekit had just recently hit v1.0.0 and I was excited to try it out. I chose Vercel to host mainly because it's &amp;lt;u&amp;gt;cheap&amp;lt;/u&amp;gt; and supports Sveltekit SSR. I'm currently working on plugging in a full-text backend for the site because Firebase's builtin document searching functionality is pretty awful. I always think it's funny that a service provided by Google, the words most popular search engine by far has one of the worst builtin searching mechanisms ever. I'm strongly considering Meilisearch since it's got a generous free tier. However, if a better alternative comes to my attention I'll use that instead. I'm not strongly attached to anything other than low costs on this front.
Interesting Features and Notes
The Curio is not a creation of mine that I expect to grow very much. I call it a social media site, but in truth it's not. There is no first-level interaction, the most a 'post' can do is link to another one in context. However, I am proud of it and hope to grow at least a small community.
One thing I've implemented that I like is a color system that goes throughout the website. A short Class that fiddles with the bits of the UID of someone logged in, and generates a (hopefully) unique color for them.
// https://stackoverflow.com/questions/3426404/create-a-hexadecimal-colour-based-on-a-string-with-javascript
class ColorHash {
colors: number[];
constructor(data: string = &amp;quot;&amp;quot;) {
this.colors = [];
this.hash(data);
}
hash(data: string) {
this.colors = [];
// Reduce uniformity by prepending arbitrary character
data = &amp;quot;x&amp;quot; + data;
let hash = 0;
for (let i = 0; i &amp;lt; data.length; i++) {
hash = data.charCodeAt(i) + ((hash &amp;lt;&amp;lt; 5) - hash);
}
for (let i = 0; i &amp;lt; 3; i++) {
const value = (hash &amp;gt;&amp;gt; (i * 8)) &amp;amp; 0xFF;
this.colors.push(value);
}
}
rgb(data: string) {
this.hash(data);
return this.colors;
}
hex(data: string) {
this.hash(data);
function toHex(c: number) {
const hex = c.toString(16);
return hex.length == 1 ? &amp;quot;0&amp;quot; + hex : hex;
}
return &amp;quot;#&amp;quot; + toHex(this.colors[0]) + toHex(this.colors[1]) + toHex(this.colors[2]);
}
}
This serves as two things; One, as a cop-out for me so I don't have to implement user profiles, and two, it feeds my insatiable desire for every website to take full advantage of the technology browsers offer. I love colors, and when a website or application allows me to select colors, or changes appearance based on the visitor it always feels so cool. The Curio has a very minimal palette, all gray/blue and one accent color. The ColorHash class can generate a new accent color for the user which is shown site-wide. One of the benefits of a minimal design is that it's typically much easier to implement something visually across the entire website.
Running &amp;quot;The Curio&amp;quot; through the hex() function returns &amp;lt;span style=&amp;quot;color: #3f31b3;&amp;quot;&amp;gt;this&amp;lt;/span&amp;gt; color, for example. Provided that the contrast ratio between the generated color, and the background color of The Curio is enough, it will become the new accent color every time you sign in. The hex code will also be used as your username when posting new words.
For example:
The default Curio color-scheme for anyone signed out or if their user-color is too dim
A super cool custom accent color!
The structure of a word
In The Curio, every word has a uniform structure. That being Word, Type, User, Time, Definition, and Controls from top to bottom.
Word - The word that the individual post is about. It's the big, bold one at the top.
Type - Reminiscent of a dictionary, whether the word is a noun, adjective, verb, etc. The type is small, right under the word, and colored the same as the accent color.
User - A small rectangle colored the same as the user who created that word's unique color followed by the hex code for that same color.
Time - The date and time the word was added to the database. Located immediately after the User.
Definition - The definition of the word.
Controls - If you are the OP of the word, you'll have a small context menu under the definition. Currently, I've only implemented a delete action, but I'll probably get around to an edit, flag, and &amp;lt;3 button.
Thanks for reading
The Curio is a little project for me, so I don't expect it to go anywhere. However, I think if I build it in such a manner that it is capable of scaling it can't hurt. Just in case, right?
</description>
<content:encoded><![CDATA[<p><strong>TL;DR</strong> I made a thing. <a href="https://curio.lightblog.dev">Here's the direct link</a>, and <a href="https://github.com/secondary-smiles/curio">here's the github repo for it</a>.</p>
<h2>The Problem</h2>
<p>For a while now, I've had a habit of scrolling through two websites fairly often. One was the <a href="https://www.urbandictionary.com">Urban Dictionary</a>, and the other <a href="https://www.thiswebsitewillselfdestruct.com">ThisWebsiteWillSelfDestruct</a>. I found that browsing both was a more enjoyable experience than any conventional social media I'd tried. Simply relaxing, and reading endless amounts of wordplay on the Urban Dictionary, or messages thrown into the void with ThisWebsiteWillSelfDestruct was endlessly entertaining.
However, I was unsatisfied. I preferred reading the genuine messages on ThisWebsiteWillSelfDestruct, but the word, type, definition format of the Urban Dictionary had my heart.</p>
<h2>The Solution</h2>
<p>I couldn't find an alternative that I liked (although one probably exists somewhere in the void), so I made <a href="https://curio.lightblog.dev">The Curio</a>(<a href="https://curio.lightblog.dev">curio.lightblog.dev</a>). I tried to copy the minimal feel of this website, so visiting it should feel familiar to this one.</p>
<h2>The Process</h2>
<p>I don't do much web development, lightblog.dev had been by far my largest endeavor yet when I decided to start working on The Curio. In the end, I chose to use <a href="https://firebase.google.com/">Firebase</a> as a backend-as-a-service since it covers databases, authentication, and cloud functions pretty simply. For me this was invaluable, as I don't have the confidence that as a one-man team I'd be able to build a secure backend. I chose <a href="https://kit.svelte.dev/">Sveltekit</a> as a front-end for two reasons; Firstly, I already know how to use Svelte (this website is made exclusively in svelte), and secondly, Sveltekit had just recently hit v1.0.0 and I was excited to try it out. I chose <a href="https://vercel.com">Vercel</a> to host mainly because it's &lt;u&gt;cheap&lt;/u&gt; and supports Sveltekit SSR. I'm currently working on plugging in a full-text backend for the site because Firebase's builtin document searching functionality is pretty awful. I always think it's funny that a service provided by Google, the words most popular <em>search engine</em> by far has one of the worst builtin searching mechanisms ever. I'm strongly considering <a href="https://www.meilisearch.com">Meilisearch</a> since it's got a generous free tier. However, if a better alternative comes to my attention I'll use that instead. I'm not strongly attached to anything other than low costs on this front.</p>
<h2>Interesting Features and Notes</h2>
<p>The Curio is not a creation of mine that I expect to grow very much. I call it a social media site, but in truth it's not. There is no first-level interaction, the most a 'post' can do is link to another one in context. However, I am proud of it and hope to grow at least a small community.
One thing I've implemented that I like is a color system that goes throughout the website. A short Class that fiddles with the bits of the UID of someone logged in, and generates a (hopefully) unique color for them.</p>
<pre><code class="language-typescript">// https://stackoverflow.com/questions/3426404/create-a-hexadecimal-colour-based-on-a-string-with-javascript
class ColorHash {
colors: number[];
constructor(data: string = &quot;&quot;) {
this.colors = [];
this.hash(data);
}
hash(data: string) {
this.colors = [];
// Reduce uniformity by prepending arbitrary character
data = &quot;x&quot; + data;
let hash = 0;
for (let i = 0; i &lt; data.length; i++) {
hash = data.charCodeAt(i) + ((hash &lt;&lt; 5) - hash);
}
for (let i = 0; i &lt; 3; i++) {
const value = (hash &gt;&gt; (i * 8)) &amp; 0xFF;
this.colors.push(value);
}
}
rgb(data: string) {
this.hash(data);
return this.colors;
}
hex(data: string) {
this.hash(data);
function toHex(c: number) {
const hex = c.toString(16);
return hex.length == 1 ? &quot;0&quot; + hex : hex;
}
return &quot;#&quot; + toHex(this.colors[0]) + toHex(this.colors[1]) + toHex(this.colors[2]);
}
}
</code></pre>
<p>This serves as two things; One, as a cop-out for me so I don't have to implement user profiles, and two, it feeds my insatiable desire for every website to take full advantage of the technology browsers offer. I love colors, and when a website or application allows me to select colors, or changes appearance based on the visitor it always feels so cool. The Curio has a very minimal palette, all gray/blue and one accent color. The <code>ColorHash</code> class can generate a new accent color for the user which is shown site-wide. One of the benefits of a minimal design is that it's typically much easier to implement something visually across the entire website.
Running &quot;The Curio&quot; through the <code>hex()</code> function returns &lt;span style=&quot;color: #3f31b3;&quot;&gt;this&lt;/span&gt; color, for example. Provided that the contrast ratio between the generated color, and the background color of The Curio is enough, it will become the new accent color every time you sign in. The hex code will also be used as your username when posting new words.
For example:</p>
<p><img src="https://i.imgur.com/9FsxWYr.png" alt="default Curio color-scheme"></p>
<blockquote>
<p>The default Curio color-scheme for anyone signed out or if their user-color is too dim</p>
</blockquote>
<p><img src="https://i.imgur.com/7DmxTVq.png" alt="a customized Curio color-scheme"></p>
<blockquote>
<p>A super cool custom accent color!</p>
</blockquote>
<h2>The structure of a word</h2>
<p>In The Curio, every word has a uniform structure. That being Word, Type, User, Time, Definition, and Controls from top to bottom.</p>
<ul>
<li><strong>Word</strong> - The word that the individual post is about. It's the big, bold one at the top.</li>
<li><strong>Type</strong> - Reminiscent of a dictionary, whether the word is a noun, adjective, verb, etc. The type is small, right under the word, and colored the same as the accent color.</li>
<li><strong>User</strong> - A small rectangle colored the same as the user who created that word's unique color followed by the hex code for that same color.</li>
<li><strong>Time</strong> - The date and time the word was added to the database. Located immediately after the <strong>User</strong>.</li>
<li><strong>Definition</strong> - The definition of the word.</li>
<li><strong>Controls</strong> - If you are the OP of the word, you'll have a small context menu under the definition. Currently, I've only implemented a <code>delete</code> action, but I'll probably get around to an <code>edit</code>, <code>flag</code>, and <code>&lt;3</code> button.</li>
</ul>
<h2>Thanks for reading</h2>
<p>The Curio is a little project for me, so I don't expect it to go anywhere. However, I think if I build it in such a manner that it is capable of scaling it can't hurt. Just in case, right?</p>
]]></content:encoded>
<guid isPermaLink="false">creating-the-curio</guid>
<pubDate>Thu, 16 Feb 2023 19:00:00 GMT</pubDate>
</item>
<item>
<title>A Loveletter to the Internet</title>
<link>https://blog.trinket.icu/articles/loveletter-to-the-internet</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>What even is the internet?
For some, the internet is magic, for others, it's hell.
In one sentence, the internet is a system of interconnected computers and servers that allows users to communicate and share information online.
The internet is more than just that however, it's the natural evolution of humanity. For the whole of human existence, we've dominated the food chain not because of our superior speed, strength, or senses. No, we became the superior species because of communication skills. The ability to convey thoughts, feelings, stories, and messages has skyrocketed global society above and beyond anything on the planet (that we know of). What started off as speaking to one another, eventually evolved into written communication, which has now evolved into the internet.
So in a nutshell, the internet is just another evolution of humanity. Inevitable, vital, and inseparable from the rest of what makes us humans.
The concept of the internet
How did the internet become what it is?
When humans were evolving a written language it wasn't like they just said &amp;quot;poof, now the alphabet exists&amp;quot;. No, it evolved slowly and over time. At first, humans just had illustrations and signs that roughly conveyed stories and meaning, i.e. cave art. Over time, this new method of communication evolved alongside spoken language. Certain symbols began to have a 1:1 mapping to certain words. A section of wavy lines now directly means &amp;quot;river&amp;quot;, for example. For the most part, people probably didn't see anything wrong with this. Being able to preserve stories outside human memory, and communicate over long distances by passing a letter was a huge boost to everything, and it was naturally obvious to take advantage of the new mediums of communication.
When computers were still in their relative infancy (relative to the state of computers in early 2023) a new storage system was evolved for them, over time digital storage has evolved to the point that it's at today. Now, we can store entire libraries in the space one book would take up, and a whole theater's worth of movies can sit in my pocket.
Back then, storage was a lot more primitive, but still effective. The thing was, computers were still extremely expensive, and so only governments and colleges really had access to them.
A problem that would often occur would be data transfer, no one wants to run across campus to give a file to someone, or even worse, drive to another college. Another issue was that some computers were more powerful than others, and no one wanted to drive several hours to use one when they had one at their own college. The whole point was to save time, not drive several hours to run some programs on a different computer.
The network was an obvious solution to the problem of data and resource sharing. So obvious, in fact, that several networks of computers were created and prototyped nearly in parallel. At a certain point, the 'internet' was just a series of networks that colleges and governments used to share computer resources and data. There were several, and each was its own project mostly without connections to the others. The world was a series of 'intranets', or small networks cut off from others around it and private, meaning no one could publicly access it.
Intranets could range in size, from just one building, to spanning the United States. The US Government created their own intranet in collaboration with several colleges so that a network of computers could rely on each other with no single fault point. This was created in case of nuclear attack.
Without going into explicit detail, several of these intranets merged, taking on the best qualities of the other such as faster communication systems, or a better infrastructure system. In doing this, the internet became both an extremely powerful and (mostly) efficient system for communications, but also a mash of systems and protocols shoehorned into one-another.
Eventually, several key points of the internet were created, such as a DNS system, the system that allows computers to be both added to the internet and also acts as a sort of telephone operator for the whole world. Once these last bits of infrastructure were added, the internet was made public, and the rest is history for the most part.
Stages of evolution
What are all the different stages of the internet?
Three terms often tossed around are &amp;quot;Web 1.0&amp;quot;, &amp;quot;Web 2.0&amp;quot;, and &amp;quot;Web 3.0&amp;quot;. These refer to stages of the global internet, the technologies that define it, and the way it can be interacted with.
Web 1.0
Web 1.0 was the initial public stage of the &amp;quot;world wide web&amp;quot;. It was focused on fetching and reading information. Websites were static, meaning that they didn't react to user input. They are more suited to displaying information than collecting it. At this stage, someone who was able to operate a server, could make websites publicly available for browsing. This meant that anyone who navigated to your website in a web browser could view the information that you made available. They couldn't send data back to the server for the most part, it was all about fetching and reading information. During Web 1.0, regulations were still being settled around the internet, and due to its relatively small user base at the time, advertisement was not allowed on the internet as it disrupted the civility and was annoying.
Web 2.0
Web 2.0 is the current phase of the internet. Its values are interaction with the end user. During the transition from Web 1.0 to Web 2.0, technologies became more advanced. Browsers became more able to display more complex websites, and servers became able to interact with individual end users. With the advent of Web 2.0, websites became more advanced, and graphics became more fluid and interactive. What was once only a text-interface now supported interactive graphics and far more design possibilities, a new pseudo-programming language called CSS was even created with the sole purpose of allowing creators to style their websites with fine-grained control over each and every element of a web page. Web 2.0 birthed a new form of art and design, but it is also the reign of corporate control. Due to the system by which servers interact with the end-user, advertisements and tracking are a rampant issue around the internet. Companies realized it was a majorly effective method of sales-pitching and due to the individuality of users, it also allows for things like targeted advertisements on a per-user basis. During Web 2.0, data is centralized and stored on individual servers. This means that every company can collect information based on user interactions on only their own websites. Web 2.0 is the current phase, and is constantly growing and expanding as new technologies are invented that can create new and unique user experiences.
Web 3.0
Web 3.0 is a proposal for a new stage of the internet. It is not the current stage of the internet, but it is possible that it will be in the future. Without going into too much detail, Web 3.0 proposes that data be decentralized, that the internet become a personalized experience, and that radical new technologies be implemented to drastically alter the foundation of the internet. Currently, Web 2.0 has a paradigm whereby a handful of corporations controls the experience and data of many. Web 3.0 is the concept of users controlling their individual information. It also promotes the concept of artificial intelligence at the core of the internet, the theory being that it would be able to react and interact with users in a far more personal manner than current systems. However, due to the &amp;quot;open market&amp;quot; sense of the concept of Web 3.0, as well as its proposed reliance on technologies such as cryptocurrencies, Web 3.0 has been largely promoted by individuals who are not publicly considered trustworthy. Also, the fact that cryptocurrency is used as an effective system by criminals and con-artists due to its lack of middleman in money transfer has not lent confidence to the concept of Web 3.0 relying almost solely on the same technologies that cryptocurrencies do. The recent crash of many cryptocurrencies such as Bitcoin has also led a lot of people to be dissuaded by the idea of Web 3.0 actually making any improvements on Web 2.0. Many view it as a 'get-rich-quick' scheme due to the large amount of buzzwords and vaporware (software or hardware that has been advertised but is not yet available to buy, either because it is only a concept or because it is still being written or designed) used in arguments for Web 3.0.
What is it that you see
Anyone can make a website, but what goes into it?
Today, three main technologies dominate how information is transmitted over the internet. HTML, CSS, and Javascript are a trio of technologies that when combined can create visual layouts for websites.
HTML
HTML, or Hyper Text Markup Language is a bracketed-language used as the core of every website. HTML cannot define user-interactions, or create styles. HTML defines the structure of a webpage however. It defines the order of paragraphs, and the places that links lead to. A website does not need CSS or Javascript in order to be viewable, but without HTML there is no content to view.
CSS
Cascading Style Sheets is the glamor of the trinity. CSS works by selecting an element from the HTML, such as a link, or paragraph, and then applying styles to it. Styles can be many things, but are mainly used to apply colors, fronts and placement. CSS can also be used for other styles such as applying borders, or changing the shape and outline of an element.
Javascript
Javascript, or JS is the most complicated part of the technology trio. It is the only 'real' programming language and it handles user interaction. JS is capable of modifying HTML, and CSS in real-time based on what the user is doing. If you've ever scrolled down a website like the iPhone product page, you'd notice how the webpage elements change in style and content as you scroll. This is the product of JS dictating changes in both the HTML and CSS leading to a mesmerizing result. If you've ever clicked a button on a website and a fun effect happens, that's JS modifying the website based on user interaction.
These three technologies combined are behind nearly every website on the internet, and have entire ecosystems in and of their own made up of more sub-technologies to improve each of these main technologies.
Forgotten relics and places to explore
The internet is so massive, some places just go unnoticed by most.
It is estimated that more than half the world uses the internet on a mostly daily basis. Anyone can put nearly anything on the internet if they know how. This leads to a lot of meaningless garbage that people throw up, sometimes making it difficult to distinguish between quality websites and low-effort pages by people and companies. This is such a rampant issue, that search engines such as Google are highly optimized for filtering good and bad quality pages. Sometimes this filtering fails, or is politically manipulated, but that's a topic for a different day.
This constant slew of refuse, however, does a fairly effective job at burying many websites without enough exposure. Many high-quality websites exist and have small, but active communities despite being largely under the radar to most, buried amidst all the garbage websites and ignored as such.
Some people like to go 'metal-detecting' on the internet, browsing old, forgotten, or just less-spoken-of websites in search of something interesting.
Here's a few such websites.
The C2 Wiki
wiki.c2.com
The C2 Wiki, or the WikiWikiWeb, or 'Wiki' is one of the very first of its kind on the internet. The original 'wikis' were some of the first user-generated web pages, allowing users to contribute to content on the page under the guidance of moderators. The WikiWikiWeb is not a site often visited by the younger generations, but contains years and years of writing by hundreds of authors. Topics range from grammar critique, to philosophies on death.
Lesswrong
lesswrong.com
Similar to WikiWikiWeb, Lesswrong is a user-generated website, however where WikiWikiWeb focused on most topics under the sun, Lesswrong is focused on &amp;quot;improving human reasoning and decision-making&amp;quot;. Despite these, Lesswrong still has many fascinating posts about many things, such as the author's musings on snacking while typing, large discussions on whether humanity is evolutionarily obligated to end death, and even a large attempt to explain Harry Potter using rationalist theorems. Lesswrong is notable due to the extreme civility, and emphasis on quality of writing. Every post of the site has a comment section that usually extends the post due to the civil debates that typically happen having to do with the original poster.
The Evil Overlord List
eviloverlord.com
What if.. The bad guy was actually smart? Peter's Evil Overlord list is a massive collection of things to do and not to do in the event you become an evil overlord.
Some notable items on the list include;
&amp;quot;My ventilation ducts will be too small to crawl through.&amp;quot;
&amp;quot;I will never utter the sentence 'But before I kill you, there's just one thing I want to know.'&amp;quot;
&amp;quot;My Legions of Terror will be trained in basic marksmanship. Any who cannot learn to hit a man-sized target at 10 meters will be used for target practice.&amp;quot;
&amp;quot;If I learn that a callow youth has begun a quest to destroy me, I will slay him while he is still a callow youth instead of waiting for him to mature.&amp;quot;
If you ever suddenly find yourself in the role of Evil Overlord, this list is an invaluable asset.
It is, of course, incredibly important to mention the Wayback Machine (web.archive.org). This site has been collecting and organizing snapshots of most websites in existence for nearly as long as the internet has been active. It's the single most useful tool in browsing and finding archaic relics on the web.
Fashion and looks
Corporate design, form, function, and colors.
Most people have seen old websites. Nowadays, the lack of unified color palettes, text placement, size, and font stick out like a sore thumb, but it wasn't always like that. When the trinity of technologies (see what is it that you see) was in its relative infancy, design options were far more limited than they are today. Also, the internet was still a place where hobbyists would put up things like personal landing pages. The equivalent of a nerd's business card.
1997 - The beginning
In the infancy of the internet (see Web 1.0), the term web design hadn't quite been coined yet. Websites were viewed more as an extension of paper. A collection of billboards in cyberspace. It was all about bright colors and bold, contrasting Calls To Action (CTA). A CTA is an element of a design created specifically to draw attention to whatever it is advertising. Websites were like virtual billboards and so people designed them to attract as much attention as possible. Flashy logos, bold color blocks, and big bars were the name of the game.
This screenshot of the Apple website from 1997 illustrates this era of design perfectly:
Bold colors, cluttered text, websites in this era did everything they could with the available technology to stand out from the rest.
2002 - Listening to the consumer
Eventually, researchers and companies began to notice the same thing; people don't actually like bright, cluttered websites. Research was showing that websites with pleasant spacing, colors and minimal text was retaining users much more effectively than the current design trends. At the same time as this was becoming its own trend, technology was rapidly evolving. This allowed companies and website designers to fully implement this in their own websites much more easily than before.
The Google landing page in 2002 is an excellent illustration of this:
A tabbed design finally allows website visitors to see only the text they want without bombarding their senses with everything at once. A subtle red New! CTA does an excellent job of advertising a new product without taking up the whole page as it would before.
Web 2.0 - Going crazy
Whitespace and careful design is fine, but users were quickly getting bored of uniform website designs. With the advent of Web 2.0 (see Web 2.0), focus quickly shifted to interactive website design. People were tired of mono themes and flat websites so designers quickly shifted to something new. Whether for the better or for the worse depends on if you ask someone with epilepsy or not.
Bright colors, crazed fonts, animate everything. These were the core lifeblood of this era. Web 2.0 allowed for much more interactive design, and everyone was scrambling to take advantage of it.
Kiddonet is probably the most famous example of this:
Filled with noise and colors. If viewing this site live, you'll notice that every element is moving in some way or another. I am not a very big fan of this era, nostalgia aside.
2010 Experiments - Skeuomorphic design
A minor but notable trend in the history of web design is skeuomorphic design. People were still adjusting to new interfaces and technologies and skeuomorphic design aimed to bridge the real and virtual worlds. Until around 2013, Apple was maybe the most famous example of this design trend. Their iOS for iPhone was almost entirely skeuomorphic. For example, the notes app looked just like a notebook. And the calculator buttons were shaded to look three-dimensional. As if they were coming out of the screen. Due to the difficulty of effectively implementing this style, as well as the decreasing amount of need for an visually obvious style like this (people were now used to the internet and software having its own icon, it no longer needed to rely on visual cues from the real world as much).
Unfortunately, I wasn't able to find any examples of skeuomorphic design on websites. Doing a web search on your search engine of choice will likely yield many good image examples, however.
Current Design - The corporate look
Eventually, designers began to find new ways embracing both minimalism and interactive design. Websites began to take on a very uniform feel and look. Mass corporate rebranding also accented this new design paradigm well, with companies reducing colors, shading, and noise in their logos. Some view this new design trend as an ugly uniformity, others view it as the pinnacle of design. New technology from the trio (see What is it that you see) has allowed for much more responsive websites that can interact and change on a per-visitor basis as well as modify their own look and content based on how they are interacted with. As users began to adapt and become more and more familiar with the web, new priorities arose. No longer did people emphasize the intuitive design of skeuomorphism, as people got used to the new look of websites they began to emphasize speed instead. With so many options at people's fingertips, the difference of a tenth of a second loading something on a website could be the difference between a customer reading the website or leaving in search of something else. Corporate design also embraced another trend at its core; infinite scrolling. Now that browsers could support it better, websites began to take advantage of longer pages than ever before. This allowed users to scroll through it in one fluid motion, rather than forcing them to navigate a series of tabbed pages that could be very short and cause a lot of confusion if the layout was complicated.
The Obsidian homepage is a good example of this trend:
The design of this website is both unique and standard. The soft text, minimal palette and lack of noise are both a curse and a boon for this website. The minimal design is pleasant, and nice to look at but also unfortunately blends right into all the other corporate websites on the internet.
Fun fact: Obsidian is the program I'm using to write this article right now.
Conclusion
To put it all together.
The internet is a massive place, all this barely even scratches the surface of the massive web of interconnected technologies and tools we use on a daily basis. The internet is a complicated place, it's massive and full of so many different things. But it's also a place of creativity and art and human expression. It's a place where people fall in and out of love, a place where science happens, and discoveries are made. It's a place as familiar to most of us as a couch at home. The internet is here and it's not going away anytime soon.
</description>
<content:encoded><![CDATA[<h2>What even is the internet?</h2>
<blockquote>
<p>For some, the internet is magic, for others, it's hell.</p>
</blockquote>
<p>In one sentence, the internet is a system of interconnected computers and servers that allows users to communicate and share information online.</p>
<p>The internet is more than just that however, it's the natural evolution of humanity. For the whole of human existence, we've dominated the food chain not because of our superior speed, strength, or senses. No, we became the superior species because of communication skills. The ability to convey thoughts, feelings, stories, and messages has skyrocketed global society above and beyond anything on the planet (that we know of). What started off as speaking to one another, eventually evolved into written communication, which has now evolved into the internet.</p>
<p>So in a nutshell, the internet is just another evolution of humanity. Inevitable, vital, and inseparable from the rest of what makes us humans.</p>
<h2>The concept of the internet</h2>
<blockquote>
<p>How did the internet become what it is?</p>
</blockquote>
<p>When humans were evolving a written language it wasn't like they just said &quot;<em>poof, now the alphabet exists</em>&quot;. No, it evolved slowly and over time. At first, humans just had illustrations and signs that roughly conveyed stories and meaning, i.e. cave art. Over time, this new method of communication evolved alongside spoken language. Certain symbols began to have a 1:1 mapping to certain words. A section of wavy lines now directly means &quot;river&quot;, for example. For the most part, people probably didn't see anything wrong with this. Being able to preserve stories outside human memory, and communicate over long distances by passing a letter was a huge boost to everything, and it was naturally obvious to take advantage of the new mediums of communication.</p>
<p>When computers were still in their relative infancy (relative to the state of computers in early 2023) a new storage system was evolved for them, over time digital storage has evolved to the point that it's at today. Now, we can store entire libraries in the space one book would take up, and a whole theater's worth of movies can sit in my pocket.</p>
<p>Back then, storage was a lot more primitive, but still effective. The thing was, computers were still extremely expensive, and so only governments and colleges really had access to them.</p>
<p>A problem that would often occur would be data transfer, no one wants to run across campus to give a file to someone, or even worse, drive to another college. Another issue was that some computers were more powerful than others, and no one wanted to drive several hours to use one when they had one at their own college. The whole point was to save time, not drive several hours to run some programs on a different computer.</p>
<p>The network was an obvious solution to the problem of data and resource sharing. So obvious, in fact, that several networks of computers were created and prototyped nearly in parallel. At a certain point, the 'internet' was just a series of networks that colleges and governments used to share computer resources and data. There were several, and each was its own project mostly without connections to the others. The world was a series of 'intranets', or small networks cut off from others around it and private, meaning no one could publicly access it.</p>
<p>Intranets could range in size, from just one building, to spanning the United States. The US Government created their own intranet in collaboration with several colleges so that a network of computers could rely on each other with no single fault point. This was created in case of nuclear attack.</p>
<p>Without going into explicit detail, several of these intranets merged, taking on the best qualities of the other such as faster communication systems, or a better infrastructure system. In doing this, the internet became both an extremely powerful and (mostly) efficient system for communications, but also a mash of systems and protocols shoehorned into one-another.</p>
<p>Eventually, several key points of the internet were created, such as a DNS system, the system that allows computers to be both added to the internet and also acts as a sort of telephone operator for the whole world. Once these last bits of infrastructure were added, the internet was made public, and the rest is history for the most part.</p>
<h2>Stages of evolution</h2>
<blockquote>
<p>What are all the different stages of the internet?</p>
</blockquote>
<p>Three terms often tossed around are &quot;Web 1.0&quot;, &quot;Web 2.0&quot;, and &quot;Web 3.0&quot;. These refer to stages of the global internet, the technologies that define it, and the way it can be interacted with.</p>
<h3>Web 1.0</h3>
<p>Web 1.0 was the initial public stage of the &quot;world wide web&quot;. It was focused on fetching and reading information. Websites were static, meaning that they didn't react to user input. They are more suited to displaying information than collecting it. At this stage, someone who was able to operate a server, could make websites publicly available for browsing. This meant that anyone who navigated to your website in a web browser could view the information that you made available. They couldn't send data back to the server for the most part, it was all about fetching and reading information. During Web 1.0, regulations were still being settled around the internet, and due to its relatively small user base at the time, advertisement was not allowed on the internet as it disrupted the civility and was annoying.</p>
<h3>Web 2.0</h3>
<p>Web 2.0 is the current phase of the internet. Its values are interaction with the end user. During the transition from Web 1.0 to Web 2.0, technologies became more advanced. Browsers became more able to display more complex websites, and servers became able to interact with individual end users. With the advent of Web 2.0, websites became more advanced, and graphics became more fluid and interactive. What was once only a text-interface now supported interactive graphics and far more design possibilities, a new pseudo-programming language called CSS was even created with the sole purpose of allowing creators to style their websites with fine-grained control over each and every element of a web page. Web 2.0 birthed a new form of art and design, but it is also the reign of corporate control. Due to the system by which servers interact with the end-user, advertisements and tracking are a rampant issue around the internet. Companies realized it was a majorly effective method of sales-pitching and due to the individuality of users, it also allows for things like targeted advertisements on a per-user basis. During Web 2.0, data is centralized and stored on individual servers. This means that every company can collect information based on user interactions on only their own websites. Web 2.0 is the current phase, and is constantly growing and expanding as new technologies are invented that can create new and unique user experiences.</p>
<h3>Web 3.0</h3>
<p>Web 3.0 is a proposal for a new stage of the internet. It is not the current stage of the internet, but it is possible that it will be in the future. Without going into too much detail, Web 3.0 proposes that data be decentralized, that the internet become a personalized experience, and that radical new technologies be implemented to drastically alter the foundation of the internet. Currently, Web 2.0 has a paradigm whereby a handful of corporations controls the experience and data of many. Web 3.0 is the concept of users controlling their individual information. It also promotes the concept of artificial intelligence at the core of the internet, the theory being that it would be able to react and interact with users in a far more personal manner than current systems. However, due to the &quot;open market&quot; sense of the concept of Web 3.0, as well as its proposed reliance on technologies such as cryptocurrencies, Web 3.0 has been largely promoted by individuals who are not publicly considered trustworthy. Also, the fact that cryptocurrency is used as an effective system by criminals and con-artists due to its lack of middleman in money transfer has not lent confidence to the concept of Web 3.0 relying almost solely on the same technologies that cryptocurrencies do. The recent crash of many cryptocurrencies such as Bitcoin has also led a lot of people to be dissuaded by the idea of Web 3.0 actually making any improvements on Web 2.0. Many view it as a 'get-rich-quick' scheme due to the large amount of buzzwords and vaporware (<em>software or hardware that has been advertised but is not yet available to buy, either because it is only a concept or because it is still being written or designed</em>) used in arguments for Web 3.0.</p>
<h2>What is it that you see</h2>
<blockquote>
<p>Anyone can make a website, but what goes into it?</p>
</blockquote>
<p>Today, three main technologies dominate how information is transmitted over the internet. HTML, CSS, and Javascript are a trio of technologies that when combined can create visual layouts for websites.</p>
<h3>HTML</h3>
<p>HTML, or Hyper Text Markup Language is a bracketed-language used as the core of every website. HTML cannot define user-interactions, or create styles. HTML defines the structure of a webpage however. It defines the order of paragraphs, and the places that links lead to. A website does not need CSS or Javascript in order to be viewable, but without HTML there is no content to view.</p>
<h3>CSS</h3>
<p>Cascading Style Sheets is the glamor of the trinity. CSS works by selecting an element from the HTML, such as a link, or paragraph, and then applying styles to it. Styles can be many things, but are mainly used to apply colors, fronts and placement. CSS can also be used for other styles such as applying borders, or changing the shape and outline of an element.</p>
<h3>Javascript</h3>
<p>Javascript, or JS is the most complicated part of the technology trio. It is the only 'real' programming language and it handles user interaction. JS is capable of modifying HTML, and CSS in real-time based on what the user is doing. If you've ever scrolled down a website like the iPhone product page, you'd notice how the webpage elements change in style and content as you scroll. This is the product of JS dictating changes in both the HTML and CSS leading to a mesmerizing result. If you've ever clicked a button on a website and a fun effect happens, that's JS modifying the website based on user interaction.</p>
<p>These three technologies combined are behind nearly every website on the internet, and have entire ecosystems in and of their own made up of more sub-technologies to improve each of these main technologies.</p>
<h2>Forgotten relics and places to explore</h2>
<blockquote>
<p>The internet is so massive, some places just go unnoticed by most.</p>
</blockquote>
<p>It is estimated that more than half the world uses the internet on a mostly daily basis. Anyone can put nearly anything on the internet if they know how. This leads to a lot of meaningless garbage that people throw up, sometimes making it difficult to distinguish between quality websites and low-effort pages by people and companies. This is such a rampant issue, that search engines such as Google are highly optimized for filtering good and bad quality pages. Sometimes this filtering fails, or is politically manipulated, but that's a topic for a different day.
This constant slew of refuse, however, does a fairly effective job at burying many websites without enough exposure. Many high-quality websites exist and have small, but active communities despite being largely under the radar to most, buried amidst all the garbage websites and ignored as such.</p>
<p>Some people like to go 'metal-detecting' on the internet, browsing old, forgotten, or just less-spoken-of websites in search of something interesting.</p>
<p>Here's a few such websites.</p>
<h3>The C2 Wiki</h3>
<blockquote>
<p><a href="https://wiki.c2.com/">wiki.c2.com</a></p>
</blockquote>
<p>The C2 Wiki, or the WikiWikiWeb, or 'Wiki' is one of the very first of its kind on the internet. The original 'wikis' were some of the first user-generated web pages, allowing users to contribute to content on the page under the guidance of moderators. The WikiWikiWeb is not a site often visited by the younger generations, but contains years and years of writing by hundreds of authors. Topics range from grammar critique, to philosophies on death.</p>
<h3>Lesswrong</h3>
<blockquote>
<p><a href="https://www.lesswrong.com/">lesswrong.com</a></p>
</blockquote>
<p>Similar to WikiWikiWeb, Lesswrong is a user-generated website, however where WikiWikiWeb focused on most topics under the sun, Lesswrong is focused on &quot;improving human reasoning and decision-making&quot;. Despite these, Lesswrong still has many fascinating posts about many things, such as the author's musings on snacking while typing, large discussions on whether humanity is evolutionarily obligated to end death, and even a large attempt to explain Harry Potter using rationalist theorems. Lesswrong is notable due to the extreme civility, and emphasis on quality of writing. Every post of the site has a comment section that usually extends the post due to the civil debates that typically happen having to do with the original poster.</p>
<h3>The Evil Overlord List</h3>
<blockquote>
<p><a href="http://www.eviloverlord.com/lists/overlord.html">eviloverlord.com</a></p>
</blockquote>
<p>What if.. The bad guy was actually smart? Peter's Evil Overlord list is a massive collection of things to do and not to do in the event you become an evil overlord.
Some notable items on the list include;</p>
<p>&quot;My ventilation ducts will be too small to crawl through.&quot;</p>
<p>&quot;I will never utter the sentence 'But before I kill you, there's just one thing I want to know.'&quot;</p>
<p>&quot;My Legions of Terror will be trained in basic marksmanship. Any who cannot learn to hit a man-sized target at 10 meters will be used for target practice.&quot;</p>
<p>&quot;If I learn that a callow youth has begun a quest to destroy me, I will slay him while he is still a callow youth instead of waiting for him to mature.&quot;</p>
<p>If you ever suddenly find yourself in the role of Evil Overlord, this list is an invaluable asset.</p>
<p>It is, of course, incredibly important to mention the Wayback Machine (web.archive.org). This site has been collecting and organizing snapshots of most websites in existence for nearly as long as the internet has been active. It's the single most useful tool in browsing and finding archaic relics on the web.</p>
<h2>Fashion and looks</h2>
<blockquote>
<p>Corporate design, form, function, and colors.</p>
</blockquote>
<p>Most people have seen old websites. Nowadays, the lack of unified color palettes, text placement, size, and font stick out like a sore thumb, but it wasn't always like that. When the trinity of technologies (see <em>what is it that you see</em>) was in its relative infancy, design options were far more limited than they are today. Also, the internet was still a place where hobbyists would put up things like personal landing pages. The equivalent of a nerd's business card.</p>
<h3>1997 - The beginning</h3>
<p>In the infancy of the internet (see <em>Web 1.0</em>), the term <em>web design</em> hadn't quite been coined yet. Websites were viewed more as an extension of paper. A collection of billboards in cyberspace. It was all about bright colors and bold, contrasting Calls To Action (CTA). A CTA is an element of a design created specifically to draw attention to whatever it is advertising. Websites were like virtual billboards and so people designed them to attract as much attention as possible. Flashy logos, bold color blocks, and big bars were the name of the game.
This screenshot of the Apple website from 1997 illustrates this era of design perfectly:
<img src="https://i.imgur.com/4ppuHLz.png" alt="Apple's landing page in 1997"></p>
<blockquote>
<p>Bold colors, cluttered text, websites in this era did everything they could with the available technology to stand out from the rest.</p>
</blockquote>
<h3>2002 - Listening to the consumer</h3>
<p>Eventually, researchers and companies began to notice the same thing; people don't actually like bright, cluttered websites. Research was showing that websites with pleasant spacing, colors and minimal text was retaining users much more effectively than the current design trends. At the same time as this was becoming its own trend, technology was rapidly evolving. This allowed companies and website designers to fully implement this in their own websites much more easily than before.
The Google landing page in 2002 is an excellent illustration of this:
<img src="https://i.imgur.com/Z27S5Jm.png" alt="Google's landing page in 2002"></p>
<blockquote>
<p>A tabbed design finally allows website visitors to see only the text they want without bombarding their senses with everything at once. A subtle red <em>New!</em> CTA does an excellent job of advertising a new product without taking up the whole page as it would before.</p>
</blockquote>
<h3>Web 2.0 - Going crazy</h3>
<p>Whitespace and careful design is fine, but users were quickly getting bored of uniform website designs. With the advent of Web 2.0 (see <em>Web 2.0</em>), focus quickly shifted to interactive website design. People were tired of mono themes and flat websites so designers quickly shifted to something new. Whether for the better or for the worse depends on if you ask someone with epilepsy or not.
Bright colors, crazed fonts, animate everything. These were the core lifeblood of this era. Web 2.0 allowed for much more interactive design, and everyone was scrambling to take advantage of it.
Kiddonet is probably the most famous example of this:
<img src="https://i.imgur.com/EeDIhCS.png" alt="Kiddonet's landing page in 2002"></p>
<blockquote>
<p>Filled with noise and colors. If viewing this site live, you'll notice that every element is moving in some way or another. I am not a very big fan of this era, nostalgia aside.</p>
</blockquote>
<h3>2010 Experiments - Skeuomorphic design</h3>
<p>A minor but notable trend in the history of web design is skeuomorphic design. People were still adjusting to new interfaces and technologies and skeuomorphic design aimed to bridge the real and virtual worlds. Until around 2013, Apple was maybe the most famous example of this design trend. Their iOS for iPhone was almost entirely skeuomorphic. For example, the notes app looked just like a notebook. And the calculator buttons were shaded to look three-dimensional. As if they were coming out of the screen. Due to the difficulty of effectively implementing this style, as well as the decreasing amount of need for an visually obvious style like this (people were now used to the internet and software having its own icon, it no longer needed to rely on visual cues from the real world as much).</p>
<blockquote>
<p>Unfortunately, I wasn't able to find any examples of skeuomorphic design on websites. Doing a web search on your search engine of choice will likely yield many good image examples, however.</p>
</blockquote>
<h3>Current Design - The corporate look</h3>
<p>Eventually, designers began to find new ways embracing both minimalism and interactive design. Websites began to take on a very uniform feel and look. Mass corporate rebranding also accented this new design paradigm well, with companies reducing colors, shading, and noise in their logos. Some view this new design trend as an ugly uniformity, others view it as the pinnacle of design. New technology from the trio (see <em>What is it that you see</em>) has allowed for much more responsive websites that can interact and change on a per-visitor basis as well as modify their own look and content based on how they are interacted with. As users began to adapt and become more and more familiar with the web, new priorities arose. No longer did people emphasize the intuitive design of skeuomorphism, as people got used to the new look of websites they began to emphasize speed instead. With so many options at people's fingertips, the difference of a tenth of a second loading something on a website could be the difference between a customer reading the website or leaving in search of something else. Corporate design also embraced another trend at its core; infinite scrolling. Now that browsers could support it better, websites began to take advantage of longer pages than ever before. This allowed users to scroll through it in one fluid motion, rather than forcing them to navigate a series of tabbed pages that could be very short and cause a lot of confusion if the layout was complicated.
The Obsidian homepage is a good example of this trend:
<img src="https://i.imgur.com/6n2jSoP.png" alt="Obsidian's landing page in 2023"></p>
<blockquote>
<p>The design of this website is both unique and standard. The soft text, minimal palette and lack of noise are both a curse and a boon for this website. The minimal design is pleasant, and nice to look at but also unfortunately blends right into all the other corporate websites on the internet.
<strong>Fun fact:</strong> Obsidian is the program I'm using to write this article right now.</p>
</blockquote>
<h2>Conclusion</h2>
<blockquote>
<p>To put it all together.</p>
</blockquote>
<p>The internet is a massive place, all this barely even scratches the surface of the massive web of interconnected technologies and tools we use on a daily basis. The internet is a complicated place, it's massive and full of so many different things. But it's also a place of creativity and art and human expression. It's a place where people fall in and out of love, a place where science happens, and discoveries are made. It's a place as familiar to most of us as a couch at home. The internet is here and it's not going away anytime soon.</p>
]]></content:encoded>
<guid isPermaLink="false">loveletter-to-the-internet</guid>
<pubDate>Mon, 09 Jan 2023 19:00:00 GMT</pubDate>
</item>
<item>
<title>Color Themes From Images</title>
<link>https://blog.trinket.icu/articles/color-themes-from-images</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>I really like colors. Often, I'll catch myself scrolling through Adobe Color, or clicking through Poolors just searching for the perfect color palette. And so when it came time to design the color themes for LightBlog I was pretty excited. I wanted to make a couple themes that were minimal, effective, and had a wide enough range to please most visitors who came to my site whether they needed high contrast themes, dark, super dark, light, etc. I packed all this into 4 base themes for the website. I called them Light, BlindWhite, Dark, and Amoled. These four themes would, I hoped, provide a wide enough range of colors and contrasts to make most people happy when using the website.
However, something still bugged me, I kept finding myself wanting to make more and more themes, but ultimately deciding not to because I didn't want to clog up the theme sidebar with options. I thought about adding pagination to it, but ultimately decided not to because I want the content of LightBlog to be what people spend time on, not clicking the more button looking for the perfect theme.
Of course, the perfect solution to this is to let the user make a theme for themselves but that comes with some pros and cons;
Pros:
Themes will (ideally) be exactly what that person wants
The theme can be a huge aid to accessibility because the colors can be adjusted to anything anyone needs.
Cons:
It takes a while to select each and every color and make sure it's perfect one by one.
It's a lot more effort than what I want to force people to go through just to have some nicer colors.
I toyed around with some color picker-type pages to let people design the themes they wanted but I just never liked how it looked.
Here's the scrappy tool I made to add my themes to the database:
Not very pretty eh?
I would never dream of forcing anyone who visits my site ever to try and make anything with that effective though it may be.
Eventually I came to the conclusion that 5 clicks to make a theme is 3 clicks too many. But how in the world do you select 10 colors with two clicks?
I remembered then, that some sites can extract color palettes from images. I've only ever seen this used as a gimmick, but I wondered if maybe, it could serve a practical use on my website..
This process is called color quantization and can be achieved using a variety of common algorithms. As a developer, there will never be a day where I don't learn something new I suppose.
I chose to use an algorithm called median-cut since it seemed to be the simplest and most common one used in these situations.
In fact, I was rather blown away by how easy it is to quantize an image with this algorithm. The steps are as follows:
Divide you image into its R, G, and B color channels.
Find the channel with the largest range from 0-255.
Sort all the channels according to the one with the highest range.
Cut all three channels in half.
Repeat the process until you have the amount of channel pieces as colors you want. Then average all three channel pieces together from each cut and let it resolve into a color.
That's kind of an awful description but this isn't a tutorial just an article.
I was pretty sure that was the solution to my 2-click problem! Just have them upload an image with colors they like and then do the rest of the work for them.
Well I implemented it pretty easily, here's a bit of code from the project:
function splitDataFor(data, count) {
let total = [];
for (let i = 0; i &amp;lt; count; i++) {
if (i == 0) {
data.forEach((block) =&amp;gt; {
block = preprocessSortQuantizeData(block);
total = total.concat(splitSortedData(block));
});
} else {
total.forEach((block) =&amp;gt; {
block = preprocessSortQuantizeData(block);
total = total.concat(splitSortedData(block));
});
}
}
return total;
}
This code will recursively split the channels into colors as many times as I want
The only problem here was that the colors came out in effectively a random order. I had no way of knowing what colors had more or less contrast which is a huge issue. The most important thing in any theme is that background colors and text colors must have sufficient contrast to be read easily.
So solve this issue, I would have to calculate the luminance of each color and sort it in that order. According to stack overflow, you do that like this:
lum() {
return 0.299 * this.r + 0.587 * this.g + 0.114 * this.b;
}
I hate magic numbers as much as the next dev, but stackoverflow commands so I obey.
If we just sort by luminance, then that should get the job done as far as contrast ratios are concerned.
Now, light mode and dark mode. I'm the kind of person who changes between light mode and dark mode so often I have a keybinding for it. I like to switch whenever the fancy strikes so it was of utmost importance that I could extract a dark palette and a light one from every image.
Turns out to do this all you have to do is flip the palette, switching the text to lighter and background to darker and vice-versa. Just array.reverse() everything until it works.
And that's just about it; extract colors, sort, display, and optionally reverse if the user wants to.
Some pros and cons of this method of theme-generation:
Pros:
Only two clicks per theme, one to upload an image, the other to set light or dark.
No need to have any knowledge of color theory, just need to have an image you like.
All processing is done in the browser so your images will always be only yours.
Cons:
All processing is done in the browser, so if the image is huge and you computer is slow it could take a minute to process.
It can be a but unpredictable and uploading the same image twice can make two different-but-similar color themes (this is by design, but I'm still putting it in cons).
If the image does not have enough different colors the theme could be really awful and I can't do much about that.
Overall, I'm really happy with how it turned out, and now I use LightBlog with my very own theme that's only mine on the entire internet.
Feel free to try it out with the direct link, or by clicking create.. at the bottom of the theme selector.
</description>
<content:encoded><![CDATA[<p>I really like colors. Often, I'll catch myself scrolling through <a href="https://color.adobe.com/explore">Adobe Color</a>, or clicking through <a href="https://poolors.com">Poolors</a> just searching for the perfect color palette. And so when it came time to design the color themes for LightBlog I was pretty excited. I wanted to make a couple themes that were minimal, effective, and had a wide enough range to please most visitors who came to my site whether they needed high contrast themes, dark, super dark, light, etc. I packed all this into 4 base themes for the website. I called them Light, BlindWhite, Dark, and Amoled. These four themes would, I hoped, provide a wide enough range of colors and contrasts to make most people happy when using the website.
However, something still bugged me, I kept finding myself wanting to make more and more themes, but ultimately deciding not to because I didn't want to clog up the theme sidebar with options. I thought about adding pagination to it, but ultimately decided not to because I want the content of LightBlog to be what people spend time on, not clicking the <code>more</code> button looking for the perfect theme.
Of course, the perfect solution to this is to let the user make a theme for themselves but that comes with some pros and cons;</p>
<p><strong>Pros:</strong></p>
<ul>
<li>Themes will (ideally) be exactly what that person wants</li>
<li>The theme can be a huge aid to accessibility because the colors can be adjusted to anything anyone needs.</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>It takes a while to select each and every color and make sure it's perfect one by one.</li>
<li>It's a lot more effort than what I want to force people to go through just to have some nicer colors.</li>
</ul>
<p>I toyed around with some color picker-type pages to let people design the themes they wanted but I just never liked how it looked.
Here's the scrappy tool I made to add my themes to the database:
<img src="https://i.imgur.com/R45DKoM.png" alt="my scrappy theme-making editor"></p>
<blockquote>
<p>Not very pretty eh?</p>
</blockquote>
<p>I would never dream of forcing anyone who visits my site ever to try and make anything with that effective though it may be.
Eventually I came to the conclusion that 5 clicks to make a theme is 3 clicks too many. <em>But how in the world do you select 10 colors with two clicks?</em>
I remembered then, that some sites can extract color palettes from images. I've only ever seen this used as a gimmick, but I wondered if maybe, it could serve a practical use on my website..
This process is called <a href="https://wikipedia.org/wiki/Color_quantization">color quantization</a> and can be achieved using a variety of common algorithms. As a developer, there will never be a day where I don't learn something new I suppose.
I chose to use an algorithm called <a href="https://wikipedia.org/wiki/Median_cut">median-cut</a> since it seemed to be the simplest and most common one used in these situations.
In fact, I was rather blown away by how easy it is to quantize an image with this algorithm. The steps are as follows:</p>
<ol>
<li>Divide you image into its R, G, and B color channels.</li>
<li>Find the channel with the largest range from 0-255.</li>
<li>Sort all the channels according to the one with the highest range.</li>
<li>Cut all three channels in half.</li>
<li>Repeat the process until you have the amount of channel pieces as colors you want. Then average all three channel pieces together from each cut and let it resolve into a color.</li>
</ol>
<blockquote>
<p>That's kind of an awful description but this isn't a tutorial just an article.</p>
</blockquote>
<p>I was pretty sure that was the solution to my 2-click problem! Just have them upload an image with colors they like and then do the rest of the work for them.
Well I implemented it pretty easily, here's a bit of code from the project:</p>
<pre><code class="language-typescript">function splitDataFor(data, count) {
let total = [];
for (let i = 0; i &lt; count; i++) {
if (i == 0) {
data.forEach((block) =&gt; {
block = preprocessSortQuantizeData(block);
total = total.concat(splitSortedData(block));
});
} else {
total.forEach((block) =&gt; {
block = preprocessSortQuantizeData(block);
total = total.concat(splitSortedData(block));
});
}
}
return total;
}
</code></pre>
<blockquote>
<p>This code will recursively split the channels into colors as many times as I want</p>
</blockquote>
<p>The only problem here was that the colors came out in effectively a random order. I had no way of knowing what colors had more or less contrast which is a huge issue. The most important thing in any theme is that background colors and text colors <strong>must</strong> have sufficient contrast to be read easily.
So solve this issue, I would have to calculate the luminance of each color and sort it in that order. According to stack overflow, you do that like this:</p>
<pre><code class="language-typescript"> lum() {
return 0.299 * this.r + 0.587 * this.g + 0.114 * this.b;
}
</code></pre>
<blockquote>
<p>I hate magic numbers as much as the next dev, but stackoverflow commands so I obey.</p>
</blockquote>
<p>If we just sort by luminance, then that should get the job done as far as contrast ratios are concerned.
Now, light mode and dark mode. I'm the kind of person who changes between light mode and dark mode so often I have a keybinding for it. I like to switch whenever the fancy strikes so it was of utmost importance that I could extract a dark palette <em>and</em> a light one from every image.
Turns out to do this all you have to do is flip the palette, switching the text to lighter and background to darker and vice-versa. Just <code>array.reverse()</code> everything until it works.</p>
<p>And that's just about it; extract colors, sort, display, and optionally reverse if the user wants to.</p>
<p>Some pros and cons of this method of theme-generation:
<strong>Pros:</strong></p>
<ul>
<li>Only two clicks per theme, one to upload an image, the other to set light or dark.</li>
<li>No need to have any knowledge of color theory, just need to have an image you like.</li>
<li>All processing is done in the browser so your images will always be only yours.
<strong>Cons:</strong></li>
<li>All processing is done in the browser, so if the image is huge and you computer is slow it could take a minute to process.</li>
<li>It can be a but unpredictable and uploading the same image twice can make two different-but-similar color themes (this is by design, but I'm still putting it in cons).</li>
<li>If the image does not have enough different colors the theme could be really awful and I can't do much about that.</li>
</ul>
<p>Overall, I'm really happy with how it turned out, and now I use LightBlog with my very own theme that's only mine on the entire internet.</p>
<p>Feel free to try it out with the <a href="/rand/makeatheme">direct link</a>, or by clicking <code>create..</code> at the bottom of the theme selector.</p>
]]></content:encoded>
<guid isPermaLink="false">color-themes-from-images</guid>
<pubDate>Thu, 24 Nov 2022 19:00:00 GMT</pubDate>
</item>
<item>
<title>Programmer Pastimes</title>
<link>https://blog.trinket.icu/articles/programmer-pastimes</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>I often hear people say that the brain is like a muscle, using it makes it stronger, but also wears it out. If that's the case, the programming is like going to the gym 8 hours a day. Now I wouldn't say that my brain is the metaphorical equivalent to Dwayne Johnson, but I would say that he and I both get tired out after working too hard. I'm not sure what Dwayne does in his pastime (if he has pastime), but I do know that I like to do a few things. I like to play video games, or read a book, or watch some fireship on youtube (really, that guy is the king of programming content in my opinion). Everyone has some way of just relaxing and zoning out when their brain is overworked and I think it's a fascinating thing.
I don't think having a zone-out pastime is really an escapism method because I know I don't mind my life all that much. I also don't think it's a laziness thing because I naturally balance pastime and work-time in my life without much struggle. I think maybe it's just a way for the clockwork in our heads to wind itself up again, ready for us to tick it down to a standstill as soon as possible.
I personally like to take out some old book I know I like and begin my nth reread of it. Or maybe play some small video game on my phone for a few minutes (I'm pretty killer at soul knight by now). I especially like games that have an instant autosave feature. That way, I can put it away and then pick up exactly where I left off.
I'm sure those people exist who can just power through the whole day, every day and are either zombies, or full of motivation that eventually leads to burnout. I however, am not, and I find that taking small breaks is an excellent way to 'ration' motivation indefinitely.
</description>
<content:encoded><![CDATA[<p>I often hear people say that the brain is like a muscle, using it makes it stronger, but also wears it out. If that's the case, the programming is like going to the gym 8 hours a day. Now I wouldn't say that my brain is the metaphorical equivalent to Dwayne Johnson, but I would say that he and I both get tired out after working too hard. I'm not sure what Dwayne does in his pastime (if he has pastime), but I do know that I like to do a few things. I like to play video games, or read a book, or watch some fireship on youtube (really, that guy is the king of programming content in my opinion). Everyone has some way of just relaxing and zoning out when their brain is overworked and I think it's a fascinating thing.
I don't think having a zone-out pastime is really an escapism method because I know I don't mind my life all that much. I also don't think it's a laziness thing because I naturally balance pastime and work-time in my life without much struggle. I think maybe it's just a way for the clockwork in our heads to wind itself up again, ready for us to tick it down to a standstill as soon as possible.
I personally like to take out some old book I know I like and begin my nth reread of it. Or maybe play some small video game on my phone for a few minutes (I'm pretty killer at soul knight by now). I especially like games that have an instant autosave feature. That way, I can put it away and then pick up exactly where I left off.
I'm sure those people exist who can just power through the whole day, every day and are either zombies, or full of motivation that eventually leads to burnout. I however, am not, and I find that taking small breaks is an excellent way to 'ration' motivation indefinitely.</p>
]]></content:encoded>
<guid isPermaLink="false">programmer-pastimes</guid>
<pubDate>Tue, 01 Nov 2022 19:00:00 GMT</pubDate>
</item>
<item>
<title>Link Page</title>
<link>https://blog.trinket.icu/articles/linkpage</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>Evil Overlord List
Manifest V3 Before Launch
Bias Monitor {untested}
Echoes of a Black Hole
Terms of Service, Didn't Read
Ian's Shoelace Site
A Guide to the Gallifreyan Alphabet
Internet Live Stats
WannaCry
Apollo-11
TOML
Free Programming Books
Ricing Tools
Ani-Cli
Terminal Color Schemes
Poolors
Dictionary of Perceptible Joys
mystery link
</description>
<content:encoded><![CDATA[<p><a href="http://www.eviloverlord.com/lists/overlord.html">Evil Overlord List</a></p>
<p><a href="https://www.eff.org/deeplinks/2021/11/manifest-v3-open-web-politics-sheeps-clothing">Manifest V3 Before Launch</a></p>
<p><a href="https://github.com/Alex0Blackwell/bias-monitor">Bias Monitor {untested}</a></p>
<p><a href="https://news.mit.edu/2022/search-reveals-eight-new-sources-black-hole-echoes-0502">Echoes of a Black Hole</a></p>
<p><a href="https://tosdr.org">Terms of Service, Didn't Read</a></p>
<p><a href="https://www.fieggen.com/shoelace/index.htm">Ian's Shoelace Site</a></p>
<p><a href="https://shermansplanet.com/gallifreyan/guide.pdf">A Guide to the Gallifreyan Alphabet</a></p>
<p><a href="https://www.internetlivestats.com">Internet Live Stats</a></p>
<p><a href="https://github.com/Explodingstuff/WannaCry">WannaCry</a></p>
<p><a href="https://github.com/chrislgarry/Apollo-11">Apollo-11</a></p>
<p><a href="https://toml.io">TOML</a></p>
<p><a href="https://ebookfoundation.github.io/free-programming-books/">Free Programming Books</a></p>
<p><a href="https://github.com/fosslife/awesome-ricing">Ricing Tools</a></p>
<p><a href="https://github.com/pystardust/ani-cli">Ani-Cli</a></p>
<p><a href="https://gogh-co.github.io/Gogh/">Terminal Color Schemes</a></p>
<p><a href="https://poolors.com">Poolors</a></p>
<p><a href="https://dictionaryofperceptiblejoys-blog.tumblr.com">Dictionary of Perceptible Joys</a></p>
<hr>
<p><a href="/old"><strong>mystery link</strong></a></p>
]]></content:encoded>
<guid isPermaLink="false">linkpage</guid>
<pubDate>Mon, 24 Oct 2022 19:00:00 GMT</pubDate>
</item>
<item>
<title>Learning to Code</title>
<link>https://blog.trinket.icu/articles/learning-to-code</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>You know, when I decided to sit down and learn to code it was because I had just played a video game called The Pathless. The Pathless* touched my soul in a way that was new to me. Something about the story, visuals, and my part in all of it really made me feel something new-- inspiration.
I promptly decided I was going to be a AAA game developer. Imagine that, a 13 year old kid wasting a road trip on a video game and finding his life inspiration on a car the trip across a few states.
I promptly sat down in front of a 2012 MacBook Pro (the only computer available to me at the time) and googled &amp;quot;How to make video games&amp;quot;. Well that was my first internet rabbit hole, I kept seeing terms like Game Engine, 3D design and animation, and the most daunting of all; Programming. I was determined though, and a patchy vocabulary was not going to be the end of my moment of inspiration. I made a list of all the terms I didn't know and googled them separately.
After a night of internetting I went to sleep excited. I still didn't know what a game engine was, but I certainly felt like I'd made progress.
Bright and early the next day I began to research game engines until I felt like I understood what they were; I was pretty sure a game engine was the thing that took my idea for a game, and all my art and instructions on how it should run and made it into code for me. Perfect! I didn't really know how to code and I was fine with that.
I downloaded Unity and got to work. ..For about 10 minutes and then I realized that this was not a software I could just fat fingers my way through and make sense of. Well reader, I called it quits then. I decided game design maybe just wasn't my thing and to study on more realistic goals for a 13yr-old.
A few years passed, recently I has gotten back into writing and story creation-- i.e. I played a lot of DnD. I had been writing a lot of movie script-style short stories and really enjoying it, so I decided to start looking at cinematography. I had a Canon camera, so I did a lot of photography, I figured it would be a simple enough endeavor to start make short films.
That failed. I just couldn't invest the time and effort to create something I was satisfied with, not to mention my continuous failure to meet my own standards just made me push myself away from that niche. Well, I thought, aren't animated movies a thing? Can I make short films on a computer? According to google, I could! I wasted no time redownloading Unity because the word cinemachine was too cool not to figure out how to use it. Well, history may not repeat, but it sure does rhyme. I found myself in the same predicament of not knowing how to make the application do what I wanted it to do. I gave up on Unity again, but my desire to create a game had grown again.
I had recently played some games by Appsir Games**, and I remembered seeing somewhere that they used a game engine called Buildbox. Well, I looked it up and learned all about no-code-tools. History rhymes like a motherfucker and so the download, open, have-no-idea-what-I'm-doing cycle repeated.
This time however, I stuck it through and watched some videos. Not much, I build a little driving obstacle-course simulator and sent it to my gamer friend as an unsigned EXE (The next 20 minutes were a frantic Discord call of me pleading with him to open it, and him saying his PC was saying it was untrusted).
That one simple experience turned into more complex game projects until finally, it happened. I ran into a problem I couldn't fix with nodes. I found a snippet of code on some forums somewhere on the internet and it worked, so I kept working on my new game project.
Something kept nagging me though; amidst all these nodes and networks, there was a little snippet of code making it all work and I had no idea how. This bothered me more than I expected so I sat down and began reading the 20 lines or so. I read them again and again, and looked up the words I didn't know until I did.
It worked, and I began to understand what I was reading, and it was fascinating. These twenty lines of code were doing things I would have spent hours dragging nodes to achieve.
I was set, it was time to learn to code, and nothing could stop me now.
I took my mom's 2014 MacBook Air that she'd just gotten for college and downloaded the Swift Playgrounds app.
The following month, I spent most nights dragging little blocks and snippets of code to solve the puzzles presented to me.
I didn't learn how to code from that app, but it did teach me what if statements are, what a function is, and most importantly, it imprinted DRY into me as my first experience of code design.
Once I finished with Swift Playgrounds, I wanted to do something big. Make an app, a video game, something. But the problem was, I knew what my code should do and how, I just had no idea what to actually type.
In that same area of time, was my first month of freshman year in highschool. We had an assignment to pick a dream of ours and see how close we could get to realizing it in a month.
I told them I wanted to make a text-adventure game like Zork (which I absolutely loved, but had never actually beaten).
The school issued me an old MacBook (they were everywhere when I was a kid), and I got to work. First, I had to find some way to teach myself code. I figured YouTube was a great place to start only the school had most content streaming platforms blocked on the network. I actually managed to find an old archive of this guy explaining the fundamentals of C# that wasn't blocked so I decided my game would be written in C#.
I spent about a month watching about 2 hours of lecture a day + coding along,
and by the end of it, I had done it! I had a C# text-adventure game! It only had 5 choices, and no real ending, and sometimes it just broke, but still! I had done it!
That rush of dopamine, the satisfaction of a (semi)working program was all it took to fall down the rabbit hole.
I asked my family for a Codecademy subscription for Christmas and took their Python course. Then, I took their HTML and CSS course. Then their JS course and you get it. I ate it all up trying to get as much knowledge as possible continuously.
That cycle repeated until I fell into tutorial hell. The way I got out of that was by getting programming books, actually. My dad got me a book about the command line from NoStarchPress***, and it taught me so much.
Now, I've progressed much in my quest for knowledge, but I often feel like I'm walking up the infinite spiral staircase from the Phantom Tollbooth, always moving, always learning, and yet no closer to the end at all.
* A genuinely amazing game, check it out if you have time. About 4 hours to beat normally, about 12 hours worth of content and open-world exploration if you want to 100% the game.
** An incredible indie developer who spits out some of the only platformer adventure games I've had the patience to play through (in fact I've played most of their games more than a few times. It's a monthly ritual for me).
*** Any book from NoStarchPress will teach anyone tons, I never get bored of their stuff.
</description>
<content:encoded><![CDATA[<p>You know, when I decided to sit down and learn to code it was because I had just played a video game called <a href="https://thepathless.com">The Pathless</a>. The Pathless* touched my soul in a way that was new to me. Something about the story, visuals, and my part in all of it really made me feel something new-- <em>inspiration</em>.</p>
<p>I promptly decided I was going to be a AAA game developer. Imagine that, a 13 year old kid wasting a road trip on a video game and finding his life inspiration on a car the trip across a few states.</p>
<p>I promptly sat down in front of a 2012 MacBook Pro (the only computer available to me at the time) and googled <em>&quot;How to make video games&quot;</em>. Well that was my first internet rabbit hole, I kept seeing terms like <em>Game Engine</em>, <em>3D design and animation</em>, and the most daunting of all; <em>Programming</em>. I was determined though, and a patchy vocabulary was not going to be the end of my moment of inspiration. I made a list of all the terms I didn't know and googled them separately.</p>
<p>After a night of internetting I went to sleep excited. I still didn't know what a <em>game engine</em> was, but I certainly felt like I'd made progress.</p>
<p>Bright and early the next day I began to research game engines until I felt like I understood what they were; I was pretty sure a game engine was the thing that took my idea for a game, and all my art and instructions on how it should run and made it into code for me. Perfect! I didn't really know how to code and I was fine with that.</p>
<p>I downloaded Unity and got to work. ..For about 10 minutes and then I realized that this was not a software I could just fat fingers my way through and make sense of. Well reader, I called it quits then. I decided game design maybe just wasn't my thing and to study on more realistic goals for a 13yr-old.</p>
<p>A few years passed, recently I has gotten back into writing and story creation-- i.e. I played a lot of DnD. I had been writing a lot of movie script-style short stories and really enjoying it, so I decided to start looking at cinematography. I had a Canon camera, so I did a lot of photography, I figured it would be a simple enough endeavor to start make short films.</p>
<p>That failed. I just couldn't invest the time and effort to create something I was satisfied with, not to mention my continuous failure to meet my own standards just made me push myself away from that niche. Well, I thought, aren't animated movies a thing? Can I make short films on a computer? According to google, I could! I wasted no time redownloading Unity because the word <em>cinemachine</em> was too cool not to figure out how to use it. Well, history may not repeat, but it sure does rhyme. I found myself in the same predicament of not knowing how to make the application do what I wanted it to do. I gave up on Unity again, but my desire to create a game had grown again.</p>
<p>I had recently played some games by <a href="https://www.appsirgames.com">Appsir Games**</a>, and I remembered seeing somewhere that they used a game engine called Buildbox. Well, I looked it up and learned all about no-code-tools. History rhymes like a motherfucker and so the download, open, have-no-idea-what-I'm-doing cycle repeated.</p>
<p>This time however, I stuck it through and watched some videos. Not much, I build a little driving obstacle-course simulator and sent it to my gamer friend as an unsigned EXE (The next 20 minutes were a frantic Discord call of me pleading with him to open it, and him saying his PC was saying it was untrusted).</p>
<p>That one simple experience turned into more complex game projects until finally, it happened. I ran into a problem I couldn't fix with nodes. I found a snippet of code on some forums somewhere on the internet and it worked, so I kept working on my new game project.</p>
<p>Something kept nagging me though; amidst all these nodes and networks, there was a little snippet of code making it all work <em>and I had no idea how</em>. This bothered me more than I expected so I sat down and began reading the 20 lines or so. I read them again and again, and looked up the words I didn't know until I did.</p>
<p>It worked, and I began to understand what I was reading, and it was <em>fascinating</em>. These twenty lines of code were doing things I would have spent hours dragging nodes to achieve.</p>
<p>I was set, it was time to learn to code, and nothing could stop me now.</p>
<p>I took my mom's 2014 MacBook Air that she'd just gotten for college and downloaded the Swift Playgrounds app.</p>
<p>The following month, I spent most nights dragging little blocks and snippets of code to solve the puzzles presented to me.</p>
<p>I didn't learn how to code from that app, but it did teach me what if statements are, what a function is, and most importantly, it imprinted DRY into me as my first experience of code design.</p>
<p>Once I finished with Swift Playgrounds, I wanted to do something big. Make an app, a video game, <em>something</em>. But the problem was, I knew what my code should do and how, I just had no idea what to actually type.</p>
<p>In that same area of time, was my first month of freshman year in highschool. We had an assignment to pick a dream of ours and see how close we could get to realizing it in a month.
I told them I wanted to make a text-adventure game like <a href="https://wikipedia.org/wiki/Zork">Zork</a> (which I absolutely loved, but had never actually beaten).</p>
<p>The school issued me an old MacBook (they were everywhere when I was a kid), and I got to work. First, I had to find some way to teach myself code. I figured YouTube was a great place to start only the school had most content streaming platforms blocked on the network. I actually managed to find an old archive of this guy explaining the fundamentals of C# that wasn't blocked so I decided my game would be written in C#.</p>
<p>I spent about a month watching about 2 hours of lecture a day + coding along,
and by the end of it, I had done it! I had a C# text-adventure game! It only had 5 choices, and no real ending, and sometimes it just broke, but still! I had done it!
That rush of dopamine, the satisfaction of a (semi)working program was all it took to fall down the rabbit hole.</p>
<p>I asked my family for a Codecademy subscription for Christmas and took their Python course. Then, I took their HTML and CSS course. Then their JS course and you get it. I ate it all up trying to get as much knowledge as possible continuously.</p>
<p>That cycle repeated until I fell into tutorial hell. The way I got out of that was by getting programming books, actually. My dad got me a book about the command line from NoStarchPress***, and it taught me so much.</p>
<p>Now, I've progressed much in my quest for knowledge, but I often feel like I'm walking up the infinite spiral staircase from the Phantom Tollbooth, always moving, always learning, and yet no closer to the end at all.</p>
<hr>
<blockquote>
<p>* A genuinely amazing game, check it out if you have time. About 4 hours to beat normally, about 12 hours worth of content and open-world exploration if you want to 100% the game.</p>
</blockquote>
<blockquote>
<p>** An incredible indie developer who spits out some of the only platformer adventure games I've had the patience to play through (in fact I've played most of their games more than a few times. It's a monthly ritual for me).</p>
</blockquote>
<blockquote>
<p>*** Any book from NoStarchPress will teach anyone tons, I never get bored of their stuff.</p>
</blockquote>
]]></content:encoded>
<guid isPermaLink="false">learning-to-code</guid>
<pubDate>Sat, 15 Oct 2022 19:00:00 GMT</pubDate>
</item>
<item>
<title>Routing in Svelte</title>
<link>https://blog.trinket.icu/articles/routing-in-svelte</link>
2023-12-19 18:02:34 +00:00
<dc:creator>Shav Kinderlehrer</dc:creator>
<description>Yes, you read that right. Routing in Svelte, not routing in SvelteKit. Light Blog was originally written in SvelteKit, but I found that trying to develop using SvelteKit while still in beta was a nightmare. Basic features constantly breaking, weird bugs I couldn't fix within the website, constantly changing apis. That's not to say that I don't like SvelteKit, everything it does it does amazingly and it was a joy to code in it. I just couldn't make anything functional in the state it was in. Perhaps that's my bad code, or it could be the framework being in beta.
Once I admitted defeat and decided to rewrite Light Blog I began looking for a new framework to build it in because vanilla JS/TS is a nightmare (in my humble opinion). React makes my head hurt, I didn't know what web components were, and I really like SvelteKit's SFC system. I didn't want to learn a new framework (Vuejs), and Qwik wasn't going to come out for another month.
I was in a corner (admittedly, one I put myself in), I had a site to make, but no framework I was excited to use. But then I had an idea, it occurred to me that most URLs are a path name like you would use in a terminal.
# Go to about page
cd pages/about
cat index.html
&amp;lt;!-- Link To About Page --&amp;gt;
&amp;lt;a href=&amp;quot;pages/about/index.html&amp;quot;&amp;gt;Link to about page&amp;lt;a&amp;gt;
In my head, these two were very strongly linked (pun intended). That's why a lot of frameworks have file-based-routers, the files of code you write directly define the webpages accessible on your website. Something I like about OOP is that it states that everything can be put into a box. Sometimes things shouldn't be forced into boxes, but a lot of the times it fits nicely. I wanted to see if a URL could fit into a 'box'. Turns out it does and has for a long time, no need to reinvent the wheel here, it's called window.location.
I began to wonder, if I already have the 'box' of the URL, what can I do with it?
Well, I thought, maybe instead of file-based-routes, I could try and put the pages in a box as well. I came up with a structure that looked like this:
{
&amp;quot;routes&amp;quot;: [
{
&amp;quot;title&amp;quot;: &amp;quot;Home&amp;quot;,
&amp;quot;desc&amp;quot;: &amp;quot;Dev blog about everything under the sun&amp;quot;,
&amp;quot;slug&amp;quot;: &amp;quot;/&amp;quot;,
&amp;quot;path&amp;quot;: &amp;quot;index&amp;quot;,
&amp;quot;sidebar&amp;quot;: true,
&amp;quot;level&amp;quot;: 0
},
{
&amp;quot;title&amp;quot;: &amp;quot;Articles&amp;quot;,
&amp;quot;desc&amp;quot;: &amp;quot;Find articles to read about many topics&amp;quot;,
&amp;quot;slug&amp;quot;: &amp;quot;/articles&amp;quot;,
&amp;quot;path&amp;quot;: &amp;quot;articles&amp;quot;,
&amp;quot;sidebar&amp;quot;: false,
&amp;quot;level&amp;quot;: 1,
&amp;quot;subroutes&amp;quot;: [
{
&amp;quot;title&amp;quot;: &amp;quot;Not Found Error&amp;quot;,
&amp;quot;desc&amp;quot;: &amp;quot;An article at this URL doesn't exist yet&amp;quot;,
&amp;quot;slug&amp;quot;: &amp;quot;/articles/notFound&amp;quot;,
&amp;quot;path&amp;quot;: &amp;quot;articles/notFound&amp;quot;,
&amp;quot;sidebar&amp;quot;: false,
&amp;quot;level&amp;quot;: 2
},
{
&amp;quot;title&amp;quot;: &amp;quot;*&amp;quot;,
&amp;quot;desc&amp;quot;: &amp;quot;[DYNAMIC]&amp;quot;,
&amp;quot;slug&amp;quot;: &amp;quot;/articles/*&amp;quot;,
&amp;quot;path&amp;quot;: &amp;quot;articles/slug&amp;quot;,
&amp;quot;sidebar&amp;quot;: true,
&amp;quot;level&amp;quot;: 2
}
]
},
{
&amp;quot;title&amp;quot;: &amp;quot;About&amp;quot;,
&amp;quot;desc&amp;quot;: &amp;quot;How this website works and how to use it&amp;quot;,
&amp;quot;slug&amp;quot;: &amp;quot;/about&amp;quot;,
&amp;quot;path&amp;quot;: &amp;quot;about&amp;quot;,
&amp;quot;sidebar&amp;quot;: &amp;quot;true&amp;quot;,
&amp;quot;level&amp;quot;: 1
}
]
}
So now I had an object for the URL and an object for the pages, I wondered if that wasn't enough to handle routing without file-based-routing.
Well, I figured, if an SPA made in Svelte were to try and combine Sveltes enjoyability with these boxes it would work perfectly fine.
It didn't.
It took a whole lot of code and a whole lot of frustration, but eventually I did it, I managed to create a system to compare the URL to the pages json and return a 'state' that the rest of the website reacted to. Here's the code for it:
function parseSlug(slug = window.location.pathname) {
let returnUrlState = deepCopy(urlState);
let backupUrlState;
const slugLayers = slug.split(&amp;quot;/&amp;quot;).filter((el) =&amp;gt; {
return el !== &amp;quot;&amp;quot;;
});
if (slugLayers.length === 0) slugLayers.push(&amp;quot;&amp;quot;);
let fullPath = &amp;quot;&amp;quot;;
slugLayers.forEach((layer, index) =&amp;gt; {
let urlStateSetThisLayer = false;
fullPath += `/${layer}`;
routes.forEach((route) =&amp;gt; {
if (route.slug === fullPath &amp;amp;&amp;amp; !urlStateSetThisLayer) {
returnUrlState = deepCopy(route);
urlStateSetThisLayer = true;
if (returnUrlState.subroutes &amp;amp;&amp;amp; index != slugLayers.length - 1)
backupUrlState = deepCopy(returnUrlState);
return;
}
});
if (!returnUrlState.subroutes || urlStateSetThisLayer) return;
returnUrlState.subroutes.forEach((subroute) =&amp;gt; {
if (subroute.slug === fullPath &amp;amp;&amp;amp; !urlStateSetThisLayer) {
returnUrlState = deepCopy(subroute);
urlStateSetThisLayer = true;
if (returnUrlState.subroutes &amp;amp;&amp;amp; index != slugLayers.length - 1)
backupUrlState = deepCopy(returnUrlState);
return;
} else if (subroute.slug.endsWith(&amp;quot;*&amp;quot;) &amp;amp;&amp;amp; !urlStateSetThisLayer) {
returnUrlState = deepCopy(subroute);
returnUrlState.title = layer;
urlStateSetThisLayer = true;
if (returnUrlState.subroutes &amp;amp;&amp;amp; index != slugLayers.length - 1)
backupUrlState = deepCopy(returnUrlState);
return;
}
});
});
if (JSON.stringify(returnUrlState) === JSON.stringify(backupUrlState)) {
returnUrlState = error;
returnUrlState.desc = &amp;quot;NotFoundError&amp;quot;;
returnUrlState.slug = window.location.pathname;
}
returnUrlState.slug = fullPath;
return returnUrlState;
}
Robert C. Martin would be disappointed in me for this.
Now, if you actually read the entire block of code (I wouldn't have, it's pretty ugly), then you may have noticed this little block:
//...
if (/*condition*/){
//...
} else if (subroute.slug.endsWith(&amp;quot;*&amp;quot;) &amp;amp;&amp;amp; !urlStateSetThisLayer) {
returnUrlState = deepCopy(subroute);
returnUrlState.title = layer;
urlStateSetThisLayer = true;
if (returnUrlState.subroutes &amp;amp;&amp;amp; index != slugLayers.length - 1)
backupUrlState = deepCopy(returnUrlState);
return;
}
//...
Notably, subroute.slug.endsWith(&amp;quot;*&amp;quot;). I added that because I liked how SvelteKit has dynamic routing, where a URL can accept any slug and change the page content accordingly. For example /articles/hello-world and /articles/foobarbaz actually load the same page that has access to the hello-world and foobarbaz slugs and can change their own content accordingly. I did this because I'm a lazy programmer and I didn't want more than a few pages to implement.
Well this parseSlug() function took a long time to make work, and even longer to fix the biggest bugs (I'm confident there's still a good few waiting for when I let my guard down).
I was pretty happy with my work, it functioned, it only broke here and there, and it meant I got to use Svelte i love svelte.
So TL;DR I was too lazy to learn a new framework and so accidentally made a worse version of existing ones (the classic tale of every web dev).
Some pros and cons I can think of right now:
Pros:
Extremely fast links since no reloads are necessary
Data persistence across all pages
Cons:
All the pages have to be loaded on first load, this slows down the website.
This hell:
switch (urlState.path) {
case &amp;quot;index&amp;quot;:
displayPage = index;
break;
case &amp;quot;articles&amp;quot;:
displayPage = articles;
break;
case &amp;quot;articles/notFound&amp;quot;:
displayPage = notFound;
break;
case &amp;quot;articles/slug&amp;quot;:
displayPage = slug;
break;
//..
I have to do this because of how Svelte components work
Do what you want to make your website work, I'm not making an industry that hinges on 200ms faster page load time.
</description>
<content:encoded><![CDATA[<p>Yes, you read that right. Routing in Svelte, not routing in <em>SvelteKit</em>. Light Blog was originally written in SvelteKit, but I found that trying to develop using SvelteKit while still in beta was a nightmare. Basic features constantly breaking, weird bugs I couldn't fix within the website, constantly changing apis. That's not to say that I don't like SvelteKit, everything it does it does amazingly and it was a joy to code in it. I just couldn't make anything functional in the state it was in. Perhaps that's my bad code, or it could be the framework being in beta.</p>
<p>Once I admitted defeat and decided to rewrite Light Blog I began looking for a new framework to build it in because vanilla JS/TS is a nightmare (in my humble opinion). React makes my head hurt, I didn't know what web components were, and I really like SvelteKit's <a href="https://dev.to/vannsl/all-you-need-to-know-to-start-writing-svelte-single-file-components-cbd">SFC system</a>. I didn't want to learn a new framework (Vuejs), and Qwik wasn't going to come out for another month.</p>
<p>I was in a corner (admittedly, one I put myself in), I had a site to make, but no framework I was excited to use. But then I had an idea, it occurred to me that most URLs are a path name like you would use in a terminal.</p>
<pre><code class="language-bash"># Go to about page
cd pages/about
cat index.html
</code></pre>
<pre><code class="language-html">&lt;!-- Link To About Page --&gt;
&lt;a href=&quot;pages/about/index.html&quot;&gt;Link to about page&lt;a&gt;
</code></pre>
<p>In my head, these two were very strongly linked (pun intended). That's why a lot of frameworks have <a href="https://kit.svelte.dev/docs/routing">file-based-routers</a>, the files of code you write directly define the webpages accessible on your website. Something I like about <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a> is that it states that everything can be put into a box. Sometimes things <em>shouldn't</em> be forced into boxes, but a lot of the times it fits nicely. I wanted to see if a URL could fit into a 'box'. Turns out it does and has for a long time, no need to reinvent the wheel here, it's called <code>window.location</code>.
I began to wonder, if I already have the 'box' of the URL, what can I do with it?</p>
<p>Well, I thought, maybe instead of file-based-routes, I could try and put the pages in a box as well. I came up with a structure that looked like this:</p>
<pre><code class="language-json">{
&quot;routes&quot;: [
{
&quot;title&quot;: &quot;Home&quot;,
&quot;desc&quot;: &quot;Dev blog about everything under the sun&quot;,
&quot;slug&quot;: &quot;/&quot;,
&quot;path&quot;: &quot;index&quot;,
&quot;sidebar&quot;: true,
&quot;level&quot;: 0
},
{
&quot;title&quot;: &quot;Articles&quot;,
&quot;desc&quot;: &quot;Find articles to read about many topics&quot;,
&quot;slug&quot;: &quot;/articles&quot;,
&quot;path&quot;: &quot;articles&quot;,
&quot;sidebar&quot;: false,
&quot;level&quot;: 1,
&quot;subroutes&quot;: [
{
&quot;title&quot;: &quot;Not Found Error&quot;,
&quot;desc&quot;: &quot;An article at this URL doesn't exist yet&quot;,
&quot;slug&quot;: &quot;/articles/notFound&quot;,
&quot;path&quot;: &quot;articles/notFound&quot;,
&quot;sidebar&quot;: false,
&quot;level&quot;: 2
},
{
&quot;title&quot;: &quot;*&quot;,
&quot;desc&quot;: &quot;[DYNAMIC]&quot;,
&quot;slug&quot;: &quot;/articles/*&quot;,
&quot;path&quot;: &quot;articles/slug&quot;,
&quot;sidebar&quot;: true,
&quot;level&quot;: 2
}
]
},
{
&quot;title&quot;: &quot;About&quot;,
&quot;desc&quot;: &quot;How this website works and how to use it&quot;,
&quot;slug&quot;: &quot;/about&quot;,
&quot;path&quot;: &quot;about&quot;,
&quot;sidebar&quot;: &quot;true&quot;,
&quot;level&quot;: 1
}
]
}
</code></pre>
<p>So now I had an object for the URL and an object for the pages, I wondered if that wasn't enough to handle routing without file-based-routing.</p>
<p>Well, I figured, if an <a href="https://en.wikipedia.org/wiki/Single-page_application">SPA</a> made in Svelte were to try and combine Sveltes enjoyability with these boxes it would work perfectly fine.</p>
<p>It didn't.</p>
<p>It took a whole lot of code and a whole lot of frustration, but eventually I did it, I managed to create a system to compare the URL to the pages json and return a 'state' that the rest of the website reacted to. Here's the code for it:</p>
<pre><code class="language-ts">function parseSlug(slug = window.location.pathname) {
let returnUrlState = deepCopy(urlState);
let backupUrlState;
const slugLayers = slug.split(&quot;/&quot;).filter((el) =&gt; {
return el !== &quot;&quot;;
});
if (slugLayers.length === 0) slugLayers.push(&quot;&quot;);
let fullPath = &quot;&quot;;
slugLayers.forEach((layer, index) =&gt; {
let urlStateSetThisLayer = false;
fullPath += `/${layer}`;
routes.forEach((route) =&gt; {
if (route.slug === fullPath &amp;&amp; !urlStateSetThisLayer) {
returnUrlState = deepCopy(route);
urlStateSetThisLayer = true;
if (returnUrlState.subroutes &amp;&amp; index != slugLayers.length - 1)
backupUrlState = deepCopy(returnUrlState);
return;
}
});
if (!returnUrlState.subroutes || urlStateSetThisLayer) return;
returnUrlState.subroutes.forEach((subroute) =&gt; {
if (subroute.slug === fullPath &amp;&amp; !urlStateSetThisLayer) {
returnUrlState = deepCopy(subroute);
urlStateSetThisLayer = true;
if (returnUrlState.subroutes &amp;&amp; index != slugLayers.length - 1)
backupUrlState = deepCopy(returnUrlState);
return;
} else if (subroute.slug.endsWith(&quot;*&quot;) &amp;&amp; !urlStateSetThisLayer) {
returnUrlState = deepCopy(subroute);
returnUrlState.title = layer;
urlStateSetThisLayer = true;
if (returnUrlState.subroutes &amp;&amp; index != slugLayers.length - 1)
backupUrlState = deepCopy(returnUrlState);
return;
}
});
});
if (JSON.stringify(returnUrlState) === JSON.stringify(backupUrlState)) {
returnUrlState = error;
returnUrlState.desc = &quot;NotFoundError&quot;;
returnUrlState.slug = window.location.pathname;
}
returnUrlState.slug = fullPath;
return returnUrlState;
}
</code></pre>
<blockquote>
<p>Robert C. Martin would be disappointed in me for this.</p>
</blockquote>
<p>Now, if you actually read the entire block of code (I wouldn't have, it's pretty ugly), then you may have noticed this little block:</p>
<pre><code class="language-ts">//...
if (/*condition*/){
//...
} else if (subroute.slug.endsWith(&quot;*&quot;) &amp;&amp; !urlStateSetThisLayer) {
returnUrlState = deepCopy(subroute);
returnUrlState.title = layer;
urlStateSetThisLayer = true;
if (returnUrlState.subroutes &amp;&amp; index != slugLayers.length - 1)
backupUrlState = deepCopy(returnUrlState);
return;
}
//...
</code></pre>
<p>Notably, <code>subroute.slug.endsWith(&quot;*&quot;)</code>. I added that because I liked how SvelteKit has dynamic routing, where a URL can accept any slug and change the page content accordingly. For example <code>/articles/hello-world</code> and <code>/articles/foobarbaz</code> actually load the same page that has access to the <code>hello-world</code> and <code>foobarbaz</code> slugs and can change their own content accordingly. I did this because I'm a lazy programmer and I didn't want more than a few pages to implement.</p>
<p>Well this <code>parseSlug()</code> function took a long time to make work, and even longer to fix the biggest bugs (I'm confident there's still a good few waiting for when I let my guard down).</p>
<p>I was pretty happy with my work, it functioned, it only broke here and there, and it meant I got to use Svelte <a href="/rand/ilovesvelte">i love svelte</a>.</p>
<p>So TL;DR I was too lazy to learn a new framework and so accidentally made a worse version of existing ones (the classic tale of every web dev).</p>
<p>Some pros and cons I can think of right now:</p>
<p><strong>Pros:</strong></p>
<ul>
<li>
<p>Extremely fast links since no reloads are necessary</p>
</li>
<li>
<p>Data persistence across all pages</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>
<p>All the pages have to be loaded on first load, this slows down the website.</p>
</li>
<li>
<p>This hell:</p>
</li>
</ul>
<pre><code class="language-js">switch (urlState.path) {
case &quot;index&quot;:
displayPage = index;
break;
case &quot;articles&quot;:
displayPage = articles;
break;
case &quot;articles/notFound&quot;:
displayPage = notFound;
break;
case &quot;articles/slug&quot;:
displayPage = slug;
break;
//..
</code></pre>
<blockquote>
<p>I have to do this because of how <a href="https://svelte.dev/tutorial/svelte-component">Svelte components</a> work</p>
</blockquote>
<p>Do what you want to make your website work, I'm not making an industry that hinges on 200ms faster page load time.</p>
]]></content:encoded>
<guid isPermaLink="false">routing-in-svelte</guid>
<pubDate>Thu, 06 Oct 2022 19:00:00 GMT</pubDate>
</item>
</channel>
</rss>