2016년 6월 6일 월요일

Google blog (Blogger) - Source code 예쁘게 올리기

요약: Google Code Prettify (https://github.com/google/code-prettify)를 이용한다.

1. Google blog에 login 한 상태로 오른쪽 위의 "디자인"을 click.

2. "템플릿" → "HTML 편집" 선택.

3. 오른쪽의 code에서 "</head>" 앞에 다음과 같이 입력하고 "템플릿 저장"을 click.
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>

4. 완성. Blog에 글을 쓸 때, "HTML"을 선택하고 다음과 같이 "<pre class="prettyprint">"와 "</pre>" 사이에 source code를 넣으면 된다.
<pre class="prettyprint">int main(int argc, char *argv[]) {
  return 0;
}</pre>

5. 글을 게시하면 다음과 같이 source code가 예쁘게 나타남.
int main(int argc, char *argv[]) {
  return 0;
}

※ HTML이 특별하게 취급하는 문자들은 다음과 같이 바꿔줘야 (escape해야) 함.
fromto
&&amp;
<&lt;
>&gt;
"&quot;

이를 위해 나는 다음 C++ program을 만들어 사용:
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

void ReplaceAll(string &str, char from, string to) {
  size_t pos = 0;
  while (true) {
    pos = str.find(from, pos);
    if (pos == string::npos) break;

    str.replace(pos, 1, to);
    pos += to.length();
  }
}

int main(int argc, char *argv[]) {
  if (argc != 2) {
    cerr << "usage: " << argv[0] << " [input file]" << endl;
    exit(1);
  }

  string ifname = argv[1];
  ifstream ifile(ifname);
  if (!ifile.is_open()) {
    cerr << "cannot open: " << ifname << endl;
    exit(1);
  }

  string ofname = ifname.insert(ifname.length() - 4, ".pre");
  ofstream ofile(ofname);
  if (!ofile.is_open()) {
    cerr << "cannot open: " << ofname << endl;
    exit(1);
  }

  string line;
  while (getline(ifile, line)) {
    ReplaceAll(line, '&', "&amp;");
    ReplaceAll(line, '<', "&lt;");
    ReplaceAll(line, '>', "&gt;");
    ReplaceAll(line, '\"', "&quot;");

    ofile << line << endl;
  }

  ifile.close();
  ofile.close();
}

참고:
  1. https://www.sitepoint.com/everything-need-know-html-pre-element/