Hacker News new | past | comments | ask | show | jobs | submit login
Explaining Code Using ASCII Art (regehr.org)
232 points by behnamoh on June 27, 2022 | hide | past | favorite | 80 comments



Man - this is my fkn brand.

Plain text is almost a universal truth -- and it's easy to church up your documentation with a well presented ASCII chart.

Some ANSI Color Codes and ASCIInema can carry you a long way.

Here's a list of plain text information tools from my notes:

  https://mbarkhau.keybase.pub/asciigrid/
  https://gitlab.com/mbarkhau/asciigrid/
ascii-tables is exactly what is says on the label.

  https://ozh.github.io/ascii-tables/
  https://github.com/ozh/ascii-tables/

  https://www.netpen.io/main/
  https://github.com/ebirger/netpen/
svgbob and svg-term are both great for creating SVGs out of these plain text files:

  https://github.com/marionebl/svg-term-cli/
  https://ivanceras.github.io/svgbob-editor/
  https://github.com/ivanceras/svgbob/
Here are some TUI/CLI focused frameworks. These are over kill for me - but maybe useful to someone here:

  https://www.textualize.io/
  https://charm.sh/
  http://maaslalani.com/slides/
  https://github.com/peterbrittain/asciimatics/
TUI/Text-Based presentaion tools:

  https://sli.dev/
  https://github.com/slidevjs/slidev/
  https://github.com/maaslalani/slides/
  http://maaslalani.com/slides/
  https://github.com/d0c-s4vage/lookatme/
  https://github.com/chunqiuyiyu/ervy/
Honorable Mention goes to wtf-util and it's TUI configurator:

  https://wtfutil.com/
  https://github.com/ggerganov/wtf-tui
Thanks for coming to my ted talk!


Thanks for the shoutout. AsciiGrid is dockerized should you want to run it yourself, for example because the keybase website happens to not be serving it anymore: https://github.com/mbarkhau/asciigrid#docker


Plug for my side project: https://animasci.com/

Runs in the browser, editor for animated ASCII art, exports as embeddable javascript and animated GIFs.


Marp is pretty neat for markdown presentations, not too complicated and has useful (and pretty!) output.

https://marp.app/



> Plain text is almost a universal truth

Would you mind explaining what you mean by this? I take it you mean it ubiquitous, which of course it is, but as a phenomenon I'd much rather see things that look like they come from the real world, with color, depth, texture, and I'd much rather see a future where interactions with computers are moving in that direction.


This isn't a very good solution, IMHO. Or, it doesn't scale. If you find yourself with an existing solution that doesn't scale for what you need it to, cut your losses and find a better tool or solution.

Some simple visualization using ASCII is fine. Something you can create from scratch and otherwise modify in as much time as it would take to document code. But, if you need a sequence diagram, or flow chart, what not. The tradeoff for maintenance and lack of readability makes it look silly. The "why was this developer wasting time doing things with the wrong tools"-kind of silly.

If you need complex diagrams. Create them using draw.io or plantuml, and add them to the source control. Generate images which you instead reference in the documentation in code. Tools such as Doxygen and other such tools would be able to pull in the images and actually look good. This is both maintainable, and scalable.


Any visual information that needs to be understood by a human doesn't scale. ASCII UMLs might scale slightly less well than, say, powerpoint UMLs, but having them right there in the code comment in cases that do fit is splendid.


I'm not sure I agree with "it doesn't scale". It scales just as well as writing code by hand does!

PlantUML/mermaidjs do hit a sweet spot IMO, of having the chart defined as plaintext but rendering a pretty picture. The only way these could be improved IMO is if the ascii "code" for the diagram was also an actual diagram you could understand without running it through the parser.


I should clarify what I mean with scaling. I was trying to describe complexity of maintaining the illustration for the complexity of what it is illustrating.

For ASCII art, this is far from linear, in most of the examples shown.

Consider some of the more complex ones shown in the linked article. The minor added complexity of adding a field, suddenly might mean you need to remake parts, or even entire visual art for it to stay congruent. You'll have software engineers hitting spacebar a few hundred times just to align things right. With proper tools, you'd just add the field, and that's it.


I like doing things in plain text and I like ASCII art. However, this is tedious work, if you don't have the tooling to maintain these "diagrams", when things change.

The table of "The layout of a data structure in the Jikes RVM" for example. Imagine, if suddenly there was a new attribute in one of the tables, which has a longer name than any of the previously existing ones. Great fun to manually widen the whole thing. With multiple cursors easily possible, but even then it sucks and there are other scenarios, where it gets much worse.

In Org mode I could imagine managing such a table and then copying it back into the code comment. And maybe Emacs' ASCII art drawing mode (forgot its name) would help me with other shapes, but drawing something like an ERM or so is still tedious.

Maybe those ASCII art diagrams could be created, when the design is already finished.


