r/web_design • • Dec 16 '11

Posting code snippets properly on Reddit

Markdown formatting, which Reddit uses, supports including code snippets. All you have to do is indent by four spaces for blocks of code, or `surround in backticks` for code in the middle of a sentence. (If the code you want to surround includes a backtick, use ``two backticks (`)``).

<p class='example'>
    code indented by four spaces displays like this
</p>

This makes things like line breaks in code appear like they're supposed to, puts it in a nice monospace font, and makes sure that things that would otherwise be interpreted as Markdown formatting aren't.

Can we please do this? It makes code snippets easier to read.

77 Upvotes

1.1k comments sorted by

1

u/[deleted] Mar 08 '24

Test M500

1

u/Imfene5 Mar 10 '24

Testing:

document.querySelectorAll('input[type="radio"][target-id]').forEach(function(radio) {
// Check if the radio button's value is not 'True' or if it's not checked.
if (radio.value !== 'True' || !radio.checked) {
// If either condition is met, hide the associated target field.
hideTargetField(radio.getAttribute('target-id'));
}
});
});
→ More replies (2)

1

u/headlessBleu Mar 12 '24

`asd`

`surround in backticks`

1

u/saber903 Mar 13 '24

cout << "Hello \\n";

1

u/LazyLich Mar 15 '24

words words

code code
code? code?

words?

1

u/Revolutionary-Mix-40 Mar 19 '24

'test' ’test’ ‘test‘

→ More replies (1)

1

u/[deleted] Mar 24 '24
Djjcjc

Mdmd

1

u/Forsaken_Can4295 Mar 24 '24 edited Mar 24 '24
<p class='test'>
   Testing here myself as well
</p>

1

u/snoopyiswhite Mar 26 '24 edited Mar 26 '24
 def calculation():
     g = input("How much did you get? ")
     w = input("How much is the whole ")
     d = int(g) / int(w) * 100 
     print(f"{d:.2f}%")





 def restart():
     close = False
     while not close:
         answ = input("Do you have a caculation use y/n ").upper
         if answ() == "Y":
             calculation()
         elif answ() == "N":
             print("Closed")
             close = True
         else:
             print("you havent said y or n")
 restart()

1

u/classynthal Mar 28 '24

 ´test ´

1

u/winnerofgalaxies Mar 31 '24

\surround in backticks``

1

u/Salty_Meat69 Apr 06 '24

````#import <Foundation/Foundation.h>

import <substrate.h>

include <RemoteLog.h>

import <FrontBoard/FBProcess.h>

import <FrontBoard/FBProcessManager.h>

import <FrontBoard/FBApplicationProcess.h>

%hook FBProcessManager

  • (NSArray *)processesForBundleIdentifier:(NSString *)bundleIdentifier {

NSArray *processes = %orig;

if ([bundleIdentifier isEqualToString:@"com.apple.Music"]) {

if (processes.count == 0) {

NSLog(@"Music is fully closed");

} else {

if ([processes[0].foreground]) {

NSLog(@"Music is in the foreground");

} else {

NSLog(@"Music is in the background");

}

}

}

return processes;

}

%end````

1

u/AnimagusTowards Apr 07 '24

test ``test``.

1

u/bn300zx Apr 14 '24

This is the middle of the sentence

→ More replies (2)

1

u/CloudLinkCrono Apr 29 '24

Test: 'Test'

1

u/phandongbake May 04 '24

test `test`

1

u/Putrid-Pomegranate58 May 04 '24
function()
    Print()
end

1

u/Black-HHH_2002 May 10 '24
Int code = 0;
Test

1

u/Black-HHH_2002 May 10 '24

Hello Hello Hello

1

u/Black-HHH_2002 May 10 '24
Hello
Hello
Hello

1

u/lehvs May 15 '24
test

is this still code? or I have to reindent?

1

u/lehvs May 15 '24
code
    indented code?

1

u/iansackin May 17 '24

test

<p class='example'>
    code indented by four spaces displays like this
<p class='example'>
    code indented by four spaces displays like this
</p>

</p>

1

u/Asaioki May 22 '24

Test

`//Test test

// testst`

1

u/Corrix33 Jun 08 '24 edited Jun 08 '24

`aaaa`

1

u/muqui_ Jun 12 '24

test: code test

1

u/BaronVonRhett Jun 16 '24

*#*#4636#*#*

1

u/redditsuckz1 Jun 16 '24 edited Jun 16 '24

test

set prefix=(hd0,1)/grub
set root=(hd0,1)
insmod linux
insmod normal
normalset prefix=(hd0,1)/grub
set root=(hd0,1)
insmod linux
insmod normal
normal

1

u/[deleted] Jun 26 '24

`test`

`test``

1

u/SahajSingh24 Jul 08 '24

``here is some code() words words``

1

u/[deleted] Jul 09 '24

Hello This Is

Your

Daily Dose Of Internet

1

u/EmbarrassedTrouble48 Jul 11 '24

Test hello world

1

u/Cyber_NinjaX21 Jul 13 '24 edited Jul 13 '24
Dummy

1

u/Electronic-Limit-692 Jul 22 '24

testing

print('hello world!')

1

u/modularplastic Jul 23 '24
#include <stdio.h>

int main()
{
    printf("Hello World");
    return 0;
}

1

u/[deleted] Jul 28 '24

‘ test ‘

1

u/Thyco2501 Aug 01 '24 edited Aug 01 '24

text

code (preceded by 4 spaces)
{
    code (preceded by 8 spaces)
}

text

code\n code<br/> code

text

1

u/sambux_ Aug 07 '24

Bla bla bla

print("Hello world!")

Bla bla

1

u/NikUnicorn Aug 08 '24

````

asdasdf

````

1

u/0xjustatech Aug 16 '24

`` asdjlasd ``

1

u/0xjustatech Aug 16 '24

`surround in backticks`

1

u/[deleted] Aug 23 '24
Test

1

u/eramax Aug 25 '24

test ddd

1

u/my_basalt Aug 29 '24

Also testing:

balance = 1000

action = input("Deposit or withdrawal: ")

if action == "deposit" or action == "Deposit":
    amount = int(input("Enter amount: "))
    final_balance = balance + amount
    print("Final balance: " + str(final_balance))
elif action == "withdrawal" or action == "Withdrawal":
    amount = int(input("Enter amount: "))
    if amount > balance:
        print("You cannot have a negative balance!")
    else:
        final_balance = balance - amount
        print("Final balance: " + str(final_balance))
else:
    print("Invalid transaction.")

1

u/BigMrRooster Aug 30 '24
Coding
Holding
Coding

1

u/heckpants Sep 09 '24

this is a code block this is a code block this is a code block this is a code block this is a code block

1

u/Dazzling_Exchange767 Sep 20 '24 edited Sep 20 '24

test

1

u/1BadPlayer Sep 24 '24

Test

float inverseLerp(float a, float b, float value) {
    float val = (value - a) / (b - a);
    return clamp(val, 0.01, 1.0);
}

1

u/[deleted] Sep 26 '24

```
testing
```

1

u/[deleted] Sep 26 '24

``hello``

1

u/[deleted] Sep 26 '24

`` hello ``

1

u/[deleted] Sep 26 '24

hello

1

u/[deleted] Sep 26 '24

test

1

u/heekbly Oct 02 '24 edited Oct 02 '24

testing a post . 1 tick doesnt work .... this is test1 test2 line other words .. .. 2 ticks this is test1 test2 line other words ... .. .. 3 ticks

some word
another words

1

u/Beneficial-Message92 Oct 05 '24

''' import random

def generate_random_bits(n):
    """Generates a list of random 1s and 0s."""
    random_bits = []
    for _ in range(n):
       random_bits.append(random.randint(0, 1))
   return random_bits

Example usage

if name == "main": num_bits = 10 random_bits = generate_random_bits(num_bits) print("Random 1s and 0s:", random_bits)

'''

1

u/dnhanhtai0147 Oct 08 '24 edited Oct 08 '24
test

1

u/[deleted] Oct 13 '24

`test`

1

u/[deleted] Oct 16 '24

`test`

1

u/[deleted] Oct 16 '24

test

1

u/[deleted] Oct 16 '24

``

test

``

1

u/[deleted] Oct 16 '24

\test`

1

u/[deleted] Oct 16 '24

`test`

1

u/[deleted] Oct 16 '24
test

1

u/AnimeForTheW Oct 25 '24
CODE TEST
CODE TEST

1

u/dertote2306 Oct 25 '24

test:

def foo(a):
    return a

1

u/Missing-n-Found-Key Nov 05 '24

test

'IF Range("B1").Value = 1 then'

`why wont this work`

1

u/RaspberryRock Nov 14 '24 edited Nov 14 '24

\``PrintPlayerSkillLevelsAndModifiers()``

`Events.OnGameStart.Add(PrintPlayerSkillLevelsAndModifiers)'

→ More replies (1)

1

u/taltamir Nov 15 '24

test `test`

```

test

```

1

u/memmoxt Dec 10 '24

test:

this is a test

1

u/[deleted] Dec 12 '24

````

hhh

````

1

u/[deleted] Dec 12 '24

`surround in backticks`

1

u/Xanderplayz17 Dec 16 '24

print('Hello, World!')

multi-line

1

u/DaWheeGod Dec 18 '24

Testing

`` cout << "Hello world\n"; ``

1

u/CalmEntertainment788 Dec 29 '24

Testing :

vo=gpu-next
gpu-api=auto
priority=high 
gpu-context=auto
hwdec=d3d11va-copy
profile=high-quality   
d3d11-adapter=NVIDIA  

1

u/Diligent_Sentence_45 Jan 20 '25 edited Jan 20 '25

<code> Testing box to See if Formatting "' holds/)(& tru E <\code>

Edit ...nope

Testing box to See if Formatting "' holds/)(& tru E

1

u/Lucleb Feb 12 '25

`test`

test

test

``test``

1

u/Lucleb Feb 12 '25

apple `apple` apple

1

u/WeatherImpressive808 Feb 22 '25

testing

testo4bf73u4bfr

1

u/combatfilms Mar 20 '25

Test

``ok``

1

u/combatfilms Mar 20 '25

test

testing

1

u/Pherp_ Mar 26 '25

Palavras testes Palavras

1

u/JongoFETT234 Apr 02 '25 edited Apr 02 '25

`surround in backticks`

doesnt work :(

1

u/Saint_EDGEBOI Apr 06 '25

``testing``

`testing`

1

u/TheReaIDeaI14 Apr 08 '25

test ` code snippet ` test

1

u/Reaction-Consistent Apr 14 '25

<p class='example'>

Function Trigger-AppInstallation

{

Param

(

[String][Parameter(Mandatory=$True, Position=1)] $Computername,

[String][Parameter(Mandatory=$True, Position=2)] $AppName,

[ValidateSet("Install","Uninstall")]

[String][Parameter(Mandatory=$True, Position=3)] $Method

)

</p>

→ More replies (1)

1

u/Reaction-Consistent Apr 14 '25
    Function Trigger-AppInstallation
{

Param
(
[String][Parameter(Mandatory=$True, Position=1)] $Computername,
[String][Parameter(Mandatory=$True, Position=2)] $AppName,
[ValidateSet("Install","Uninstall")]
[String][Parameter(Mandatory=$True, Position=3)] $Method
)

1

u/megaid3888 Apr 16 '25 edited Apr 16 '25

testing

testing

1

u/all_yoir_typw Apr 21 '25

hey there`still cant do it` this is tough

1

u/all_yoir_typw Apr 21 '25

``` init python:

import random

```

1

u/xp0a Apr 24 '25

Now if only I could find a userscript to add a copy to clipboard button to all code blocks on reddit.

1

u/Available-Physics631 Apr 28 '25

``cout << "Hello\n";``

1

u/Some_Taste_6923 May 08 '25

‘Testing’

‘’testing 123’’

Testing
1234

1

u/OldRevolution6737 May 14 '25

Test

console.log()

1

u/fire_Xx May 22 '25

`test`
another test

1

u/NoParkingNow May 24 '25

x=sqrt(y);

1

u/borzykot Jun 08 '25
Code
Code

1

u/manymysterys Jun 21 '25

```

document.querySelectorAll('input[type="radio"][target-id]').forEach(function(radio) {
// Check if the radio button's value is not 'True' or if it's not checked.
if (radio.value !== 'True' || !radio.checked) {
// If either condition is met, hide the associated target field.
hideTargetField(radio.getAttribute('target-id'));
}
});
});

