HTMLRewrite.cpp revision 6a34083e9f74a45e2f79c9fab66f177809a5db66
1//== HTMLRewrite.cpp - Translate source code into prettified HTML --*- C++ -*-// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the HTMLRewriter clas, which is used to translate the 11// text of a source file into prettified HTML. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Rewrite/Rewriter.h" 16#include "clang/Rewrite/HTMLRewrite.h" 17#include "clang/Basic/SourceManager.h" 18#include "llvm/Support/MemoryBuffer.h" 19#include <sstream> 20 21using namespace clang; 22 23void html::EscapeText(Rewriter& R, unsigned FileID, bool EscapeSpaces) { 24 25 const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID); 26 const char* C = Buf->getBufferStart(); 27 const char* FileEnd = Buf->getBufferEnd(); 28 29 assert (C <= FileEnd); 30 31 for (unsigned FilePos = 0; C != FileEnd ; ++C, ++FilePos) { 32 33 SourceLocation Loc = SourceLocation::getFileLoc(FileID, FilePos); 34 35 switch (*C) { 36 default: break; 37 38 case ' ': 39 if (EscapeSpaces) R.ReplaceText(Loc, 1, " ", 5); 40 break; 41 42 case '<': R.ReplaceText(Loc, 1, "<", 4); break; 43 case '>': R.ReplaceText(Loc, 1, ">", 4); break; 44 case '&': R.ReplaceText(Loc, 1, "&", 5); break; 45 } 46 } 47} 48 49void html::InsertTag(Rewriter& R, html::Tags tag, 50 SourceLocation B, SourceLocation E, 51 bool NewlineOpen, bool NewlineClose) { 52 53 const char* TagStr = 0; 54 55 switch (tag) { 56 default: break; 57 case PRE: TagStr = "pre"; break; 58 case HEAD: TagStr = "head"; break; 59 case BODY: TagStr = "body"; break; 60 } 61 62 assert (TagStr && "Tag not supported."); 63 64 { // Generate the opening tag. 65 std::ostringstream os; 66 os << '<' << TagStr << '>'; 67 if (NewlineOpen) os << '\n'; 68 R.InsertTextAfter(B, os.str().c_str(), os.str().size()); 69 } 70 71 { // Generate the closing tag. 72 std::ostringstream os; 73 os << "</" << TagStr << '>'; 74 if (NewlineClose) os << '\n'; 75 R.InsertTextBefore(E, os.str().c_str(), os.str().size()); 76 } 77} 78