The way I use ASCII art diagrams in my source-code is through this simple web service that I hosted:

https://dot-to-ascii.ggerganov.com

I generate the ASCII graph and then paste it in the comments together with a link to the service. This way I can go back later and update it if needed:

/*

Link: https://dot-to-ascii.ggerganov.com/?src_hash=476410d3

                     0.6
                 ┌─────────────────────────┐
                 ▼                         │
  ┌───┐  0.8   ┌───┐  0.1   ┌───┐  0.7   ┌───┐  0.2   ┌───┐
  │ d │ ─────▶ │   │ ◀───── │ e │ ─────▶ │ a │ ─────▶ │ b │
  └───┘        │ c │        └───┘        └───┘        └───┘
               │   │  0.4                               │
               │   │ ◀──────────────────────────────────┘
               └───┘
*/


For some reason the arrow ▶ is a double-width character on my PC so it breaks.

I'm using Noto Sans Mono as monospace font. Broken with Iosevka as well, works with Dejavu Sans Mono.

That said, it's pretty cool, bookmarked.

EDIT: weird now I'm looking at my comment from an iPhone and the arrow is rendered with the arrow emoji. Have I found an exploit to embed emojis in HN comments?!


▶ is not a box-drawing character like the rest, so most monospace fonts won’t support it, so it’ll be rendered in a different font with almost certainly different metrics, so in environments that follow text metrics rather than rigidly drawing on a grid, that arrow will ruin everything. The web is one such environment.


Interestingly, my browser's default monospace choice of Courier is only very slightly distorted by the arrowheads. Like at most 2 pixels off when looking at it at whatever size it is on the dot-to-ascii site. Switching to Menlo results in no distortion at all.


There is a "Boxart" button at the bottom of the page to toggle between pure ASCII chars and "extended" ASCII (not sure what is the proper name).


> EDIT: weird now I'm looking at my comment from an iPhone and the arrow is rendered with the arrow emoji. Have I found an exploit to embed emojis in HN comments?!

Apple emoji font, in addition to emojis, also includes other characters like numbers, arrows, and "trademark" (tm), "registered" (r), and "copyright" (c) symbols, so that's why.


You should try fonts that are not proportional.


This is great! Thanks for sharing, it's added to my bookmarks


Wow this is wonderful, I hope to use this a lot!


There's this neat mac app Monodraw. It costs 10 bucks but worth every penny because it's like a vector editor for ascii. I've used it for all sorts of things and heartily recommend it to anyone that does textual charts, diagrams and such.

https://monodraw.helftone.com/


I love Monodraw! Been using it for years.


Seconding this - I love it!


> I like doing things in plain text and I like ASCII art. However, this is tedious work, if you don't have the tooling to maintain these "diagrams", when things change.

Not having integrated built-in tools to properly maintain this type of representation is a missed opportunity.

IDEs went the copy/paste and word replace route, and the few diagram and table drawing tools in ASCII are often in separate applications, reducing their usefulness.


Maybe the universal solution to this is for the Unicode Consortium to dedicate a set of codepoints for encoding SVG or something similar.

Then the system text renderer can be responsible for drawing these diagrams, and they can be embedded anywhere in text.

It would also have the side benefit of letting people draw their own emojis, rather than waiting some time from months to never to have their suggestions included in the next Unicode release.


I beg you, do not give them ideas.

Leave plaintext to be as plain as possible. Emoji were already a bad compromise made to get Japanese encodings to sort-of work. Leave markup to general markup languages. Don't make unicode even more convoluted.


a descent editor would have multi-cursor, multi-line edits that could be also configured to do 'inserts' over appends.

So you'd use a mouse to "draw" a line (if it's horizontal or vertical), and it'd take only 4 "draw line" to make a box, and turn on 'insert' mode to type in the text inside the box.

Drawing diagonal lines is a bit more involved, but not too hard either. Adding a cell to an ascii table is also pretty easy using this same method.

However, it is preferable to have the diagram in svg tho. The svg file could even be separate from the comments, but just referenced.


If we're already assuming an IDE, how about one that expands images which are linked in comments? It'd have minimal friction if everyone else on the team uses the IDE, and if someone does not, they can open the link instead.

I cannot find any information about an IDE which does this.


HolyC (from TempleOS) allows non-text content to be placed directly inside source code, but no one (anymore) programs in it


> Emacs' ASCII art drawing mode (forgot its name)

M-x picture-mode

https://www.gnu.org/software/emacs/manual/html_node/emacs/Pi...

Further enhanced by M-x artist-mode (also included with Emacs):

https://www.lysator.liu.se/~tab/artist/


I've used https://asciiflow.com/#/ but it isn't perfect.


What would be really cool is if you can cut-n-paste an existing diagram (possibly also with comment markers) and edit it. Then cutting-and-pasting it back into the source code.