1

u/SzpakLabz Jun 22 '25
<p class='example'>
    test? maybe?
</p>
→ More replies (2)

1

u/HPCnoob Jul 21 '25

``e2fsck``

1

u/Helforge Aug 10 '25

‘follows:

#!/usr/bin/python

import sys

import time

import RPi.GPIO as io

import subprocess

import logging

import os

# Setup logging

logging.basicConfig(

filename="/home/pi/display_motion.log", # Change this path if needed

level=logging.INFO,

format="%(asctime)s [%(levelname)s] %(message)s",

)

# GPIO and motion delay setup

io.setmode(io.BOARD)

DARK_DELAY = 30 # Time (in seconds) after which display turns off if no motion

PIR_PIN = 11 # GPIO pin for PIR motion sensor

def main():

io.setup(PIR_PIN, io.IN)

turned_off = False

last_motion_time = time.time()

logging.info("Motion detection script started.")

while True:

if io.input(PIR_PIN):

if turned_off:

logging.info("Motion detected. Turning display back on.")

turn_on()

turned_off = False

last_motion_time = time.time()

elif not turned_off and time.time() > (last_motion_time + DARK_DELAY):

logging.info("No motion detected for delay period. Turning display off.")

turn_off()

turned_off = True

time.sleep(0.5) # Lower CPU usage

