java实现代码高亮


  1 package JavaSyntaxHighterDemo;
  2
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.InputStreamReader;
  7 import java.util.Arrays;
  8 import java.util.HashSet;
  9 import java.util.Set;
 10
 11 /**
 12  * @author Kevin Tse
 13  * @version 0.1
 14  */
 15 public class JavaSyntaxHighlighter {
 16
 17     public static int STATE_TEXT = 1; // 普通文本
 18     public static int STATE_DOUBLE_QUOTE = 2; // 双引号
 19     public static int STATE_SINGLE_QUOTE = 3; // 单引号
 20     public static int STATE_MULTI_LINE_COMMENT = 4; // 多行注释
 21     public static int STATE_LINE_COMMENT = 5; // 单行注释
 22
 23     private int lineNumber; // 行号
 24     private boolean enableLineNumber = true; // 开启行号标志
 25
 26     public boolean isEnableLineNumber() {
 27         return enableLineNumber;
 28     }
 29
 30     // line numbers are printed by default.
 31     // but this behavior can be disabled by invoking this method and setting the
 32     // flag to false
 33     public void setEnableLineNumber(boolean enableLineNumber) {
 34         this.enableLineNumber = enableLineNumber;
 35     }
 36
 37     String[] literalArray = { "null", "true", "false" };    //字面常量
 38     String[] keywordArray = { "abstract", "break", "case", "catch", "class",
 39             "const", "continue", "default", "do", "else", "extends", "final",
 40             "finally", "for", "goto", "if", "implements", "import",
 41             "instanceof", "interface", "native", "new", "package", "private",
 42             "protected", "public", "return", "static", "strictfp", "super",
 43             "switch", "synchronized", "this", "throw", "throws", "transient",
 44             "try", "volatile", "while" };                  //关键词
 45     String[] primitiveTypeArray = { "boolean", "char", "byte", "short", "int",
 46             "long", "float", "double", "void" };           //原始数据类型
 47
 48     Set<String> literalSet = new HashSet<String>(Arrays.asList(literalArray));
 49     Set<String> keywordSet = new HashSet<String>(Arrays.asList(keywordArray));
 50     Set<String> primitiveTypeSet = new HashSet<String>(Arrays
 51             .asList(primitiveTypeArray));
 52
 53     public String process(String src) {
 54         int currentState = STATE_TEXT;
 55         int identifierLength = 0;
 56         int currentIndex = -1;
 57         char currentChar = 0;
 58         String identifier = "";
 59         StringBuffer out = new StringBuffer();
 60
 61         while (++currentIndex != src.length() - 1) {
 62             currentChar = src.charAt(currentIndex);
 63             if (Character.isJavaIdentifierPart(currentChar)) {
 64                 out.append(currentChar);
 65                 ++identifierLength;
 66                 continue;
 67             }
 68             if (identifierLength > 0) {
 69                 identifier = out.substring(out.length() - identifierLength);
 70                 if (currentState == STATE_TEXT) {
 71                     if (literalSet.contains(identifier)) { // identifier is a
 72                                                             // literal
 73                         out.insert(out.length() - identifierLength,
 74                                 "<div class=\"literalStyle\">");
 75                         out.append("</div>");
 76                     } else if (keywordSet.contains(identifier)) { // identifier
 77                                                                     // is a
 78                                                                     // keyword
 79                         out.insert(out.length() - identifierLength,
 80                                 "<div class=\"keywordStyle\">");
 81                         out.append("</div>");
 82                     } else if (primitiveTypeSet.contains(identifier)) { // identifier
 83                                                                         // is a
 84                                                                         // primitive
 85                                                                         // type
 86                         out.insert(out.length() - identifierLength,
 87                                 "<div class=\"primitiveTypeStyle\">");
 88                         out.append("</div>");
 89                     } else if (identifier.equals(identifier.toUpperCase())
 90                             && !Character.isDigit(identifier.charAt(0))) { // identifier
 91                                                                             // is
 92                                                                             // a
 93                                                                             // constant
 94                         out.insert(out.length() - identifierLength,
 95                                 "<div class=\"constantStyle\">");
 96                         out.append("</div>");
 97                     } else if (Character.isUpperCase(identifier.charAt(0))) { // identifier
 98                                                                                 // is
 99                                                                                 // non-primitive
100                                                                                 // type
101                         out.insert(out.length() - identifierLength,
102                                 "<div class=\"nonPrimitiveTypeStyle\">");
103                         out.append("</div>");
104                     }
105                 }
106             }
107
108             switch (currentChar) {
109             // because I handle the "greater than" and "less than" marks
110             // somewhere else, I comment them out here
111             // case ‘<‘:
112             // out.append("&lt;");
113             // break;
114             // case ‘>‘:
115             // out.append("&gt;");
116             // break;
117             case ‘\"‘:
118                 out.append(‘\"‘);
119                 if (currentState == STATE_TEXT) {
120                     currentState = STATE_DOUBLE_QUOTE;
121                     out.insert(out.length() - ("\"").length(),
122                             "<div class=\"doubleQuoteStyle\">");
123                 } else if (currentState == STATE_DOUBLE_QUOTE) {
124                     currentState = STATE_TEXT;
125                     out.append("</div>");
126                 }
127                 break;
128             case ‘\‘‘:
129                 out.append("\‘");
130                 if (currentState == STATE_TEXT) {
131                     currentState = STATE_SINGLE_QUOTE;
132                     out.insert(out.length() - ("\‘").length(),
133                             "<div class=\"singleQuoteStyle\">");
134                 } else if (currentState == STATE_SINGLE_QUOTE) {
135                     currentState = STATE_TEXT;
136                     out.append("</div>");
137                 }
138                 break;
139             case ‘\\‘:
140                 out.append("\\");
141                 if (currentState == STATE_DOUBLE_QUOTE
142                         || currentState == STATE_SINGLE_QUOTE) {
143                     // treat as a character escape sequence
144                     out.append(src.charAt(++currentIndex));
145                 }
146                 break;
147             // if you want to translate tabs into spaces, uncomment the
148             // following lines
149             // case ‘\t‘:
150             // // replace tabs with tabsize number of spaces
151             // for (int i = 0; i < tabSize; i++)
152             // out.append("&nbsp;&nbsp;&nbsp;&nbsp;");
153             // break;
154             case ‘*‘:
155                 out.append(‘*‘);
156                 if (currentState == STATE_TEXT && currentIndex > 0
157                         && src.charAt(currentIndex - 1) == ‘/‘) {
158                     out.insert(out.length() - ("/*").length(),
159                             "<div class=\"multiLineCommentStyle\">");
160                     currentState = STATE_MULTI_LINE_COMMENT;
161                 }
162                 break;
163             case ‘/‘:
164                 out.append("/");
165                 if (currentState == STATE_TEXT && currentIndex > 0
166                         && src.charAt(currentIndex - 1) == ‘/‘) {
167                     out.insert(out.length() - ("//").length(),
168                             "<div class=\"singleLineCommentStyle\">");
169                     currentState = STATE_LINE_COMMENT;
170                 } else if (currentState == STATE_MULTI_LINE_COMMENT) {
171                     out.append("</div>");
172                     currentState = STATE_TEXT;
173                 }
174                 break;
175             case ‘\r‘:
176             case ‘\n‘:
177                 // end single line comments
178                 if (currentState == STATE_LINE_COMMENT) {
179                     out.insert(out.length() - 1, "</div>");
180                     currentState = STATE_TEXT;
181                 }
182                 if (currentChar == ‘\r‘ && currentIndex < src.length() - 1) {
183                     out.append("\r\n");
184                     ++currentIndex;
185                 } else
186                     out.append(‘\n‘);
187
188                 if (enableLineNumber)
189                     out.append("<div class=\"lineNumberStyle\">"
190                             + (++lineNumber) + ".</div>");
191                 break;
192             case 0:
193                 if (currentState == STATE_LINE_COMMENT
194                         && currentIndex == (src.length() - 1))
195                     out.append("</div>");
196                 break;
197             default: // everything else
198                 out.append(currentChar);
199             }
200             identifierLength = 0;
201         }
202         return out.toString();
203     }
204
205     // test the program by reading a Java file as a String and letting the
206     // program process the source code
207     public static void main(String args[]) throws Exception {
208         File file = new File(
209                 "src/JavaSyntaxHighterDemo/JavaSyntaxHighlighter.java");
210         BufferedReader br = new BufferedReader(new InputStreamReader(
211                 new FileInputStream(file), "UTF-8"));
212         StringBuffer sb = new StringBuffer();
213         String temp = null;
214         while ((temp = br.readLine()) != null) {
215             sb.append(temp).append(‘\n‘);
216         }
217         String src = sb.toString();
218         JavaSyntaxHighlighter jsh = new JavaSyntaxHighlighter();
219         System.out.println(jsh.process(src));
220     }
221
222 }


java实现代码高亮

时间: 2024-07-28 19:31:50

java实现代码高亮的相关文章

Word 代码高亮

整理文档比较费事,提供个脚本放在VBA里,使Word 代码高亮的一种方法是改变颜色 'script to high light code In document Private Function isKeyword(w) As Boolean Dim keys As New Collection With keys .Add "onStart": .Add "Log": .Add "volatile": .Add "friend&quo

使用prismjs为网站添加代码高亮功能

prismjs 是一款轻量.可扩展的代码语法高亮库,使用现代化的 Web 标准构建,使用 Prismjs 可以快速为网站添加代码高亮功能,支持超过113中编程语言,还支持多种插件,是简洁.高效的代码高亮解决方案.科技爱好者博客就是使用了Prism.js 实现漂亮的代码语法高亮功能,本文教你如何在wordpress上快速使用Prismjs实现代码高亮. 一.下载JS和CSS文件并上传到网站根目录. 在Prismjs网站下载页面下载需要的JS和CSS文件,下载页面: http://prismjs.c

[转]7个高性能JavaScript代码高亮插件

对于喜欢写技术博客的同学来说,一定对代码高亮组件非常熟悉.一款优秀的JavaScript代码高亮插件,将会帮助你渲染任何一种编程语言,包括一些关键字的着色,以及每行代码的缩进等.今天我们要来分享一些高性能的JavaScript代码高亮插件,这些JavaScript代码高亮插件将非常有效地帮你实现在网页上的代码编辑和展示. 1.SyntaxHighlighter – 最优秀的JavaScript代码高亮插件 SyntaxHighlighter 是一款完全基于JavaScript的代码高亮插件,Sy

SyntaxHighlighter代码高亮插件

SyntaxHighlighter是Google Code上的一个开源项目,主要用于给网页上的代码着色, 使用十分方便,效果也不错,而且几乎支持常见的所有语言. 使用步骤: 一.下载并解压缩SyntaxHighlighter(http://download.csdn.net/detail/itmyhome/7757359)当前版本3.0.83 二.引入文件 将解压后的scripts和styles文件夹复制到项目中,在页面中引入shCore.js和核心CSS文件shCore.css 其次引入你要高

7个高性能JavaScript代码高亮插件

本文由码农网 – 小峰原创,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划! 对于喜欢写技术博客的同学来说,一定对代码高亮组件非常熟悉.一款优秀的JavaScript代码高亮插件,将会帮助你渲染任何一种编程语言,包括一些关键字的着色,以及每行代码的缩进等.今天我们要来分享一些高性能的JavaScript代码高亮插件,这些JavaScript代码高亮插件将非常有效地帮你实现在网页上的代码编辑和展示. 1.SyntaxHighlighter – 最优秀的JavaScript代码高亮插件 Syn

9个实用的Javascript代码高亮脚本

代码高亮很有用,特别是在需要在网站或者blog中显示自己编写的代码的时候,或者给其他人查看或调试语法错误的时候.我们可以将代码高亮,以便阅读者可以十分方便的读取代码块,增加用户阅读代码的良好体验. 目前,有很多免费而且有用的代码高亮脚本.这些脚本大多是由Javascript语言编写,也有些使用其它语言(比如java.Phyton或Ruby)等写的. 下面来推荐最受欢迎.最实用的9个Javascript代码高亮脚本. 1. SyntaxHighlighter 我相信这是最普遍代码高亮代码.它支持多

bootstrap设计网站中添加代码高亮插件

这款插件的名字叫做google-code-prettify 使用该插件之前的效果: 使用插件之后的效果: 接下来说步骤: (1)下载两个文件 http://codecloud.sinaapp.com/google-code-prettify/prettify.css http://codecloud.sinaapp.com/google-code-prettify/prettify.js (2)在head中引入这两个文件 <link href="google-code-prettify/p

代码高亮插件SyntaxHighlighter

一 第一 解压压缩包,scripts文件夹中包含了各种语言的JS文件,在styles文件夹中是各种显示高亮的主题 第二 如何使用?首先要引入其核心javascript文件shCore.js和核心CSS文件shCore.css,这两个是必选要引入的.其次引入你要高亮的语言JS,比如我想高亮显示的是C#,那么必须引入在scripts文件夹中的shBrushCSharp.js,最后引入高亮显示的主题CSS,默认的为shThemeDefault.css 第三 下面以高亮显示JavaScript代码为例讲

在Github README.md中插入图片以及代码高亮

1.插入图片: 首先在项目根目录建个存图片的文件夹放入图片,提交这个目录,在github里找到这张图片,复制图片连接,在readme里插入以下代码 ![image](https://github.com/xxxx.jpg) 2.代码高亮: ```java //这里放你的代码 ``` 另有懒人法: 在博客编辑器里编辑你的readme,然后点html,把这些html代码复制到readme也可.