Markwon


Source link: https://github.com/noties/Markwon

Markwon

Markwon is a library for Android that renders markdown as system-native Spannables. It gives ability to display markdown in all TextView widgets ( TextView, Button, Switch, CheckBox, etc), Notifications, Toasts, etc. No WebView is required. Library provides reasonable defaults for display style of markdown but also gives all the means to tweak the appearance if desired. All markdown features are supported (including limited support for inlined HTML code, markdown tables and images).

*This file is displayed by default in the sample-apk application. Which is a generic markdown viewer with support to display markdown via http, https & file schemes and 2 themes included: Light & Dark

Installation

compile 'ru.noties:markwon:1.0.1' compile 'ru.noties:markwon-image-loader:1.0.1' // optional compile 'ru.noties:markwon-view:1.0.1' // optional

Supported markdown features:

  • Emphasis ( *, _)
  • Strong emphasis ( **, __)
  • Strike-through ( ~~)
  • Headers ( #{ 1,6 } )
  • Links ( []() && [][])
  • Images ( requires special handling)
  • Thematic break ( ---, ***, ___)
  • Quotes & nested quotes ( >{ 1, } )
  • Ordered & non-ordered lists & nested ones
  • Inline code
  • Code blocks
  • Tables ( with limitations)
  • Small subset of inline-html (which is rendered by this library):
    • Emphasis ( <i>, <em>, <cite>, <dfn>)
    • Strong emphasis ( <b>, <strong>)
    • SuperScript ( <sup>)
    • SubScript ( <sub>)
    • Underline ( <u>)
    • Strike-through ( <s>, <strike>, <del>)
    • other inline html is rendered via ( Html.fromHtml(...))
  • Task lists:
  • Not done
    • Done with X
    • and or small x

Screenshots

Taken with default configuration (except for image loading):

By default configuration uses TextView textColor for styling, so changing textColor changes style


Quick start

This is the most simple way to set markdown to a TextView or any of its siblings:

Markwon.setMarkdown(textView, markdown);

It's just a helper method, that does underneath:

  • constructs a Parser (see: commonmark-java) and parses markdown
  • constructs a SpannableConfiguration
  • renders parsed markdown to Spannable (via SpannableRenderer)
  • prepares TextView to display images, tables and links
  • sets text

This flow answers the most simple usage of displaying markdown: one shot parsing & configuration of relatively small markdown chunks. If your markdown contains a lot of text or you plan to display multiple UI widgets with markdown you might consider stepping in and taking control of this flow.

The candidate requirements to step in:

  • parsing and processing of parsed markdown in background thread
  • reusing Parser and/or SpannableConfiguration between multiple calls
  • ignore images and tables specific logic (you know that markdown won't contain them)

So, if we expand Markwon.setMarkdown(textView, markdown) method we will see the following:

// create a Parser instance (can be done manually) // internally creates default Parser instance & registers `strike-through` & `tables` extension final Parser parser = Markwon.createParser();
  // core class to display markdown, can be obtained via this method, // which creates default instance (no images handling though), // or via `builder` method, which lets you to configure this instance // // `this` refers to a Context instance final SpannableConfiguration configuration = SpannableConfiguration.create(this);
  // it's better **not** to re-use this class between multiple calls final SpannableRenderer renderer = new SpannableRenderer();
  final Node node = parser.parse(markdown);
 final CharSequence text = renderer.render(configuration, node);
  // for links in markdown to be clickable textView.setMovementMethod(LinkMovementMethod.getInstance());
  // we need these due to the limited nature of Spannables to invalidate TextView Markwon.unscheduleDrawables(textView);
 Markwon.unscheduleTableRows(textView);
  textView.setText(text);
  Markwon.scheduleDrawables(textView);
 Markwon.scheduleTableRows(textView);

Please refer to SpannableConfiguration document for more info


Demo

Based on this cheatsheet


Headers


Header 1

Header 2

Header 3

Header 4

Header 5
Header 6

Emphasis

Emphasis, aka italics, with asterisks or underscores.

Strong emphasis, aka bold, with asterisks or underscores.

Combined emphasis with asterisks and underscores.

Strikethrough uses two tildes. Scratch this.


Lists

  1. First ordered list item
  2. Another item
  • Unordered sub-list.
  1. Actual numbers don't matter, just that it's a number

  2. Ordered sub-list

  3. And another item.

    You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).

    To have a line break without a paragraph, you will need to use two trailing spaces. Note that this line is separate, but within the same paragraph. (This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.)

  • Unordered list can use asterisks
  • Or minuses
  • Or pluses

Links

I'm an inline-style link

I'm a reference-style link

I'm a relative reference to a repository file

You can use numbers for reference-style link definitions

Or leave it empty and use the link text itself.


Code

Inline code has back-ticks around it.

*Please note, that syntax highlighting is supported but library provides no means to do it automatically

var s = "JavaScript syntax highlighting"; alert(s);
s = "Python syntax highlighting" print s
No language indicated, so no syntax highlighting. But let's throw in a <b>tag</b>. 

Tables

Colons can be used to align columns.

Tables Are Cool
col 3 is right-aligned $1600
col 2 is centered $12
zebra stripes are neat $1

There must be at least 3 dashes separating each header cell. The outer pipes (|) are optional, and you don't need to make the raw Markdown line up prettily. You can also use inline Markdown.

Markdown Less Pretty
Still renders nicely
1 2 3

Blockquotes

Blockquotes are very handy in email to emulate reply text. This line is part of the same quote.

Quote break.

This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can put Markdown into a blockquote.

Nested quotes

Hello!

And to you!


Inline HTML

*As Android doesn't support HTML out of box, Markwon library supports only a small subset of it. Everything else is rendered via Html.fromHtml()

  • Emphasis ( <i>, <em>, <cite>, <dfn>)
  • Strong emphasis ( <b>, <strong>)
  • SuperScript ( <sup>)
  • SubScript ( <sub>)
  • Underline ( <u>)
  • Strike-through ( <s>, <strike>, <del>)

Let's use it: H T ML


Horizontal Rule

Three or more...


Hyphens ( -)


Asterisks ( *)


Underscores ( _)


License

  Copyright 2017 Dimitry Ivanov ([email protected])
 Licensed under the Apache License, Version 2.0 (the "License");

you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. 

Resources

Imitation QQ discussion group Avatar.

Simple View injection framework to be used as a tool for learning compile-time Annotation Processing.

Simple to use library for animating color change for ActionBar, NavigationBar, and status bar. Apply background tinting to the Android system UI when using KitKat translucent modes.

A data-binding Presentation Model (MVVM) framework for the Android platform.

ColorMixer is a widget for choosing a color in HSV color-space.

Conversations is an open source XMPP (formally known as Jabber) client for Android 4.0+ smart phones.

Features:

  • End-to-end encryption with either OTR or openPGP
  • Sending and receiving images
  • Indication when your contact has read your message
  • Intuitive UI that follows Android Design guidelines
  • Pictures / Avatars for your Contacts
  • Syncs with desktop client
  • Conferences (with support for bookmarks)
  • Address book integration
  • Multiple Accounts / unified inbox
  • Very low impact on battery life

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes