본문 바로가기

[IT/Programming]/HTML related

인터넷에서 예쁘게 코드 입력하기 (google code prettify)

반응형
# 인터넷에서 예쁘게 코드 입력하기 (Syntax Highlighter - google code prettify) 뭐 여러가지 js가 있는거 같긴한데 개인적으론 이거 쓰면서 만족하고 있음. Google 직원이 만들었으니 잘 만들었겠지. 뭔가 에러처리 (잘 안생길거 같은 에러들도 이것저것 처리를 해놓은듯) 를 잘해놔서 코드가 복잡하긴한데, 잘 돌아감. 상당히 빠른거 같고. HTML에서 약속된 문법들은 escape해줘야 제대로 표현됨. 예를 들면 { < : &lt; }, { > : &gt; }, { & : &amp; } 같은 것들. 'less than', 'greater than', 'ampersand'의 약자일듯. JavaScript - String - replace(RegExp, txt) method 쓰면 편함. 하지만 여전히 escaping은 미리 신경써줘야 함. script 안에 들어가 있지 않는 한. HTML document가 이상하게 rendering 될수도 있음. 아래는 예제. HTML 예제 코드에 어떻게 사용하는지도 간단하게 나와있음. 자세한 설명은 official page 가서... Markdown 언어로 쉽게 코드들을 프린트하고 싶다면 도 참고해 보시길... 제가 만든 Markdown 언어 SEE (Super Easy Edit of docuK). 지금 이 문서도 SEE 로 작성했음. ## PH
  • 2023-02-21 : To SEE. And bug fix.
  • 2014-??-?? : First Posting.
## TOC ## Examples of Code pretty-printed ### HTML code (How to pretty-print) ```[.linenums.lang-html] <script defer src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script> <!-- 위와 같은 script를 넣어주고 pre class="prettyprint" tag안에 code를 작성해주면 나머지는 대부분 자동적으로 예쁘게 처리해줌. defer 는 페이지가 다 load/rendering 되 다음에 동작하도록 하기위해 넣었음. --> <div class="subsec code"><h3>HTML code</h3> <pre class="prettyprint linenums lang-html"> // lang(code language)은 굳이 class에 설정해놓지 않아도 자동으로 알아서 어떤 code인지 알아내서 highlight 시킨다고 하긴 함. HTML code( <html></html> )를 여기 넣으면 highlight 됨. <!-- HTML 표현할때는 주의해야 하는게... '<'랑 '>'가 html tag에 쓰이니까. '<'=&lt; , '>'=&gt;으로 표현해야 함. (&는 &amp;로) 몇개는 자동으로 처리해 주는듯 하기도 하기도 함. ('>'랑 '&'는 굳이 안바꿔도 되는듯.) 몇개 예제들을 보니 javascript 통해서 처리하는듯도. replace(/regExp/g, str) function 이용. (g는 global하게 찾으라는 의미.) 뭐 find all and replace 지원하는 editor가 많으니 '<'=&lt; 요것만 바꿔서 처리하면 될듯. --></pre> </div> <script> PR.prettyPrint(); // 마지막에 이런 script를 추가해야 함? 안해줘도 되던데... // 되도록 run_prettify.js 추가를 마지막 부분에 하는게 좋은듯. </script> ```/ ```[.linenums.lang-html] <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <!-- 난 prettify.js 가 업데이트 될 경우를 대비해서 다음과 같은 파일을 이용, 코드로 prettify.js 를 로딩 했음. --> <!-- From recoeve.net CDN --> <script src="https://recoeve.net/CDN/docuK-postProcess-2.3.js" charset="utf-8"></script> ```/ 파일 docuK-postProcess-2.3.js 에는 다음과 같은 코드가 들어있음. 나중에 prettify.js 의 CDN (URL/URI) 가 바뀌면 각 글에서 prettify.js URI 를 다 바꿀 필요 없이 docuK-postProcess-2.3.js 만 수정하면 됨. (수정된 걸 upload 해서 같은 URI 에서 업데이트 된 docuK-postProcess-2.3.js 를 가져오게 만들면 됨.) ```[.linenums.lang-js] window.$headOrBody=$("head")||$("body")||$("#docuK-style"); // google code prettify js script (from cdn.jsdelivr.net CDN) is added. if (docuK.find('.prettyprint').exists()) { let $gcp=$(`<script id="prettyfy-js" src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></`+`script>`); // Avoid closing script $headOrBody.append($gcp); m.logPrint(`<br><br>Google code prettyfy.js is loaded since ".prettyprint" is there in your document.`); } ```/ ```[.linenums.lang-css] /* 여러가지 스타일도 제공하긴 하는데, css를 어느정도 아신다면 활용해 보시는 것도. 아래는 제가 이 글에서 사용한 css. */ /* Pretty printing styles. Used with prettify.js*/ /* Vim sunburst theme by David Leibovic 를 약간 수정함. */ pre .str, code .str {color:#65B042}/* string - green */ pre .kwd, code .kwd {color:#E28964}/* keyword - dark pink */ pre .com, code .com {color:#AEAEAE; font-style: italic}/* comment - gray */ pre .typ, code .typ {color:#89bdff}/* type - light blue */ pre .lit, code .lit {color:#3387CC}/* literal - blue */ pre .pun, code .pun {color:#fff}/* punctuation - white */ pre .pln, code .pln {color:#fff}/* plaintext - white */ pre .tag, code .tag {color:#89bdff}/* html/xml tag - light blue */ pre .atn, code .atn {color:#bdb76b}/* html/xml attribute name - khaki */ pre .atv, code .atv {color:#F3FF64}/* html/xml attribute value - yellow */ pre .dec, code .dec {color:#3387CC}/* decimal - blue */ pre, code {font-family:inherit; overflow-wrap:break-word} pre.prettyprint, code.prettyprint {background-color:#000} pre.prettyprint {padding:0.5em} /* Specify class=linenums on a pre to get line numbering */ ol.linenums {margin-top:0; margin-bottom:0; color:#AEAEAE; padding-left:2em}/* IE indents via margin-left */ li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8 {list-style-type:none} /* Alternate shading for lines */ li.L1,li.L3,li.L5,li.L7,li.L9 {background:rgb(12, 12, 12)} @media print { pre .str, code .str {color:#060} pre .kwd, code .kwd {color:#006; font-weight:bold} pre .com, code .com {color:#600; font-style:italic} pre .typ, code .typ {color:#404; font-weight:bold} pre .lit, code .lit {color:#044} pre .pun, code .pun {color:#440} pre .pln, code .pln {color:#000} pre .tag, code .tag {color:#006; font-weight:bold} pre .atn, code .atn {color:#404} pre .atv, code .atv {color:#060} } ```/ ```[.linenums.lang-html] <pre class="prettyprint linenums lang-html" style="font-size:1.6em; width:100%; height:20em"> <a href="http://kipid.tistory.com/entry/Syntax-Highlighter-in-HTML-google-code-prettify" target="_blank" class="link">인터넷에서 예쁘게 코드 입력하기 (google code prettify)</a> <div class="예제">HTML 예제가 잘 출력될까나?</div> css 출력도 별로 예쁘지 않고, sql이나 이런것도 완벽하지는 않은듯 -ㅇ-;;; c, c++, java 같은 것들 공유하라고 만든 prettifier라 그런듯? ```/ // 자세한 설명은 reference 참고 . ### C++ code ```[.linenums.lang-cpp] #include <iostream> #include <cmath> using namespace std; class Voila { private: int x,y,z; public: // Voila static const string VOILA = "Voila"; // will not interfere with embedded tags. // HTML tag(<span> 같은)를 넣어도 된다는거 같은데... color(font)는 못바꾸는듯? // tab 크기가 너무 큰거 같아서 여기서는 space 두개로 code를 썼는데... tab 넓이 설정은 어찌 못바꾸나? // 이것저것 css나 javascript를 다운 받아서 살펴봐야할듯;;;; 없으면 고쳐써야하나; Voila(int x=0, int y=0, int z=0){ this.x=x; this.y=y; this.z=z; }; ~Voila(); friend ostream &operator<<(ostream &os, const Voila &obj); }; int main(){ return 0; } ```/ ### SQL code ```[.linenums.lang-sql] // Database: 데이터가 실질적으로 적재되는 테이블들을 분류하는 상위 개념 // 생성 // SQL CREATE DATABASE Syntax CREATE DATABASE dbname; create database dbname; Create Database dbname; // 첫글자를 대문자로 쓴것만 제대로 표시되는듯? ㅡ,.ㅡ;;; Create Database `데이터베이스명` Character Set utf8 Collate utf8_general_ci; // 생성 Ex. Create Database my_db; Create Database `class0` Character Set utf8 Collate utf8_general_ci; Create Database `class1` Character Set utf8 Collate utf8_general_ci; // 삭제/제거 Drop Database `데이터베이스명`; // Drop Table 과 구분하기 위해 Database, Table 써줘야 함. // 열람 Show Databases; // 복수(pl: s붙음) +--------------------+ | Database | +--------------------+ | information_schema | | class0 | | class1 | | my_db | | mysql | | phpmyadmin | +--------------------+ // 선택 Use `데이터베이스명`; ```/ ### JAVA code ```[.linenums.lang-java] class FirstJavaProgram{ public static void main(String[] args){ System.out.println("Welcome to Java"); System.out.println("First Java Program"); } } ```/ ## Code 가 user 혹은 clien 등에 의해서 바뀐 다음에도 prettify 하려면? 대충 아래와 같이 하면 되는데... ```[.linenums.lang-html] <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script> <script> // 가장 간단히는 아래와 같이 PR.prettyPrint() 함수를 이용하면 됨. PR.prettyPrint(function () { // function to be called before PR prettyPrints. }, $("#pre-code-docuK-HTML")[0] /* Element to be prettyPrinted. (jQuery 사용.) */ ); // prettify.js 가 load 안되었을 경우를 대비해 setTimeout 이용. prettify.js 가 load 되어야 window.PR variable 이 생김. setTimeout(function later() { if (typeof PR!=='undefined'&&PR.prettyPrint) { PR.prettyPrint(function () { m.logPrint("<br><br>Code in '#pre-code-docuK-HTML' is prettyPrinted."); }, $("#pre-code-docuK-HTML")[0]); } else { setTimeout(later, 1024); } }, 1024); </script> ```/ ## 그냥 맘편히 MarkDown SEE (Super Easy Edit) of docuK 쓰세요.
```[.linenums.lang-html] Code to be prettyPrinted. ```/
위와 같은 형태의 MarkDown 으로 쓰면 쉽게 쓸 수 있음. 참조: . ## RRA
  1. googlearchive /code-prettify (Status: Archived) :: JavaScript code prettifier
    // This is a syntax highlighter written in javascript. It powers code.google.com and stackoverflow.com.
  2. Blog - craig.is - rainbows (syntax highlighting library written in Javascript);
    // I haven't used this syntax highlighter (javascript). I refer this as it seems good.
  3. Web - puzzleware.net - Code Htmler;
    // This site directly converts your code into colorized HTML texts. You can simply copy and paste it. Not excellent but quite simple way. (No option for HTML codes.)
  4. Blog - alexgorbatchev.com - Syntax Highlighter;
    // I tested this. But I don't like it much since it requires many scripts and is not stable because of table structure used in wrong manner.
  5. 내글 링크

  6. HTML docuK format ver. 2.3 (2022-12-26)
    Super Easy Edit (SEE) of docuK
반응형