When you draw 2 boxes and an arrow between them, then move a box, it does not stay connected to the arrow. I think that is an instant no-go for designing diagrams. Perhaps it can be used for converting to plain text diagram, but not for working on diagrams and changing stuff around a lot.


ThankYou for mentioning this! I always wanted something like! It will save me soo much time and effort!


Personally, I tend to use simple diagrams to illustrate the basics. I try to keep them as small and minimal as possible. This way I can reduce the risk of excess work if something changes. If the case, that I want to illustrate, is too complex to fit into a small ASCII diagram, it most likely should be better modeled in a dedicated modeling tool (I use Sparx EA).

Also I think that modeling languages like Mermaid are a nice alternative for small to medium diagrams. But these wont work in code comments. But they can be fitted into a Markdown file.


Wait, wait, wait. This entire webpage has examples of ASCII art, and yet 100% of the examples are bitmaps?


They are JPEGs, even. How sacrilegious.


to be fair, mobile users are probably grateful of that


Not me, as they are all in different resolutions, having to zoom out, to zoom in, and zoom in again. Simple text would be better.


The author collected these from a Twitter thread of theirs, in which the artworks had to be shared as images. Converting all back to text would be laborious.


Each image is a link to the original source. It was a simple matter of copying and pasting the text instead of the image.


But then you wouldn't see them correctly on mobile browsers.


If you're referencing line wrapping, wrapping the <pre> in a <div> with just two styles would work:

    display: block;
    overflow-x: auto;
That would allow the <pre> to overflow to the right and let the user scroll over.


Isn't it fair considering how easy they could be broken due to the difference between environments?


Put them in `<pre>` tags and they should render as monospace and the whitespace as-is at least.


A lot of hate in this thread. If you stop analyzing the utility/practicality/extensibility of it you might admire just how beautiful it is (or try to picture the tired dev taking a coding break to do some "art").

Love this stuff.


For me to draw even a simple ascii art it takes more time, attention, effort than any graphical. I can't crop, can't mirror, can't rotate, can't zoom, can't add secondary or any color for that matter. I know the process is slow, and obviously not efficient by any measure. yet I do it and ...

I love ASCII ART. Its elegance is in its simplicity. To be able a draw anything from simple boxes[0] to Mona Lisa[1] to Porn[2] using nothing but bunch of plain ascii characters just blows my mind. To craft is to hand place each character, at its right place without disturbing anything around, which feels nothing less than crafting a glass-piece.

Links :

[0] : https://www.asciiart.eu/art-and-design/borders

[1] : https://www.asciiart.eu/art-and-design/mona-lisa

[2] : https://www.asciiart.eu/people/sexual/women


[2] That’s erotica, not porn.


Hardly: erotica is, at least by my definition, textual porn that semantically arouses. This is very clearly visual porn, though it may be textual.


> erotica is, at least by my definition, textual porn

That's not what the word means in normal use.


It isn’t hate. It is the natural tendency of software developers to identify flaws, falsehoods, limitations and drawbacks — which is a beneficial trait to have when developing software.


I personally like ascii art drawings to explain things in the code, but it likely makes the life of blind programmers harder when they try to browse the code. I guess it should be used with parsimony and completed with a textual explanation. I don't know if there are tools to easily skip blocks of ascii art.


I wish more code would work like the 2dmatch example of "very cool special case where the ASCII art is also code". Use the representation that shows the relevant information in the most direct form, rather than translating it from an abstract description as sequential code instructions.

The GPL license describes source code as "the preferred form of the work for making modifications to it". Sometimes the preferred form that conveys the most information is a 2D visual representation, and it would be sleek if we had more parsers capable of extracting case specifications directly from that format.


I get that it's because the author collected these examples from Twitter, but I find it upsetting that all this ASCII art is presented as pictures instead of... ASCII.


He beats expectations by linking to the actual source code


But… but… when you have identified where it comes from, why would you go to the trouble of putting the images in rather than copying the code? I would genuinely expect copying the code to be easier, and it’s clearly better and more consistent.


Because making the code render properly would require a JS library. (Only slightly sarcastic, as I genuinly have heard similar arguments before)


This gives a consistent and faithful image. Doing it as plaintext would cause problems with reflowing, weird scrolling boxes, and generally might have you fighting with the browser text renderer.


Consistent? Faithful? I see a whole bunch of images in different styles with different fonts, colours, fairly consistently the wrong line-heights, and even severe JPEG artefacts in at least one case.

Doing it in plain text with `white-space: pre` (the default for the <pre> element) would work better.


Consistent over devices, not Consistent between the images. The point is that jpeg rendering is a whole lot more consistent between devices than html rendering.