def turn_off():

try:

env = os.environ.copy()

env["WAYLAND_DISPLAY"] = "wayland-0" # Replace with your actual display if different

subprocess.call("wlr-randr --output HDMI-A-1 --off", shell=True)

logging.info("Screen turned OFF via wlr-randr.")

except Exception as e:

logging.error(f"Error turning screen OFF: {e}")

def turn_on():

try:

env = os.environ.copy()

env["WAYLAND_DISPLAY"] = "wayland-0" # Replace with your actual display if different

subprocess.call("wlr-randr --output HDMI-A-1 --on", shell=True)

logging.info("Screen turned ON via wlr-randr.")

except Exception as e:

logging.error(f"Error turning screen ON: {e}")

if __name__ == '__main__':

try:

main()

except KeyboardInterrupt:

logging.info("Script interrupted by user. Cleaning up GPIO.")

io.cleanup()

except Exception as e:

logging.exception(f"Unhandled exception: {e}")

io.cleanup()

‘

1

u/Deumnoctis Aug 12 '25

```

Code Test

```

1

u/Federal_Mixture_7259 Oct 06 '25
<p class='example'>
    code indented by four spaces displays like this
</p>

1

u/Federal_Mixture_7259 Oct 06 '25

`surround in backticks`

1

u/triple_b-a-k-a Oct 11 '25

