Display code with syntax highlighting :sparkles: in native way.

Overview

CodeView (Android)

Android Arsenal Release Build Status

CodeView helps to show code content with syntax highlighting in native way.

Description

CodeView contains 3 core parts to implement necessary logic:

  1. CodeView & related abstract adapter to provide options & customization (see below).

  2. For highlighting it uses CodeHighlighter, it highlights your code & returns formatted content. It's based on Google Prettify and their Java implementation & fork.

  3. CodeClassifier is trying to define what language is presented in the code snippet. It's built using Naive Bayes classifier upon found open-source implementation, 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!)

Download

Add it in your root build.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'

Usage

If you want to use code classifier to auto language recognizing just add to your Application.java:

// train classifier on app start
CodeProcessor.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.CodeView
	android:id="@+id/code_view"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content" />
CodeView codeView = (CodeView) findViewById(R.id.code_view);

So now you can set code using implicit form:

// auto language recognition
codeView.setCode(getString(R.string.listing_js));

Or explicit (see available extensions below):

// will work faster!
codeView.setCode(getString(R.string.listing_py), "py");

Customization

When you call setCode(...) 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.

Initialization

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 (see Adapter or example for more details):

final CustomAdapter myAdapter = new CustomAdapter(this, getString(R.string.listing_md));
codeView.setAdapter(myAdapter);

Note: Each CodeView has a adapter and each adapter has options. When calling setOptions(...) or setAdapter(...) 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 call updateOptions(...) or updateAdapter(...) accordingly.

Options

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);

Color theme

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:

ColorThemeData myTheme = 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!):

ColorThemeData customTheme = new ColorThemeData(new SyntaxColors(...), ...);
codeView.getOptions().setTheme(customTheme);

Font

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 providing Typeface or font path. Fonts are internally cached.

Format

Manage the space that code line take. There are 3 types: Compact, ExtraCompact and Medium. Setup is similar:

// Kotlin
codeView.getOptions().withFont(Font.Compact)
// Java
codeView.getOptions().withFont(Format.Default.getCompact());

Also you can create custom Format by providing params such as scaleFactor, lineHeight, borderHeight (above first line and below last) and fontSize.

Adapter

Sometimes you may want to take code lines under your control, and that's why you need a Adapter.

You can create your own implementation as follows:

  1. Create your model to store data, for example some MyModel class.
  2. Extend AbstractCodeAdapter<MyModel> typed by your model class.
  3. Implement necessary methods in obtained MyCodeAdapter:
// Kotlin
class MyCodeAdapter : AbstractCodeAdapter<MyModel> {
    constructor(context: Context, content: String) : super(context, content)

    override fun createFooter(context: Context, entity: MyModel, isFirst: Boolean) =
        /* init & return your view here */
}
// Java
public class MyCodeAdapter extends AbstractCodeAdapter<MyModel> {
    public CustomAdapter(@NotNull Context context, @NotNull String content) {
    	// @see params in AbstractCodeAdapter
        super(context, content, true, 10, context.getString(R.string.show_all), null);
    }

    @NotNull
    @Override
    public View createFooter(@NotNull Context context, CustomModel entity, boolean isFirst) {
        return /* your initialized view here */;
    }
}

  1. Set custom adapter to your code view:
final MyCodeAdapter adapter = new MyCodeAdapter(this, getString(R.string.listing_py));
codeView.setAdapter(diffsAdapter);

  1. Init footer entities to provide mapper from your model to view:
// it will add an addition diff to code line
adapter.addFooterEntity(16, new MyModel(getString(R.string.py_addition_16), true));
// and this a deletion diff
adapter.addFooterEntity(11, new MyModel(getString(R.string.py_deletion_11), false));

  1. 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.

See Github diff as example of my "best practice" implementation.

How it looks in app

See example.

CodeView_Android_Solarized_light

List of available languages & their extensions

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.

List of available themes

List of available fonts

  • Consolas
  • CourierNew
  • DejaVuSansMono
  • DroidSansMonoSlashed
  • Inconsolata
  • Monaco