I wonder how this kind of schematics would sound like when using a screen reader. Hopefully the schematics can be passed if the screen reader struggles to read it, or read an "alt" alternative text instead. But I doubt it. After seeing how a person uses a screen reader, I think using a spreadsheet is sometimes more accessible than ASCII art because I guess screen readers cannot interpret ASCII characters in terms of columns and lines.

If I would have to document a table into the code, I would try to use as little ASCII characters as needed, in order to not confuse the screen reader.


This one has to be my favourite- I thought maybe whoever transcribed the source code listing for the AGC to GitHub took some artistic license- but no, it's there in the original scans!

https://archive.org/details/Comanche55J2k60/page/n1027/mode/...


Shameless appeal for code commentary review:

This reminds me of a code comment I wrote about some web crawling code that is intended to maintain a continuous web address "flow graph", matching any origin URL(s) (the 'water table' of a web page) down to the current location of that page on the web (the 'river delta').

This can be complicated because old URLs may be redirected (HTTP 301, 302) to different locations over time, often for SEO reasons or due to change of domain ownership.

Does the code comment linked below make sense? I'd really appreciate any feedback and improvements:

https://github.com/openculinary/backend/blob/5116c4f5d39dae1...

(and yes, I realize the ASCII art here pales in comparison to some of the visually appealing and clear diagrams shared in the article. I'm doing my best :))


I love asciiflow.com for creating these sort of pictures. I'm a firm believer that the closer your documentation is to your code the better maintained it will be.


I really liked the simplicity of the older asciiflow. So much so that I keep a bookmark to the wayback machine for it [1]

Not too long ago I had a project that was implemented as a complex state machine where the requirements kept changing, and keeping the documentation as an ASCII diagram in the source code had a couple of benefits: * It meant that the documentation could be updated when the code had to be changed * I didn't have to hunt for the diagrams on the project wiki when I made these changes. * The diagram was kept in version control with the rest of the code. Each commit/branch had a diagram that accurately reflected its state.

I could then use Ditaa to convert the diagram to a more appropriate format when updating the project's wiki or emailing the customer

[1] https://web.archive.org/web/20130813045206/http://www.asciif... [2] https://github.com/stathissideris/ditaa


Could this kind of documentation be an exception? After all, it can be quite hard to edit these pictures.


I think you want to lean heavily into the words and use pictures sparingly where they really add value. They're also not completely uneditable - you can just dump them back in asciiflow and fiddle with them if you want to make a change.

I also find that usually the pictures capture a fairly high level structural concept - the sort of thing that changes a bit less. Sometimes I do a message sequence chart and editing to add an extra message is usually pretty easy.



Oh man - I'm def gonna spend some time picking the bones of this list -- great finds.

I have a whole section of my notes dedicated to ASCII Art in the purely creative/crack/BBS scene.

Unicode/Cyrillic fonts used by loud girls on instagram:

  https://coolfonts.text-generator.org/
  https://www.messletters.com/en/
  https://github.com/sepandhaghighi/art
Some creative ASCII tools:

  https://github.com/maaslalani/draw
  https://blocktronics.github.io/moebius/
  http://picoe.ca/products/pablodraw/
  https://ivanceras.github.io/svgbob-editor/
  http://www.torchsoft.com/en/aas_information.html
  https://github.com/hpjansson/chafa/
Here's some ANSI and BBS scene stuff:

  https://www.asciiarena.se/
  https://16colo.rs/
  https://www.ansilove.org/
  https://www.trueschool.se/
  https://www.teletextart.com/
  https://www.pouet.net/
  https://github.com/NuSkooler/enigma-bbs
Like most of us - I grew up with mostly Async communication online.

I'm still out here dishing out emoticons like it's 1998 and every kilobyte counts.

  (•_•)
  ( •_•)>⌐■-■
  (⌐■_■)


"Unicode/Cyrillic fonts used by loud girls on instagram" had me LOLing hahahaha

we can be friends


Why not UTF-8 art? I guess we could make much nicer diagrams with then?


I imagine it gets very font-dependent what the results actually look like, sticking to ASCII gives great reproducibility guarantees.


that's anachronistic since ASCII predates UTF8

creators of 8bit games didn't have the technology to create 64bit games, yet today we create 8bit games for 64bit machines


For generating protocol headers: https://www.luismg.com/protocol/


I put some basic ASCII art explaining concepts in my article here[1], some might like to check it out:

[1]: https://timvisee.com/blog/solving-aoc-2020-in-under-a-second...


These days I tend to think that code should contain guides and markers so developers can find their way, but actual documentation is best placed in separate files outside of the code.


I wonder if Github Co-pilot or DALL-E type work could be expanded to generate ASCII diagrams (or art) based on descriptions provided.


Good stuff. I wonder if there's a way to "detect" ASCII art automatically by crawling open source repositories.


Reminds me of Radare2's ascii function/code graph.


thanks, this is what I was looking for for my upcoming interviews.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: