Unformatted Code Detector

:discourse2: Summary Unformatted Code Detector detects unformatted code and gives a warning before posting.
:eyeglasses: Preview Preview on Discourse Theme Creator
:hammer_and_wrench: Repository Link https://github.com/discourse/unformatted-code-detector
:open_book: New to Discourse Themes? Beginner’s guide to using Discourse Themes

Install this theme component

Features

Users posting unformatted code will see a warning message instructing them how to format it correctly.

Sensitivity and whether it detects HTML are configurable via theme settings.

Settings

Name Description
emoji icon The emoji icon to be displayed next to the title in the unformatted warning modal.
disable at trust level Disable warning for users with a trust level of N or higher. -1 = enabled for all users.
sensitivity Sensitivity of the detection algorithm. 0 = plugin disabled; 1 = warn for anything that looks even slightly like code.
min post length to check Minimum post length to check (number of characters)
max post length to check Maximum post length to check (number of characters). -1 = no maximum.
include html Check for HTML tags as well as other types of code. Recommended to disable if users frequently need to render custom HTML in their posts.
Translation Default
warning_modal.title Are you posting code?
warning_modal.content It looks like your post may contain code or logs. To keep your post readable, please remember to format your code using the Preformatted text toolbar button </>, or the backtick ` key on your keyboard, like so: [examples]
warning_modal.do_not_show_again do not show this message again
warning_modal.fix_post Edit Post
warning_modal.ignore_and_post_anyway Post Anyway

Debugging

If you receive a warning for a post which doesn’t include any text, you can print debug information by opening the browser JS console, and typing debugUnformattedCodeDetector() Enter. This will print some information about which lines were considered ‘code’, and what the sensitivity settings are.

:information_source: “Do not show this message again” only works per device, not per user. This is a known issue and will be fixed once Discourse gains the functionality to attach user info from themes.


:discourse2: Hosted by us? Theme components are available to use on our Standard, Business, and Enterprise plans.

Last edited by @JammyDodger 2024-06-16T11:48:08Z

Check documentPerform check on document:
60개의 좋아요

We at the Home Assistant forums think that this is the best thing invented since sliced bread. Or maybe Home Assistant. Thank you so so much @lionel-rowe!!!

Two minor request:

  • I don’t want to allow users to skip formatting or disable the dialog in the future. I want them to feel pain until they change their ways. I’m sadistic like that. Can you make the “Don’t show this message again” and “Post anyway” buttons optional? For now I’ve hid them with some CSS but would be better to just not include the HTML at all.

  • Unsure if you are doing language detection or not, but if you are, can you add the estimated language name after the first code fence so that users will properly syntax highlight too?

Thanks so much!!

6개의 좋아요

I wouldn’t recommend hiding them, especially if you leave the setting to include HTML detection on. Power users may still want to have their (sanitized) HTML parsed as such, not formatted as code. Two examples where this can be useful are kbd and abbr tags.

If you exclude HTML tags from detection (which may be viable depending on the scope of your forum), hiding the “don’t show this again” would probably be OK. I still wouldn’t recommend hiding the “post anyway”, though, because there are bound to still be some edge cases of false positives (I hit one the other day where I’d omitted a space before an opening parenthesis — poor typesetting, but not unformatted code). Then you’ll have a situation where users can’t post their question at all, and, unless they report the issue to you directly, you won’t even know about it.

Language detection is beyond the scope of this component, I’m afraid. Where possible, it looks for syntactical features shared by many languages, such as lines ending in semicolons, certain configurations of curly braces, and so on.

I am thinking about ways to enhance the UX, though. One big improvement would be to make it much more interactive. For example, instead of a simple modal, the user would be presented with a wizard that first asks them which language their post concerns (select from a dropdown), then a screen which asks them to select which ranges of their post are code (defaulting to lines that contain strings flagged by the plugin), then generating the appropriate markdown. This would still include a “skip and post anyway” option, though, for the reasons I mentioned.

I don’t have a timeline for this change, but it’d be good to know if it’s something people would be interested in.

7개의 좋아요

Already hit the edge cases issue within 30 minutes or so of hiding the elements, so they have been re-added.

I would be super interested in the modal being more interactive!

1개의 좋아요

간단한 안내드립니다. 이 컴포넌트를 곧 공식화할 예정이며, @lionel-rowe 와 @david 와 긴밀히 협력하여 이를 진행할 것입니다. 아이디어나 피드백이 있으시다면, 지금이 공유할 적기입니다!

18개의 좋아요

2개의 게시물이 새로운 주제로 분리되었습니다: Emojis trigger code detector and ‘fix code’ doesn’t work

훌륭한 소식입니다!

적절할지 확실하지는 않지만, 포맷을 깨뜨리는 가장 흔한 마크다운 오류에 대해서도 알림을 줄 수 있다면 좋겠습니다.

4개의 좋아요

추정되는 포맷되지 않은 코드가 어디에 있는지 힌트가 제공되면 좋겠습니다.

저는 다른 답변을 작성하다가 경고를 받았는데, 코드를 붙여넣은 적은 없습니다. 잠시 후 topic_id라는 단어를 사용했기 때문이라는 걸 깨달았습니다. 하지만 이 단어가 코드라고 감지된다는 사실은 직관적이지 않습니다(대부분의 사람은 그렇게 생각하지 않을 것입니다). 제 생각에는 단어에 밑줄이 있다고 해서 반드시 코드인 것은 아닙니다.

2개의 좋아요

지금까지 피드백을 남겨주신 모든 분들께 감사드립니다! 감지 기능의 과도한 민감도를 줄이기 위해 몇 가지 설정을 추가하고 조정할 예정입니다.

@tpetrov 한 가지 더 여쭤볼 것이 있습니다 — 팝업의 문구가 게시글에 코드가 포함되어 있지 않다고 생각하면 무시하고 그대로 게시할 수 있다는 점을 명확하게 전달하고 있나요? 아니면 감지된 문제를 찾아서 "수정"해야 하는 것처럼 느껴지나요?

5개의 좋아요

제가 우려하는 점은 많은 사람들이 이 내용을 끝까지 읽지 않을 것이라는 점입니다…
요즘 사람들은 팝업에 문장이 두 개 이상 나오면 텍스트를 무시하고 확인 버튼을 찾으려는 경향이 있습니다 (쿠키 동의, 약관 동의 등).

그래도 "글에 포맷되지 않은 코드가 포함되어 있을 수 있습니다"라는 문장을 "글에 코드를 사용하시나요?"로 바꾸는 건 어떨까요? 때로는 질문이 더 많은 관심을 끌 수 있습니다.

저는 UX 전문가가 아니지만, 이 버튼은 다소 극단적으로 느껴집니다:
image - 제가라면 클릭하고 싶지 않은 버튼입니다. 물론 이것이 의도된 효과일 것입니다. 즉, 사람들이 글의 포맷을 더 잘 다듬기 위해 노력하는 대신 단순히 건너뛰지 못하게 하려는 것입니다.

1개의 좋아요

오오, 이 아이디어 좋네요… 그런데 방금 오탐이 하나 발생했어요:

깨진 링크 때문일까요? 템플릿 엔진에서 가져온 것으로, 다음과 같은 형태를 하고 있습니다: [keep things civilized](%{guidelines_url}). 아니면 HTML img 태그 때문일까요?

2개의 좋아요

나쁜 아이디어가 아니네요, @david. 모달 제목을 "코드 스니펫을 게시하시나요?"로 변경해 보는 건 어떨까요?

아마도 옳은 말씀인 것 같습니다. 다음 버전에서는 이를 표준 회색 버튼으로 변경할 예정입니다.

결국 두 가지 모두 때문이었습니다! 기본 설정을 적용한 다음 버전에서는 이 게시글에 더 이상 트리거가 발생하지 않을 것입니다.

6개의 좋아요

새로운 카피를 배포하고 있으며, 해당 컴포넌트를 위한 긍정적 및 부정적 테스트 샘플 게시글로 구성된 코퍼스를 구축하고 있습니다. 잘 진행되고 있으니 조금만 기다려 주세요!

8개의 좋아요

작은 지적 하나: warning_modal.content의 기본값은 “code” 도구 모음 버튼을 요청하고 있지만, 마우스를 해당 버튼 위에 올리면 에디터에서 “Preformatted text” 버튼이라고 표시됩니다.

grafik

grafik

새로운 사용자가 이 버튼을 찾기 쉽게 하기 위해(그들은 code 버튼을 찾지 못할 것입니다), warning_modal.content를 "code button"에서 "Preformatted text button"으로 변경해야 합니다.

3개의 좋아요

더 많은 예제와 설명이 포함된 주제에 링크를 추가하는 방법은 무엇인가요?

warning_modal.content 끝에 단순히 추가해 보았지만, 그 결과 이렇게 되었습니다(제가 추가한 부분은 노란색으로 표시):

현재 콘텐츠 아래에 텍스트와 링크를 추가하는 방법은 무엇인가요?

수정:

warning_modal.content에서 문자 하나만 변경해도 포맷이 깨진다는 것을 방금 알게 되었습니다.

더 나쁜 점은, warning_modal.content 입력 필드에 클릭하여 포인터를 놓고 방향 키로 커서를 이동하는 것만으로도 입력 필드가 강조 표시된다는 것입니다. 아무런 변경 없이(단, 커서를 한 문자만 이동했을 뿐) 녹색 체크마크를 클릭하여 “편집된” warning_modal.content를 저장하면, 위에서 보여준 것처럼 포맷이 깨집니다.

수정 #2

해결 - https://meta.stackexchange.com/questions/82718/how-do-i-escape-a-backtick-within-in-line-code-in-markdown 의 도움으로 해결되었습니다.

@codinghorror @lionel-rowe 이 문제를 살펴보고, 공백과 백틱(특히 백틱이 많이 사용되는 “multiplelines” 섹션 내의 누락된 공백이 위의 문제를 일으키는 원인이었습니다)에 대해 기본 warning_modal.content를 조정해 주시면 좋겠습니다.

2개의 좋아요

수동으로(즉, 버튼을 사용하지 않고) 코드 펜스를 입력할 때 사용자가 어떤 키를 선택해야 하는지 더 명확하게 안내할 방법이 있을까요?

오늘 이런 상황을 목격했습니다:

사용자는 분명히 설명을 따르려 했지만, 코드 펜스에 사용할 키를 잘못 선택했습니다( ` 대신 ' ). 과거에도 ``` 대신 ... 를 사용한 경우를 본 적이 있습니다. 두 경우 모두 사용자가 어떤 키를 선택해야 하는지에 대해 더 명확한 안내가 필요함을 보여줍니다.