Used by

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

Contribute

  1. You can add your theme (see ColorTheme 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.
  2. If you are strong in regex, add missed language as shown here. You can find existing regex for some language in different sources of libraries, which plays the same role.
  3. Various adapters also welcome.

Author

Kirill Biakov

License MIT

Copyright (c) 2016 Kirill Biakov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, 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 THE
SOFTWARE.
Comments
  • when i am fetching the string of formatted code from Firebase Realtime database the code showing in a single line.

    when i am fetching the string of formatted code from Firebase Realtime database the code showing in a single line.

    ###DetailActivity.xml ``

    <TextView
        android:id="@+id/textViewrv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="40dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="program name sample as login  to firebase"
        android:layout_centerHorizontal="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
    <!-- CODEVIEW  program-->
    <RelativeLayout
        android:layout_below="@+id/textViewrv1"
        android:layout_width="match_parent"
        android:layout_marginTop="10dp"
        android:orientation="vertical"
        android:layout_height="match_parent">
    
    
       <io.github.kbiakov.codeview.CodeView
           android:id="@+id/code_view_text"
           android:layout_width="match_parent"
           android:layout_height="match_parent"></io.github.kbiakov.codeview.CodeView>
    </RelativeLayout>
    

    DetailActivity.java

    package com.rajendra.firebaseproject.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.rajendra.firebaseproject.R; import io.github.kbiakov.codeview.CodeView; import io.github.kbiakov.codeview.adapters.Options; import io.github.kbiakov.codeview.classifier.CodeProcessor; import io.github.kbiakov.codeview.highlight.ColorTheme; public class DetailActivity extends AppCompatActivity {

    String pname,pcontent;
    TextView rvpname;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        pname = getIntent().getExtras().getString("sendPNAME");
        pcontent = getIntent().getExtras().getString("sendPCONTENT");
        rvpname =findViewById(R.id.textViewrv1);
        rvpname.setText(pname);
        CodeProcessor.init(this);
        CodeView codeView = (CodeView) findViewById(R.id.code_view_text);
        //codeView.setCode(pcontent, "c");
    
        codeView.setOptions(Options.Default.get(this)
                .withLanguage("c")
                .withCode(pcontent)
                .withTheme(ColorTheme.MONOKAI));
    
    
    }
    

    }

    but the ans is showing like this screenshots :

    image

    opened by mRAJENDRAKUMAR-droid 4
  • Initial tab/space is trimmed at the starting of each new line

    Initial tab/space is trimmed at the starting of each new line

    I have recently used this library to highlight the syntax. But it trimmed initial spaces and white space characters at the beginning of each new line. This has made difficult to understand the code. Please add this feature.

    bug 
    opened by khokharnikunj8 4
  • Cannot compile

    Cannot compile

    Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
    > com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/jetbrains/annotations/NotNull.class
    

    After adding your lib, i get this error

    https://github.com/gitskarios/Gitskarios/blob/code_view/app/build.gradle#L266

    help wanted 
    opened by alorma 4
  • Customize adapter

    Customize adapter

    It will be really great if we can set something depending on lines.

    For example: at Gitskarios i'm gonna use this lib to show content, and commits diff, so sometimes i need to add comments in a line

    enhancement 
    opened by alorma 4
  • CodeView appears in 2s and then disappear, except 1st line

    CodeView appears in 2s and then disappear, except 1st line

    I have one Activity just to show the CodeView. It appears at the first time I start the Activity. When I restart the activity, it appears like in 2s and then disappears. I have no error, no special warning, etc see more https://github.com/lilliCao/javoid I followed your instruction and only used default value.

    opened by lilliCao 3
  • code show in one line

    code show in one line

    CodeView codeView = (CodeView) findViewById(R.id.code_view);

        codeView.setVerticalFadingEdgeEnabled(true);
        codeView.highlightCode("java")
                .setColorTheme(ColorTheme.SOLARIZED_LIGHT)
                .setCodeContent(getString(R.string.code));
    
    help wanted 
    opened by Dishant624 3
  • Update dependencies

    Update dependencies

    Use

    implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
    implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha01'
    

    instead of

    compile "com.android.support:appcompat-v7:$supportLibrary"
    compile "com.android.support:recyclerview-v7:$supportLibrary"
    
    opened by DATL4G 1
  • Project versions out-of-date

    Project versions out-of-date

    Hello there,

    after improting this project into my IDE, it was screaming towards me the project is using various outdated dependency resources. Only after updating all of them I was able to build the project properly.

    In particular I had to update all build.gradle files as well as the gradle-wrapper.properties file in order to make the project build again in Android Studio. So before opening a pull-request straight away to fix those issues I wanted to make sure if there is not any particular reason not to update all that stuff?

    opened by Brainsucker92 1
  • How wrap code to next line?

    How wrap code to next line?

    I need to put codeview in a scrolling element, but because of this issue I can't so I'm trying to figure out a workaround by disabling clickable on the codeview, but then I can't have code that isn't visible because it's off screen.

    For me, it's okay if the code isn't clickable/scrollable/selectable. Is there a way to wrap code to the next line?

    opened by AdityaAnand1 1
  • Add newline

    Add newline "\n" in every end of line

    Is there any solution that adds "\n" in every end of a line? Or any other way that can manage pure code of any programming language without adding "\n" in every line. Thanks 👍

    opened by mostasim 1
  • Disable blink animation on refresh of codeview

    Disable blink animation on refresh of codeview

    How do I disable blink animation when a codeview is reset. programCodeView.setOptions(Options.Default.get(getContext()) .withLanguage(programLanguage) .withCode(programLines) .withTheme(ColorTheme.MONOKAI));

    This code is used to set program lines to the code view, there's a blink which happens at this point. Can it be disabled?

    enhancement 
    opened by alokomkar 1
  • Fix recyclerview fill all items

    Fix recyclerview fill all items

    Pass MeasureSpec.UNSPECIFIED mode to child RecyclerView for providing a virtual 'infinite' vertical space will cause LinearLayoutManager try to 'fill' remaining space using ALL items in adapter, which may let main thread running measures for a long time. Just provide an 'infinite' horizontal space for long-line code is enough, then layout manager and touch event handle methods in RecyclerView can handle vertical scrolling perfectly. Can also fix missing velocity in code panel.

    Flame chart showing such issue: image

    Screen records (Xiaomi MIX2S, Qualcomm 845, should not appear a loading holder for just a 370+ lines log file.):

    out

    opened by LinZong 0
  • adds 1 MB to APK size

    adds 1 MB to APK size

    When including the library, a folder assets/training-set is visible in the decompiled APK (Build>Analyze Apk) which is contributing 1 Mb to the APK size.

    opened by sriharivishnu 0
