- Notifications
You must be signed in to change notification settings - Fork112
Display code with syntax highlighting ✨ in native way.
License
kbiakov/CodeView-Android
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
CodeView helps to show code content with syntax highlighting in native way.
CodeView contains 3 core parts to implement necessary logic:
CodeView & related abstract adapter to provide options & customization (see below).
For highlighting it usesCodeHighlighter, it highlights your code & returns formatted content. It's based onGoogle Prettify and their Java implementation &fork.
CodeClassifier is trying to define what language is presented in the code snippet. It's built usingNaive Bayes classifier upon found open-sourceimplementation, which I rewrote in Kotlin. There is no need to work with this class directly & you must just follow instructions below. (Experimental module, may not work properly!)
Add it in your rootbuild.gradle at the end of repositories:
allprojects { repositories {... maven { url"https://jitpack.io" } }}Add the dependency:
compile'com.github.kbiakov:CodeView-Android:1.3.2'If you want to use code classifier to auto language recognizing just add to yourApplication.java:
// train classifier on app startCodeProcessor.init(this);
Having done ones on app start you can classify language for different snippets even faster, because the algorithm needs time for training on sets for the presented listings of the languages which the library has.
Add view to your layout & bind as usual:
<io.github.kbiakov.codeview.CodeViewandroid:id="@+id/code_view"android:layout_width="wrap_content"android:layout_height="wrap_content" />
CodeViewcodeView = (CodeView)findViewById(R.id.code_view);
So now you can set code using implicit form:
// auto language recognitioncodeView.setCode(getString(R.string.listing_js));
Or explicit (see available extensions below):
// will work faster!codeView.setCode(getString(R.string.listing_py),"py");
When you callsetCode(...) the view will be prepared with the default params if the view was not initialized before. So if you want some customization, it can be done using the options and/or adapter.
You can initialize the view with options:
codeView.setOptions(Options.Default.get(this) .withLanguage("python") .withCode(R.string.listing_py) .withTheme(ColorTheme.MONOKAI));
Or using adapter (seeAdapter or example for more details):
finalCustomAdaptermyAdapter =newCustomAdapter(this,getString(R.string.listing_md));codeView.setAdapter(myAdapter);
Note: EachCodeView has a adapter and each adapter has options. When callingsetOptions(...) orsetAdapter(...) the current adapter is "flushed" with the current options. If you want to save the state and just update options saving adapter or set adapter saving options you must callupdateOptions(...) orupdateAdapter(...) accordingly.
Options helps to easily set necessary params, such as code & language, color theme, font, format, shortcut params (max lines, note) and code line click listener. Some params are unnecessary.
When the view is initialized (options or adapter are set) you can manipulate the options in various ways:
codeView.getOptions() .withCode(R.string.listing_java) .withLanguage("java") .withTheme(ColorTheme.MONOKAI);
There are some default themes (see full list below):
codeView.getOptions().setTheme(ColorTheme.SOLARIZED_LIGHT);
But you can build your own from a existing one:
ColorThemeDatamyTheme =ColorTheme.SOLARIZED_LIGHT.theme() .withBgContent(android.R.color.black) .withNoteColor(android.R.color.white);codeView.getOptions().setTheme(myTheme);
Or create your own from scratch (don't forget to open PR with this stuff!):
ColorThemeDatacustomTheme =newColorThemeData(newSyntaxColors(...), ...);codeView.getOptions().setTheme(customTheme);
Set font for your code content:
codeView.getOptions().withFont(Font.Consolas);
Font.Consolas is a font preset (see the list of available below).To use your own font you can use similar method by providingTypeface or font path. Fonts are internally cached.
Manage the space that code line take. There are 3 types:Compact,ExtraCompact andMedium.Setup is similar:
// KotlincodeView.getOptions().withFont(Font.Compact)
// JavacodeView.getOptions().withFont(Format.Default.getCompact());
Also you can create customFormat by providing params such asscaleFactor,lineHeight,borderHeight (above first line and below last) andfontSize.
Sometimes you may want to take code lines under your control, and that's why you need aAdapter.
You can create your own implementation as follows:
- Create your model to store data, for example some
MyModelclass. - Extend
AbstractCodeAdapter<MyModel>typed by your model class. - Implement necessary methods in obtained
MyCodeAdapter:
// KotlinclassMyCodeAdapter :AbstractCodeAdapter<MyModel> {constructor(context:Context, content:String):super(context, content)overridefuncreateFooter(context:Context,entity:MyModel,isFirst:Boolean)=/* init & return your view here*/}
// JavapublicclassMyCodeAdapterextendsAbstractCodeAdapter<MyModel> {publicCustomAdapter(@NotNullContextcontext,@NotNullStringcontent) {// @see params in AbstractCodeAdaptersuper(context,content,true,10,context.getString(R.string.show_all),null); }@NotNull@OverridepublicViewcreateFooter(@NotNullContextcontext,CustomModelentity,booleanisFirst) {return/* your initialized view here */; }}
- Set custom adapter to your code view:
finalMyCodeAdapteradapter =newMyCodeAdapter(this,getString(R.string.listing_py));codeView.setAdapter(diffsAdapter);
- Init footer entities to provide mapper from your model to view:
// it will add an addition diff to code lineadapter.addFooterEntity(16,newMyModel(getString(R.string.py_addition_16),true));// and this a deletion diffadapter.addFooterEntity(11,newMyModel(getString(R.string.py_deletion_11),false));
- You can also add a multiple diff entities:
AbstractCodeAdapter<MyModel>.addFooterEntities(HashMap<Int,List<MyModel>>myEntities)
Here you must provide a map from code line numbers (started from 0) to list of line entities. It will be mapped by adapter to specified footer views.
SeeGithub diff as example of my "best practice" implementation.
Seeexample.
C/C++/Objective-C ("c","cc","cpp","cxx","cyc","m"), C# ("cs"), Java ("java"), Bash ("bash","bsh","csh","sh"), Python ("cv","py","python"), Perl ("perl","pl","pm"), Ruby ("rb","ruby"), JavaScript ("javascript","js"), CoffeeScript ("coffee"), Rust ("rc","rs","rust"), Appollo ("apollo","agc","aea"), Basic ("basic","cbm"), Clojure ("clj"), Css ("css"), Dart ("dart"), Erlang ("erlang","erl"), Go ("go"), Haskell ("hs"), Lisp ("cl","el","lisp","lsp","scm","ss","rkt"), Llvm ("llvm","ll"), Lua ("lua"), Matlab ("matlab"), ML (OCaml, SML, F#, etc) ("fs","ml"), Mumps ("mumps"), N ("n","nemerle"), Pascal ("pascal"), R ("r","s","R","S","Splus"), Rd ("Rd","rd"), Scala ("scala"), SQL ("sql"), Tex ("latex","tex"), VB ("vb","vbs"), VHDL ("vhdl","vhd"), Tcl ("tcl"), Wiki ("wiki.meta"), XQuery ("xq","xquery"), YAML ("yaml","yml"), Markdown ("md","markdown"), formats ("json","xml","proto"),"regex"
Didn't found yours? Please, open issue to show your interest & I'll try to add this language in next releases.
- Default (simple light theme)
- Solarized Light
- Monokai
- Consolas
- CourierNew
- DejaVuSansMono
- DroidSansMonoSlashed
- Inconsolata
- Monaco
List of apps on Play Store where this library used. Ping me if you want to be here too!
| Icon | Application |
|---|---|
| GeekBrains | |
| Codify - Codes On The Go | |
| C Programming - 200+ Offline Tutorial and Examples | |
| Awesome Android - UI Libraries | |
| GitJourney for GitHub | |
| Source Code - Lập Trình |
- You can add your theme (seeColorTheme class). Try to add some classic color themes or create your own if it looks cool. You can find many of them in different open-source text editors.
- If you are strong in regex, add missed language as shownhere. You can find existing regex for some language in different sources of libraries, which plays the same role.
- Various adapters also welcome.
Copyright (c) 2016 Kirill BiakovPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.About
Display code with syntax highlighting ✨ in native way.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors3
Uh oh!
There was an error while loading.Please reload this page.