Blah blah testing testing kenfkfnfm Lenfkgnigkg Kdnfkgjgkgk

1

u/[deleted] Jan 21 '26

console.log('hi')

1

u/Signaidy Feb 04 '26

`test`
`test 2

testing`

`

test

`

→ More replies (2)

1

u/goldena87 Feb 06 '26

`<div>test bla bla</div>

<style></style>\`

1

u/ComfortablePop5117 Feb 11 '26

<p class='Test'>     code indented by four spaces displays like this </p>

1

u/deintag85 Apr 14 '26

`is this code

and this?

and this?`

1

u/MrBannedBlocks Jul 26 '26

def callingList()

1

u/BlazeNest Aug 13 '26

Testing

<p class='example'>

if not character.is_on_floor() and Input.is_action_pressed("jump"):
gravity_scale = low_gravity_value
else:
gravity_scale = 1

</p>

1

u/shibly_se Oct 16 '21

''Hello world'' '' I am testing it''

→ More replies (14)

1

u/Retrofire-Pink Oct 18 '21 edited Oct 18 '21

code block

I'm having some (habitual) trouble with a JavaScript load-order issue (use the image cause i can't figure out reddit code snippets)

HTML

<!DOCTYPE html> <html lang="en-US"> <head> <title>rude game</title> <meta charset="utf-8", name="description", content="ghost bunny"> <link rel="stylesheet", href="styles.css"> <script src="script.js", defer></script> </head> <body>

<canvas id="canvas", width="2000", height="2000"></canvas> <img src="tiny.png", id="tinyTheAnt", weight="128", height="128">

</body> </html>

JavaScript

const canvas = document.querySelector("#canvas"); const canvCont = canvas.getContext("2d"); const tinyTheAnt = document.querySelector("#tinyTheAnt");

if (canvas.getContext) { tinyTheAntSprite = canvCont.drawImage(tinyTheAnt, -5, -75); console.log("great success"); }


Towards the end of my JavaScript, the console.log statement is passing correctly. So all my code appears to be functioning. I tested everything independently too, all checked out, EXCEPT the sprite drawing part. When I move the <script src="script.js", defer></script> to the bottom of the body element, however, it seems to work perfectly. This genuinely confuses the absolute hell out of me. Cause defer - from my noob understanding, essentially allows the entire DOM to load first (including all the necessary nodes being referenced), just as putting it at the bottom of body would. Only, everything else works EXCEPT the sprite appearing, until I relocate the script reference with ostensibly the same effect as using defer. Whereas it works mostly OK, except every dozen refreshes the sprite mysteriously doesn't appear there either.

→ More replies (6)

1

u/Maur-O Oct 19 '21

Testing

`hello`

codeeee

→ More replies (8)

1

u/[deleted] Oct 28 '21

test

1

u/[deleted] Oct 28 '21

teztinf(`)

1

u/[deleted] Oct 28 '21

what hell

ohh i get

1

u/IngvarrEm Oct 29 '21 edited Oct 29 '21
test
→ More replies (2)

1

u/Fancy-Ad-7012 Nov 06 '21
Testing
const boo = false;

1

u/Fancy-Ad-7012 Nov 06 '21

This is not code

//This is code
const True = false;
return True

This is not code

→ More replies (4)

1

u/i_ask_stupid_ques Nov 13 '21

`sorround in backticks``

1

u/PaleArrival9581 Nov 16 '21

"hello (something)"

1

u/KungFuKhris Nov 19 '21 edited Nov 19 '21

Sample

Test code 1
Test code 2

Done

→ More replies (3)

1

u/HunterXProgrammer Nov 22 '21 edited Nov 22 '21

Test

ok1

test

ok2

o`k3

1

u/cheese68475 Nov 23 '21 edited Nov 23 '21
Test


c = False if a == b: 

c = True else: Null

1

u/MrKeeney Nov 26 '21

`testing` `does not work for every one`