Releases(1.3.2)
Owner
Kirill Biakov
Sr. Android developer at @tutu-ru. Passionate about mobile app architecture, Kotlin and Rx.
Kirill Biakov
Make your native android Dialog Fancy. A library that takes the standard Android Dialog to the next level with a variety of styling options. Style your dialog from code.

FancyAlertDialog-Android Prerequisites Add this in your root build.gradle file (not your module build.gradle file): allprojects { repositories { ..

Shashank Singhal 350 Dec 9, 2022
This is a sample Android Studio project that shows the necessary code to create a note list widget, And it's an implementation of a lesson on the Pluralsight platform, but with some code improvements

NoteKeeper-Custom-Widgets This is a sample Android Studio project that shows the necessary code to create a note list widget, And it's an implementati

Ibrahim Mushtaha 3 Oct 29, 2022
MarkdownView is an Android webview with the capablity of loading Markdown text or file and display it as HTML, it uses MarkdownJ and extends Android webview.

About MarkdownView (Markdown For Android) is an Android library that helps you display Markdown text or files (local/remote) as formatted HTML, and st

Feras Alnatsheh 1k Dec 20, 2022
Implementation of the fragment with the ability to display indeterminate progress indicator when you are waiting for the initial data.

Android-ProgressFragment Implementation of the fragment with the ability to display indeterminate progress indicator when you are waiting for the init

Evgeny Shishkin 813 Nov 11, 2022
Android Library to display your changelog

ChangeLog Library ChangeLog Library provides an easy way to display a change log in your Android app. Travis master: Travis dev: Examples Sample appli

Gabriele Mariotti 861 Nov 11, 2022
Android library to display a list of items for pick one

PickerUI Android library to display a list of items for pick one with blur effect (if you wish). Support for Android 3.0 and up. It supports portrait

David Pizarro 630 Nov 19, 2022
ckChangeLog - An Android Library to display a Change Log

ckChangeLog - An Android Library to display a Change Log This library provides an easy way to display a change log in your app. Features Displays chan

cketti 182 Dec 3, 2022
An Android custom view to display digits rendered as dots in a grid, with a style like a 1970s LED clock.

#DotMatrixView This is an Android library project providing a custom view that can display things on a grid of dots. When the displayed value changes,

Mark Roberts 48 Apr 21, 2022
Android App that communicates with a back-end server to display different One Piece characters

About This project is an Android App that communicates with a back-end server to display different One Piece characters. It's roughly based on this co

Sam Garcia 1 Feb 4, 2022
:bread: Make your native android Toasts Tasty

TastyToast Make your native android toast look beautiful. Preview About Refer Here Wiki Grab the above demo app from here : Dependency Add dependency

Rahul Yadav 2k Dec 29, 2022
Kotlin/Native interop to libui: a portable GUI library

kotlin-libui Kotlin/Native bindings to the libui C library. libui is a C lightweight multi-platform UI library using native widgets on Linux (Gtk3), m

Mike Sinkovsky 611 Dec 30, 2022
MIUINativeNotifyIcon - Fix the native notification bar icon function abandoned by the MIUI development team

MIUI 原生通知图标 Fix the native notification bar icon function abandoned by the MIUI

Fankesyooni 189 Jan 4, 2023
Rn-scratch-card - React Native Scratch Card which temporarily hides content from user

rn-scratch-card React Native Scratch Card which temporarily hides content from a

Sweatcoin 54 Jan 4, 2023
This library provides a simple way to add a draggable sliding up panel (popularized by Google Music and Google Maps) to your Android application. Brought to you by Umano.

Note: we are not actively responding to issues right now. If you find a bug, please submit a PR. Android Sliding Up Panel This library provides a simp

Umano: News Read To You 9.4k Dec 31, 2022
[] A simple way to "badge" any given Android view at runtime without having to cater for it in layout

Android ViewBadger A simple way to "badge" any given Android view at runtime without having to cater for it in layout. Note: If your aim is to replica

Jeff Gilfelt 3k Nov 28, 2022
An elegant way to show your menu or messages.

Android View Hover In my opinion, jumping to a new activity to show your menu is a kind of wasting time and life. So, I think, we need a hover view, t

代码家 3.2k Jan 2, 2023
TourGuide is an Android library that aims to provide an easy way to add pointers with animations over a desired Android View

TourGuide TourGuide is an Android library. It lets you add pointer, overlay and tooltip easily, guiding users on how to use your app. Refer to the exa

Tan Jun Rong 2.6k Jan 5, 2023
Bubbles for Android is an Android library to provide chat heads capabilities on your apps. With a fast way to integrate with your development.

Bubbles for Android Bubbles for Android is an Android library to provide chat heads capabilities on your apps. With a fast way to integrate with your

Txus Ballesteros 1.5k Jan 2, 2023
SwipeBack for Android Activities to do pretty the same as the android "back-button" will do, but in a really intuitive way by using a swipe gesture

SwipeBack SwipeBack is for Android Activities to do pretty the same as the android "back-button" will do, but in a really intuitive way by using a swi

Hannes Dorfmann 697 Dec 14, 2022