대안: 사용자에게 이러한 키로 혼란을 주지 말고, 단순히 “서식 지정된 텍스트(Preformatted text)” 버튼을 사용하면 된다고 안내하는 것입니다.


@lionel-rowe 감지 동작을 어떻게 사용자 지정할 수 있나요?

현재 시뱅(shebang) 은 코드로 감지되지 않고 있으며, 이를 변경하고 싶습니다.

기대하는 동작: #! 은 스크립트의 시작을 나타내므로 코드로 감지되어야 합니다.

감지되지 않는 예시:


#!/bin/sh

echo “test”

. /lib/upgrade/common.sh

firmware=“/tmp/firmware.img”
tmpdir=“/tmp/_upgrade”
output=“/dev/ttyS0”
before=“before-upgrade.sh”
after=“after-upgrade.sh”


이와 관련하여, root@ 가 코드로 감지되면 우리에게 유용할 것입니다.

root@OpenWrt:~# ip link add link eth0 name eth0.9 type vlan id 9
root@OpenWrt:~# brctl addbr br-foo
root@OpenWrt:~# brctl addif br-foo eth0.9
root@OpenWrt:~# ip link set eth0.9 up
root@OpenWrt:~# ip link set br-foo up

4개의 좋아요

@david 감지 방식을 사용자 지정할 수 있는 방법이 있나요?

현재 사이트별 커스터마이징을 지원하는 방법은 없습니다. 대신 ‘코드 에너지’ 시스템에 셉뱅(shebang)과 셸 프롬프트 감지 기능을 추가하는 방안을 검토해 볼 수는 있습니다.

3개의 좋아요

이 문제를 제기해 주셔서 감사합니다. 다중 줄 테마 번역과 관련된 핵심 버그인 것 같습니다. 수정을 위한 PR을 생성했습니다:

3개의 좋아요

대부분의 Discourse 사이트가 Discourse를 문제 해결 도구로 사용하고 있습니다. 이 플러그인은 코드가 아닌 다음 작업에도 적합한가요?

Linux:

  • 로그
  • Linux 명령줄 인터페이스(CLI)
  • 터미널 출력

예시:

Sensors:
  System Temperatures: cpu: 78.0 C mobo: 36.0 C gpu: nouveau temp: 56.0 C 
  Fan Speeds (RPM): cpu: 0 fan-1: 3139 fan-3: 0 fan-5: 0 
  Power: 12v: N/A 5v: 2.90 3.3v: N/A vbat: 3.34 

감사합니다.

4개의 좋아요