├── settings.gradle
├── example.gif
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── app
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── drawable-hdpi
│ │ │ │ ├── ic_action_redo.png
│ │ │ │ ├── ic_action_undo.png
│ │ │ │ ├── ic_format_bold.png
│ │ │ │ ├── ic_format_clear.png
│ │ │ │ ├── ic_format_quote.png
│ │ │ │ ├── ic_insert_link.png
│ │ │ │ ├── ic_format_bullet.png
│ │ │ │ ├── ic_format_italic.png
│ │ │ │ ├── ic_format_underline.png
│ │ │ │ └── ic_format_strikethrough.png
│ │ │ ├── drawable-mdpi
│ │ │ │ ├── ic_action_redo.png
│ │ │ │ ├── ic_action_undo.png
│ │ │ │ ├── ic_format_bold.png
│ │ │ │ ├── ic_format_clear.png
│ │ │ │ ├── ic_format_quote.png
│ │ │ │ ├── ic_insert_link.png
│ │ │ │ ├── ic_format_bullet.png
│ │ │ │ ├── ic_format_italic.png
│ │ │ │ ├── ic_format_underline.png
│ │ │ │ └── ic_format_strikethrough.png
│ │ │ ├── drawable-xhdpi
│ │ │ │ ├── ic_action_redo.png
│ │ │ │ ├── ic_action_undo.png
│ │ │ │ ├── ic_format_bold.png
│ │ │ │ ├── ic_insert_link.png
│ │ │ │ ├── ic_format_bullet.png
│ │ │ │ ├── ic_format_clear.png
│ │ │ │ ├── ic_format_italic.png
│ │ │ │ ├── ic_format_quote.png
│ │ │ │ ├── ic_format_underline.png
│ │ │ │ └── ic_format_strikethrough.png
│ │ │ ├── drawable-xxhdpi
│ │ │ │ ├── ic_action_redo.png
│ │ │ │ ├── ic_action_undo.png
│ │ │ │ ├── ic_format_bold.png
│ │ │ │ ├── ic_format_bullet.png
│ │ │ │ ├── ic_format_clear.png
│ │ │ │ ├── ic_format_italic.png
│ │ │ │ ├── ic_format_quote.png
│ │ │ │ ├── ic_insert_link.png
│ │ │ │ ├── ic_format_underline.png
│ │ │ │ └── ic_format_strikethrough.png
│ │ │ ├── drawable-xxxhdpi
│ │ │ │ ├── ic_action_redo.png
│ │ │ │ ├── ic_action_undo.png
│ │ │ │ ├── ic_format_bold.png
│ │ │ │ ├── ic_format_clear.png
│ │ │ │ ├── ic_format_quote.png
│ │ │ │ ├── ic_insert_link.png
│ │ │ │ ├── ic_format_bullet.png
│ │ │ │ ├── ic_format_italic.png
│ │ │ │ ├── ic_format_underline.png
│ │ │ │ └── ic_format_strikethrough.png
│ │ │ ├── values
│ │ │ │ ├── styles.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── strings.xml
│ │ │ ├── menu
│ │ │ │ └── menu_main.xml
│ │ │ ├── layout
│ │ │ │ ├── dialog_link.xml
│ │ │ │ └── activity_main.xml
│ │ │ └── values-v21
│ │ │ │ └── styles.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── io
│ │ │ └── github
│ │ │ └── mthli
│ │ │ └── knifedemo
│ │ │ └── MainActivity.java
│ └── androidTest
│ │ └── java
│ │ └── io
│ │ └── github
│ │ └── mthli
│ │ └── knifedemo
│ │ └── ApplicationTest.java
├── build.gradle
└── proguard-rules.pro
├── knife
├── src
│ ├── androidTest
│ │ └── java
│ │ │ └── io
│ │ │ └── github
│ │ │ └── mthli
│ │ │ └── knife
│ │ │ └── ApplicationTest.java
│ └── main
│ │ ├── res
│ │ └── values
│ │ │ ├── strings.xml
│ │ │ └── attrs.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── io
│ │ └── github
│ │ └── mthli
│ │ └── knife
│ │ ├── KnifePart.java
│ │ ├── KnifeURLSpan.java
│ │ ├── KnifeQuoteSpan.java
│ │ ├── KnifeBulletSpan.java
│ │ ├── KnifeTagHandler.java
│ │ ├── KnifeParser.java
│ │ └── KnifeText.java
├── proguard-rules.pro
└── build.gradle
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':knife'
2 |
--------------------------------------------------------------------------------
/example.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/example.gif
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_action_redo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_action_redo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_action_undo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_action_undo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_format_bold.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_format_bold.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_format_clear.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_format_clear.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_format_quote.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_format_quote.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_insert_link.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_insert_link.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_action_redo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_action_redo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_action_undo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_action_undo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_format_bold.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_format_bold.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_format_clear.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_format_clear.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_format_quote.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_format_quote.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_insert_link.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_insert_link.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_action_redo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_action_redo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_action_undo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_action_undo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_format_bold.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_format_bold.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_insert_link.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_insert_link.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_format_bullet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_format_bullet.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_format_italic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_format_italic.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_format_bullet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_format_bullet.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_format_italic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_format_italic.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_format_bullet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_format_bullet.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_format_clear.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_format_clear.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_format_italic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_format_italic.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_format_quote.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_format_quote.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_action_redo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_action_redo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_action_undo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_action_undo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_format_bold.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_format_bold.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_format_bullet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_format_bullet.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_format_clear.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_format_clear.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_format_italic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_format_italic.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_format_quote.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_format_quote.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_insert_link.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_insert_link.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_action_redo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_action_redo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_action_undo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_action_undo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_format_bold.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_format_bold.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_format_clear.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_format_clear.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_format_quote.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_format_quote.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_insert_link.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_insert_link.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_format_underline.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_format_underline.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_format_underline.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_format_underline.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_format_underline.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_format_underline.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_format_bullet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_format_bullet.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_format_italic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_format_italic.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_format_strikethrough.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-hdpi/ic_format_strikethrough.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_format_strikethrough.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-mdpi/ic_format_strikethrough.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_format_underline.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_format_underline.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_format_underline.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_format_underline.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_format_strikethrough.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xhdpi/ic_format_strikethrough.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_format_strikethrough.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxhdpi/ic_format_strikethrough.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_format_strikethrough.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mthli/Knife/HEAD/app/src/main/res/drawable-xxxhdpi/ic_format_strikethrough.png
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | #FF90CAF9
6 | #FF2196F3
7 | #FF1976D2
8 |
9 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Oct 21 11:34:03 PDT 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 2dp
6 | 8dp
7 | 8dp
8 | 2dp
9 |
10 |
--------------------------------------------------------------------------------
/knife/src/androidTest/java/io/github/mthli/knife/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package io.github.mthli.knife;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 |
15 | # Gradle files
16 | .gradle/
17 | build/
18 | /*/build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Other
30 | .idea/
31 | *.iml
32 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/io/github/mthli/knifedemo/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package io.github.mthli.knifedemo;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "io.github.mthli.knifedemo"
9 | minSdkVersion 14
10 | targetSdkVersion 23
11 | versionCode 2
12 | versionName "1.1"
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | compile fileTree(include: ['*.jar'], dir: 'libs')
25 | compile project(':knife')
26 | }
27 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/matthew/Android/Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/knife/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/matthew/Android/Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
6 |
7 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/dialog_link.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/knife/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
18 |
19 | Knife
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
12 |
13 |
18 |
19 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/knife/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
19 |
20 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | KnifeDemo
5 | https://github.com/mthli/Knife
6 |
7 |
8 | Undo
9 | Redo
10 | GitHub
11 |
12 |
13 | Insert link
14 | http(s)://
15 | OK
16 | Cancel
17 |
18 |
19 | Bold
20 | Italic
21 | Underline
22 | Strikethrough
23 | Bullet
24 | Quote
25 | Insert link
26 | Format clear
27 |
28 |
29 |
--------------------------------------------------------------------------------
/knife/src/main/java/io/github/mthli/knife/KnifePart.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Matthew Lee
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.mthli.knife;
18 |
19 | public class KnifePart {
20 | private int start;
21 | private int end;
22 |
23 | public KnifePart(int start, int end) {
24 | this.start = start;
25 | this.end = end;
26 | }
27 |
28 | public int getStart() {
29 | return start;
30 | }
31 |
32 | public int getEnd() {
33 | return end;
34 | }
35 |
36 | public boolean isValid() {
37 | return start < end;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/knife/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Matthew Lee
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | apply plugin: 'com.android.library'
16 |
17 | android {
18 | compileSdkVersion 23
19 | buildToolsVersion "23.0.2"
20 |
21 | defaultConfig {
22 | minSdkVersion 14
23 | targetSdkVersion 23
24 | versionCode 2
25 | versionName "1.1"
26 | }
27 |
28 | buildTypes {
29 | release {
30 | minifyEnabled false
31 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
32 | }
33 | }
34 | }
35 |
36 | dependencies {
37 | compile fileTree(dir: 'libs', include: ['*.jar'])
38 | }
39 |
--------------------------------------------------------------------------------
/knife/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/knife/src/main/java/io/github/mthli/knife/KnifeURLSpan.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Matthew Lee
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.mthli.knife;
18 |
19 | import android.os.Parcel;
20 | import android.text.TextPaint;
21 | import android.text.style.URLSpan;
22 |
23 | public class KnifeURLSpan extends URLSpan {
24 | private int linkColor = 0;
25 | private boolean linkUnderline = true;
26 |
27 | public KnifeURLSpan(String url, int linkColor, boolean linkUnderline) {
28 | super(url);
29 | this.linkColor = linkColor;
30 | this.linkUnderline = linkUnderline;
31 | }
32 |
33 | public KnifeURLSpan(Parcel src) {
34 | super(src);
35 | this.linkColor = src.readInt();
36 | this.linkUnderline = src.readInt() != 0;
37 | }
38 |
39 | @Override
40 | public void writeToParcel(Parcel dest, int flags) {
41 | super.writeToParcel(dest, flags);
42 | dest.writeInt(linkColor);
43 | dest.writeInt(linkUnderline ? 1 : 0);
44 | }
45 |
46 | @Override
47 | public void updateDrawState(TextPaint ds) {
48 | ds.setColor(linkColor != 0 ? linkColor : ds.linkColor);
49 | ds.setUnderlineText(linkUnderline);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/knife/src/main/java/io/github/mthli/knife/KnifeQuoteSpan.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Matthew Lee
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.mthli.knife;
18 |
19 | import android.graphics.Canvas;
20 | import android.graphics.Paint;
21 | import android.os.Parcel;
22 | import android.text.Layout;
23 | import android.text.style.QuoteSpan;
24 |
25 | public class KnifeQuoteSpan extends QuoteSpan {
26 | private static final int DEFAULT_STRIPE_WIDTH = 2;
27 | private static final int DEFAULT_GAP_WIDTH = 2;
28 | private static final int DEFAULT_COLOR = 0xff0000ff;
29 |
30 | private int quoteColor;
31 | private int quoteStripeWidth;
32 | private int quoteGapWidth;
33 |
34 | public KnifeQuoteSpan(int quoteColor, int quoteStripeWidth, int quoteGapWidth) {
35 | this.quoteColor = quoteColor != 0 ? quoteColor : DEFAULT_COLOR;
36 | this.quoteStripeWidth = quoteStripeWidth != 0 ? quoteStripeWidth : DEFAULT_STRIPE_WIDTH;
37 | this.quoteGapWidth = quoteGapWidth != 0 ? quoteGapWidth : DEFAULT_GAP_WIDTH;
38 | }
39 |
40 | public KnifeQuoteSpan(Parcel src) {
41 | super(src);
42 | this.quoteColor = src.readInt();
43 | this.quoteStripeWidth = src.readInt();
44 | this.quoteGapWidth = src.readInt();
45 | }
46 |
47 | @Override
48 | public void writeToParcel(Parcel dest, int flags) {
49 | super.writeToParcel(dest, flags);
50 | dest.writeInt(quoteColor);
51 | dest.writeInt(quoteStripeWidth);
52 | dest.writeInt(quoteGapWidth);
53 | }
54 |
55 | @Override
56 | public int getLeadingMargin(boolean first) {
57 | return quoteStripeWidth + quoteGapWidth;
58 | }
59 |
60 | @Override
61 | public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
62 | int top, int baseline, int bottom,
63 | CharSequence text, int start, int end,
64 | boolean first, Layout layout) {
65 | Paint.Style style = p.getStyle();
66 | int color = p.getColor();
67 |
68 | p.setStyle(Paint.Style.FILL);
69 | p.setColor(quoteColor);
70 | c.drawRect(x, top, x + dir * quoteGapWidth, bottom, p);
71 |
72 | p.setStyle(style);
73 | p.setColor(color);
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/knife/src/main/java/io/github/mthli/knife/KnifeBulletSpan.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Matthew Lee
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.mthli.knife;
18 |
19 | import android.graphics.Canvas;
20 | import android.graphics.Paint;
21 | import android.graphics.Path;
22 | import android.os.Parcel;
23 | import android.text.Layout;
24 | import android.text.Spanned;
25 | import android.text.style.BulletSpan;
26 |
27 | public class KnifeBulletSpan extends BulletSpan {
28 | private static final int DEFAULT_COLOR = 0;
29 | private static final int DEFAULT_RADIUS = 3;
30 | private static final int DEFAULT_GAP_WIDTH = 2;
31 | private static Path bulletPath = null;
32 |
33 | private int bulletColor = DEFAULT_COLOR;
34 | private int bulletRadius = DEFAULT_RADIUS;
35 | private int bulletGapWidth = DEFAULT_GAP_WIDTH;
36 |
37 | public KnifeBulletSpan(int bulletColor, int bulletRadius, int bulletGapWidth) {
38 | this.bulletColor = bulletColor != 0 ? bulletColor : DEFAULT_COLOR;
39 | this.bulletRadius = bulletRadius != 0 ? bulletRadius : DEFAULT_RADIUS;
40 | this.bulletGapWidth = bulletGapWidth != 0 ? bulletGapWidth : DEFAULT_GAP_WIDTH;
41 | }
42 |
43 | public KnifeBulletSpan(Parcel src) {
44 | super(src);
45 | this.bulletColor = src.readInt();
46 | this.bulletRadius = src.readInt();
47 | this.bulletGapWidth = src.readInt();
48 | }
49 |
50 | @Override
51 | public void writeToParcel(Parcel dest, int flags) {
52 | super.writeToParcel(dest, flags);
53 | dest.writeInt(bulletColor);
54 | dest.writeInt(bulletRadius);
55 | dest.writeInt(bulletGapWidth);
56 | }
57 |
58 | @Override
59 | public int getLeadingMargin(boolean first) {
60 | return 2 * bulletRadius + bulletGapWidth;
61 | }
62 |
63 | @Override
64 | public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
65 | int top, int baseline, int bottom,
66 | CharSequence text, int start, int end,
67 | boolean first, Layout l) {
68 | if (((Spanned) text).getSpanStart(this) == start) {
69 | Paint.Style style = p.getStyle();
70 |
71 | int oldColor = p.getColor();
72 | p.setColor(bulletColor);
73 | p.setStyle(Paint.Style.FILL);
74 |
75 | if (c.isHardwareAccelerated()) {
76 | if (bulletPath == null) {
77 | bulletPath = new Path();
78 | // Bullet is slightly better to avoid aliasing artifacts on mdpi devices.
79 | bulletPath.addCircle(0.0f, 0.0f, bulletRadius, Path.Direction.CW);
80 | }
81 |
82 | c.save();
83 | c.translate(x + dir * bulletRadius, (top + bottom) / 2.0f);
84 | c.drawPath(bulletPath, p);
85 | c.restore();
86 | } else {
87 | c.drawCircle(x + dir * bulletRadius, (top + bottom) / 2.0f, bulletRadius, p);
88 | }
89 |
90 | p.setColor(oldColor);
91 | p.setStyle(style);
92 | }
93 | }
94 | }
--------------------------------------------------------------------------------
/knife/src/main/java/io/github/mthli/knife/KnifeTagHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Matthew Lee
3 | * Copyright (C) 2013-2015 Dominik Schürmann
4 | * Copyright (C) 2013-2015 Juha Kuitunen
5 | * Copyright (C) 2013 Mohammed Lakkadshaw
6 | * Copyright (C) 2007 The Android Open Source Project
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | */
20 |
21 | package io.github.mthli.knife;
22 |
23 | import android.text.Editable;
24 | import android.text.Html;
25 | import android.text.Spannable;
26 | import android.text.Spanned;
27 | import android.text.style.BulletSpan;
28 | import android.text.style.StrikethroughSpan;
29 |
30 | import org.xml.sax.XMLReader;
31 |
32 | public class KnifeTagHandler implements Html.TagHandler {
33 | private static final String BULLET_LI = "li";
34 | private static final String STRIKETHROUGH_S = "s";
35 | private static final String STRIKETHROUGH_STRIKE = "strike";
36 | private static final String STRIKETHROUGH_DEL = "del";
37 |
38 | private static class Li {}
39 | private static class Strike {}
40 |
41 | @Override
42 | public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
43 | if (opening) {
44 | if (tag.equalsIgnoreCase(BULLET_LI)) {
45 | if (output.length() > 0 && output.charAt(output.length() - 1) != '\n') {
46 | output.append("\n");
47 | }
48 | start(output, new Li());
49 | } else if (tag.equalsIgnoreCase(STRIKETHROUGH_S) || tag.equalsIgnoreCase(STRIKETHROUGH_STRIKE) || tag.equalsIgnoreCase(STRIKETHROUGH_DEL)) {
50 | start(output, new Strike());
51 | }
52 | } else {
53 | if (tag.equalsIgnoreCase(BULLET_LI)) {
54 | if (output.length() > 0 && output.charAt(output.length() - 1) != '\n') {
55 | output.append("\n");
56 | }
57 | end(output, Li.class, new BulletSpan());
58 | } else if (tag.equalsIgnoreCase(STRIKETHROUGH_S) || tag.equalsIgnoreCase(STRIKETHROUGH_STRIKE) || tag.equalsIgnoreCase(STRIKETHROUGH_DEL)) {
59 | end(output, Strike.class, new StrikethroughSpan());
60 | }
61 | }
62 | }
63 |
64 | private void start(Editable output, Object mark) {
65 | output.setSpan(mark, output.length(), output.length(), Spanned.SPAN_MARK_MARK);
66 | }
67 |
68 | private void end(Editable output, Class kind, Object... replaces) {
69 | Object last = getLast(output, kind);
70 | int start = output.getSpanStart(last);
71 | int end = output.length();
72 | output.removeSpan(last);
73 |
74 | if (start != end) {
75 | for (Object replace : replaces) {
76 | output.setSpan(replace, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
77 | }
78 | }
79 | }
80 |
81 | private static Object getLast(Editable text, Class kind) {
82 | Object[] spans = text.getSpans(0, text.length(), kind);
83 |
84 | if (spans.length == 0) {
85 | return null;
86 | } else {
87 | for (int i = spans.length; i > 0; i--) {
88 | if (text.getSpanFlags(spans[i - 1]) == Spannable.SPAN_MARK_MARK) {
89 | return spans[i - 1];
90 | }
91 | }
92 |
93 | return null;
94 | }
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Knife
2 | ===
3 |
4 | [](http://android-arsenal.com/details/1/2924)
5 |
6 | Knife (extend EditText) is a rich text editor component for writing documents in Android.
7 |
8 | Just select text and use one line code to style it!
9 |
10 | Support Android 4.0+
11 |
12 | ## Example
13 |
14 | 
15 |
16 | Here has a [demo apk](https://github.com/mthli/Knife/releases/download/v1.1/KnifeDemo.1.1.apk "KnifeDemo.1.1.apk"), and it's [source code](https://github.com/mthli/Knife/tree/master/app "KnifeDemo.1.1.apk's source code"), very easy to understand~
17 |
18 | More experiments see [mthli/Type](https://github.com/mthli/Type "mthli/Type").
19 |
20 | ## Api
21 |
22 | - `bold(boolean valid)` __bold__ the selected text.
23 |
24 | - `italic(boolean valid)` _italic_ the selected text.
25 |
26 | - `underline(boolean valid)` \underline\ the selected text.
27 |
28 | - `strikethrough(boolean valid)` strikethrough the selected text.
29 |
30 | - `bullet(boolean valid)` bullet the selected text.
31 |
32 | - `quote(boolean valid)` quote the selected text.
33 |
34 | - `link(String link)` and `link(String link, int start, int end)` to link the text.
35 |
36 | - `contains(int FORMAT)` return `true` if the selected text contains the FORMAT.
37 |
38 | - `clearFormats()` clear all formats.
39 |
40 | - `redo()` when text changed, you can redo it!
41 |
42 | - `undo()` when text change, you can also undo it!
43 |
44 | - `fromHtml()` import from HTML file.
45 |
46 | - `toHtml()` export as HTML file.
47 |
48 | If you want to get more control of the editable text, just extend KnifeText to get all protected method.
49 |
50 | #### Custom
51 |
52 | - `app:bulletColor`
53 |
54 | - `app:bulletRadius`
55 |
56 | - `app:bulletGapWidth`
57 |
58 | - `app:historyEnable` `true` to enable record history, so you can `redo()` and `undo()`.
59 |
60 | - `app:historySize` the record max limit.
61 |
62 | - `app:linkColor`
63 |
64 | - `app:linkUnderline` `true` to enable link underline.
65 |
66 | - `app:quoteColor`
67 |
68 | - `app:quoteStripeWidth` the quote line width.
69 |
70 | - `app:quoteCapWidth`
71 |
72 | #### TODO
73 |
74 | - Insert image.
75 |
76 | ## Gradle
77 |
78 | At your top-level `build.gradle` file:
79 |
80 | repositories {
81 | // ...
82 | maven { url 'https://jitpack.io' }
83 | }
84 |
85 | And then at your project `build.gradle` file:
86 |
87 | dependencies {
88 | compile 'com.github.mthli:Knife:v1.1'
89 | }
90 |
91 | Done!
92 |
93 | ## Reference
94 |
95 | - [Spans, a Powerful Concept.](http://flavienlaurent.com/blog/2014/01/31/spans/ "Spans, a Powerful Concept.")
96 |
97 | - [Spanned | Android Developers](http://developer.android.com/reference/android/text/Spanned.html "Spanned | Android Developers")
98 |
99 | - [core/java/android/text/Html.java - Google Git](https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/Html.java "core/java/android/text/Html.java - Google Git")
100 |
101 | ## Thanks
102 |
103 | - [Squire](https://github.com/neilj/Squire "Squire")
104 |
105 | - [html-textview](https://github.com/SufficientlySecure/html-textview "html-textview")
106 |
107 | ## License
108 |
109 | Copyright 2015 Matthew Lee
110 |
111 | Licensed under the Apache License, Version 2.0 (the "License");
112 | you may not use this file except in compliance with the License.
113 | You may obtain a copy of the License at
114 |
115 | http://www.apache.org/licenses/LICENSE-2.0
116 |
117 | Unless required by applicable law or agreed to in writing, software
118 | distributed under the License is distributed on an "AS IS" BASIS,
119 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
120 | See the License for the specific language governing permissions and
121 | limitations under the License.
122 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
13 |
14 |
17 |
18 |
25 |
26 |
27 |
34 |
35 |
36 |
43 |
44 |
45 |
52 |
53 |
54 |
61 |
62 |
63 |
70 |
71 |
72 |
79 |
80 |
81 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
118 |
119 |
120 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/mthli/knifedemo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package io.github.mthli.knifedemo;
2 |
3 | import android.app.Activity;
4 | import android.app.AlertDialog;
5 | import android.content.DialogInterface;
6 | import android.content.Intent;
7 | import android.net.Uri;
8 | import android.os.Bundle;
9 | import android.text.TextUtils;
10 | import android.view.Menu;
11 | import android.view.MenuItem;
12 | import android.view.View;
13 | import android.widget.EditText;
14 | import android.widget.ImageButton;
15 | import android.widget.Toast;
16 |
17 | import io.github.mthli.knife.KnifeText;
18 |
19 | public class MainActivity extends Activity {
20 | private static final String BOLD = "Bold
";
21 | private static final String ITALIT = "Italic
";
22 | private static final String UNDERLINE = "Underline
";
23 | private static final String STRIKETHROUGH = "Strikethrough
"; // or or
24 | private static final String BULLET = "";
25 | private static final String QUOTE = "Quote
";
26 | private static final String LINK = "Link
";
27 | private static final String EXAMPLE = BOLD + ITALIT + UNDERLINE + STRIKETHROUGH + BULLET + QUOTE + LINK;
28 |
29 | private KnifeText knife;
30 |
31 | @Override
32 | protected void onCreate(Bundle savedInstanceState) {
33 | super.onCreate(savedInstanceState);
34 | setContentView(R.layout.activity_main);
35 |
36 | knife = (KnifeText) findViewById(R.id.knife);
37 | // ImageGetter coming soon...
38 | knife.fromHtml(EXAMPLE);
39 | knife.setSelection(knife.getEditableText().length());
40 |
41 | setupBold();
42 | setupItalic();
43 | setupUnderline();
44 | setupStrikethrough();
45 | setupBullet();
46 | setupQuote();
47 | setupLink();
48 | setupClear();
49 | }
50 |
51 | private void setupBold() {
52 | ImageButton bold = (ImageButton) findViewById(R.id.bold);
53 |
54 | bold.setOnClickListener(new View.OnClickListener() {
55 | @Override
56 | public void onClick(View v) {
57 | knife.bold(!knife.contains(KnifeText.FORMAT_BOLD));
58 | }
59 | });
60 |
61 | bold.setOnLongClickListener(new View.OnLongClickListener() {
62 | @Override
63 | public boolean onLongClick(View v) {
64 | Toast.makeText(MainActivity.this, R.string.toast_bold, Toast.LENGTH_SHORT).show();
65 | return true;
66 | }
67 | });
68 | }
69 |
70 | private void setupItalic() {
71 | ImageButton italic = (ImageButton) findViewById(R.id.italic);
72 |
73 | italic.setOnClickListener(new View.OnClickListener() {
74 | @Override
75 | public void onClick(View v) {
76 | knife.italic(!knife.contains(KnifeText.FORMAT_ITALIC));
77 | }
78 | });
79 |
80 | italic.setOnLongClickListener(new View.OnLongClickListener() {
81 | @Override
82 | public boolean onLongClick(View v) {
83 | Toast.makeText(MainActivity.this, R.string.toast_italic, Toast.LENGTH_SHORT).show();
84 | return true;
85 | }
86 | });
87 | }
88 |
89 | private void setupUnderline() {
90 | ImageButton underline = (ImageButton) findViewById(R.id.underline);
91 |
92 | underline.setOnClickListener(new View.OnClickListener() {
93 | @Override
94 | public void onClick(View v) {
95 | knife.underline(!knife.contains(KnifeText.FORMAT_UNDERLINED));
96 | }
97 | });
98 |
99 | underline.setOnLongClickListener(new View.OnLongClickListener() {
100 | @Override
101 | public boolean onLongClick(View v) {
102 | Toast.makeText(MainActivity.this, R.string.toast_underline, Toast.LENGTH_SHORT).show();
103 | return true;
104 | }
105 | });
106 | }
107 |
108 | private void setupStrikethrough() {
109 | ImageButton strikethrough = (ImageButton) findViewById(R.id.strikethrough);
110 |
111 | strikethrough.setOnClickListener(new View.OnClickListener() {
112 | @Override
113 | public void onClick(View v) {
114 | knife.strikethrough(!knife.contains(KnifeText.FORMAT_STRIKETHROUGH));
115 | }
116 | });
117 |
118 | strikethrough.setOnLongClickListener(new View.OnLongClickListener() {
119 | @Override
120 | public boolean onLongClick(View v) {
121 | Toast.makeText(MainActivity.this, R.string.toast_strikethrough, Toast.LENGTH_SHORT).show();
122 | return true;
123 | }
124 | });
125 | }
126 |
127 | private void setupBullet() {
128 | ImageButton bullet = (ImageButton) findViewById(R.id.bullet);
129 |
130 | bullet.setOnClickListener(new View.OnClickListener() {
131 | @Override
132 | public void onClick(View v) {
133 | knife.bullet(!knife.contains(KnifeText.FORMAT_BULLET));
134 | }
135 | });
136 |
137 |
138 | bullet.setOnLongClickListener(new View.OnLongClickListener() {
139 | @Override
140 | public boolean onLongClick(View v) {
141 | Toast.makeText(MainActivity.this, R.string.toast_bullet, Toast.LENGTH_SHORT).show();
142 | return true;
143 | }
144 | });
145 | }
146 |
147 | private void setupQuote() {
148 | ImageButton quote = (ImageButton) findViewById(R.id.quote);
149 |
150 | quote.setOnClickListener(new View.OnClickListener() {
151 | @Override
152 | public void onClick(View v) {
153 | knife.quote(!knife.contains(KnifeText.FORMAT_QUOTE));
154 | }
155 | });
156 |
157 | quote.setOnLongClickListener(new View.OnLongClickListener() {
158 | @Override
159 | public boolean onLongClick(View v) {
160 | Toast.makeText(MainActivity.this, R.string.toast_quote, Toast.LENGTH_SHORT).show();
161 | return true;
162 | }
163 | });
164 | }
165 |
166 | private void setupLink() {
167 | ImageButton link = (ImageButton) findViewById(R.id.link);
168 |
169 | link.setOnClickListener(new View.OnClickListener() {
170 | @Override
171 | public void onClick(View v) {
172 | showLinkDialog();
173 | }
174 | });
175 |
176 | link.setOnLongClickListener(new View.OnLongClickListener() {
177 | @Override
178 | public boolean onLongClick(View v) {
179 | Toast.makeText(MainActivity.this, R.string.toast_insert_link, Toast.LENGTH_SHORT).show();
180 | return true;
181 | }
182 | });
183 | }
184 |
185 | private void setupClear() {
186 | ImageButton clear = (ImageButton) findViewById(R.id.clear);
187 |
188 | clear.setOnClickListener(new View.OnClickListener() {
189 | @Override
190 | public void onClick(View v) {
191 | knife.clearFormats();
192 | }
193 | });
194 |
195 | clear.setOnLongClickListener(new View.OnLongClickListener() {
196 | @Override
197 | public boolean onLongClick(View v) {
198 | Toast.makeText(MainActivity.this, R.string.toast_format_clear, Toast.LENGTH_SHORT).show();
199 | return true;
200 | }
201 | });
202 | }
203 |
204 | private void showLinkDialog() {
205 | final int start = knife.getSelectionStart();
206 | final int end = knife.getSelectionEnd();
207 |
208 | AlertDialog.Builder builder = new AlertDialog.Builder(this);
209 | builder.setCancelable(false);
210 |
211 | View view = getLayoutInflater().inflate(R.layout.dialog_link, null, false);
212 | final EditText editText = (EditText) view.findViewById(R.id.edit);
213 | builder.setView(view);
214 | builder.setTitle(R.string.dialog_title);
215 |
216 | builder.setPositiveButton(R.string.dialog_button_ok, new DialogInterface.OnClickListener() {
217 | @Override
218 | public void onClick(DialogInterface dialog, int which) {
219 | String link = editText.getText().toString().trim();
220 | if (TextUtils.isEmpty(link)) {
221 | return;
222 | }
223 |
224 | // When KnifeText lose focus, use this method
225 | knife.link(link, start, end);
226 | }
227 | });
228 |
229 | builder.setNegativeButton(R.string.dialog_button_cancel, new DialogInterface.OnClickListener() {
230 | @Override
231 | public void onClick(DialogInterface dialog, int which) {
232 | // DO NOTHING HERE
233 | }
234 | });
235 |
236 | builder.create().show();
237 | }
238 |
239 | @Override
240 | public boolean onCreateOptionsMenu(Menu menu) {
241 | getMenuInflater().inflate(R.menu.menu_main, menu);
242 | return super.onCreateOptionsMenu(menu);
243 | }
244 |
245 | @Override
246 | public boolean onOptionsItemSelected(MenuItem item) {
247 | switch (item.getItemId()) {
248 | case R.id.undo:
249 | knife.undo();
250 | break;
251 | case R.id.redo:
252 | knife.redo();
253 | break;
254 | case R.id.github:
255 | Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.app_repo)));
256 | startActivity(intent);
257 | break;
258 | default:
259 | break;
260 | }
261 |
262 | return true;
263 | }
264 | }
265 |
--------------------------------------------------------------------------------
/knife/src/main/java/io/github/mthli/knife/KnifeParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Matthew Lee
3 | * Copyright (C) 2007 The Android Open Source Project
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.github.mthli.knife;
19 |
20 | import android.graphics.Typeface;
21 | import android.text.Html;
22 | import android.text.Spanned;
23 | import android.text.TextUtils;
24 | import android.text.style.BulletSpan;
25 | import android.text.style.CharacterStyle;
26 | import android.text.style.ImageSpan;
27 | import android.text.style.ParagraphStyle;
28 | import android.text.style.QuoteSpan;
29 | import android.text.style.StrikethroughSpan;
30 | import android.text.style.StyleSpan;
31 | import android.text.style.URLSpan;
32 | import android.text.style.UnderlineSpan;
33 |
34 | public class KnifeParser {
35 | public static Spanned fromHtml(String source) {
36 | return Html.fromHtml(source, null, new KnifeTagHandler());
37 | }
38 |
39 | public static String toHtml(Spanned text) {
40 | StringBuilder out = new StringBuilder();
41 | withinHtml(out, text);
42 | return tidy(out.toString());
43 | }
44 |
45 | private static void withinHtml(StringBuilder out, Spanned text) {
46 | int next;
47 |
48 | for (int i = 0; i < text.length(); i = next) {
49 | next = text.nextSpanTransition(i, text.length(), ParagraphStyle.class);
50 |
51 | ParagraphStyle[] styles = text.getSpans(i, next, ParagraphStyle.class);
52 | if (styles.length == 2) {
53 | if (styles[0] instanceof BulletSpan && styles[1] instanceof QuoteSpan) {
54 | // Let a
follow the BulletSpan or QuoteSpan end, so next++
55 | withinBulletThenQuote(out, text, i, next++);
56 | } else if (styles[0] instanceof QuoteSpan && styles[1] instanceof BulletSpan) {
57 | withinQuoteThenBullet(out, text, i, next++);
58 | } else {
59 | withinContent(out, text, i, next);
60 | }
61 | } else if (styles.length == 1) {
62 | if (styles[0] instanceof BulletSpan) {
63 | withinBullet(out, text, i, next++);
64 | } else if (styles[0] instanceof QuoteSpan) {
65 | withinQuote(out, text, i, next++);
66 | } else {
67 | withinContent(out, text, i, next);
68 | }
69 | } else {
70 | withinContent(out, text, i, next);
71 | }
72 | }
73 | }
74 |
75 | private static void withinBulletThenQuote(StringBuilder out, Spanned text, int start, int end) {
76 | out.append("- ");
77 | withinQuote(out, text, start, end);
78 | out.append("
");
79 | }
80 |
81 | private static void withinQuoteThenBullet(StringBuilder out, Spanned text, int start, int end) {
82 | out.append("");
83 | withinBullet(out, text, start, end);
84 | out.append("
");
85 | }
86 |
87 | private static void withinBullet(StringBuilder out, Spanned text, int start, int end) {
88 | out.append("");
89 |
90 | int next;
91 |
92 | for (int i = start; i < end; i = next) {
93 | next = text.nextSpanTransition(i, end, BulletSpan.class);
94 |
95 | BulletSpan[] spans = text.getSpans(i, next, BulletSpan.class);
96 | for (BulletSpan span : spans) {
97 | out.append("- ");
98 | }
99 |
100 | withinContent(out, text, i, next);
101 | for (BulletSpan span : spans) {
102 | out.append("
");
103 | }
104 | }
105 |
106 | out.append("
");
107 | }
108 |
109 | private static void withinQuote(StringBuilder out, Spanned text, int start, int end) {
110 | int next;
111 |
112 | for (int i = start; i < end; i = next) {
113 | next = text.nextSpanTransition(i, end, QuoteSpan.class);
114 |
115 | QuoteSpan[] quotes = text.getSpans(i, next, QuoteSpan.class);
116 | for (QuoteSpan quote : quotes) {
117 | out.append("");
118 | }
119 |
120 | withinContent(out, text, i, next);
121 | for (QuoteSpan quote : quotes) {
122 | out.append("
");
123 | }
124 | }
125 | }
126 |
127 | private static void withinContent(StringBuilder out, Spanned text, int start, int end) {
128 | int next;
129 |
130 | for (int i = start; i < end; i = next) {
131 | next = TextUtils.indexOf(text, '\n', i, end);
132 | if (next < 0) {
133 | next = end;
134 | }
135 |
136 | int nl = 0;
137 | while (next < end && text.charAt(next) == '\n') {
138 | next++;
139 | nl++;
140 | }
141 |
142 | withinParagraph(out, text, i, next - nl, nl);
143 | }
144 | }
145 |
146 | // Copy from https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/Html.java,
147 | // remove some tag because we don't need them in Knife.
148 | private static void withinParagraph(StringBuilder out, Spanned text, int start, int end, int nl) {
149 | int next;
150 |
151 | for (int i = start; i < end; i = next) {
152 | next = text.nextSpanTransition(i, end, CharacterStyle.class);
153 |
154 | CharacterStyle[] spans = text.getSpans(i, next, CharacterStyle.class);
155 | for (int j = 0; j < spans.length; j++) {
156 | if (spans[j] instanceof StyleSpan) {
157 | int style = ((StyleSpan) spans[j]).getStyle();
158 |
159 | if ((style & Typeface.BOLD) != 0) {
160 | out.append("");
161 | }
162 |
163 | if ((style & Typeface.ITALIC) != 0) {
164 | out.append("");
165 | }
166 | }
167 |
168 | if (spans[j] instanceof UnderlineSpan) {
169 | out.append("");
170 | }
171 |
172 | // Use standard strikethrough tag rather than or
173 | if (spans[j] instanceof StrikethroughSpan) {
174 | out.append("");
175 | }
176 |
177 | if (spans[j] instanceof URLSpan) {
178 | out.append("");
181 | }
182 |
183 | if (spans[j] instanceof ImageSpan) {
184 | out.append("
");
187 |
188 | // Don't output the dummy character underlying the image.
189 | i = next;
190 | }
191 | }
192 |
193 | withinStyle(out, text, i, next);
194 | for (int j = spans.length - 1; j >= 0; j--) {
195 | if (spans[j] instanceof URLSpan) {
196 | out.append("");
197 | }
198 |
199 | if (spans[j] instanceof StrikethroughSpan) {
200 | out.append("");
201 | }
202 |
203 | if (spans[j] instanceof UnderlineSpan) {
204 | out.append("");
205 | }
206 |
207 | if (spans[j] instanceof StyleSpan) {
208 | int style = ((StyleSpan) spans[j]).getStyle();
209 |
210 | if ((style & Typeface.BOLD) != 0) {
211 | out.append("");
212 | }
213 |
214 | if ((style & Typeface.ITALIC) != 0) {
215 | out.append("");
216 | }
217 | }
218 | }
219 | }
220 |
221 | for (int i = 0; i < nl; i++) {
222 | out.append("
");
223 | }
224 | }
225 |
226 | private static void withinStyle(StringBuilder out, CharSequence text, int start, int end) {
227 | for (int i = start; i < end; i++) {
228 | char c = text.charAt(i);
229 |
230 | if (c == '<') {
231 | out.append("<");
232 | } else if (c == '>') {
233 | out.append(">");
234 | } else if (c == '&') {
235 | out.append("&");
236 | } else if (c >= 0xD800 && c <= 0xDFFF) {
237 | if (c < 0xDC00 && i + 1 < end) {
238 | char d = text.charAt(i + 1);
239 | if (d >= 0xDC00 && d <= 0xDFFF) {
240 | i++;
241 | int codepoint = 0x010000 | (int) c - 0xD800 << 10 | (int) d - 0xDC00;
242 | out.append("").append(codepoint).append(";");
243 | }
244 | }
245 | } else if (c > 0x7E || c < ' ') {
246 | out.append("").append((int) c).append(";");
247 | } else if (c == ' ') {
248 | while (i + 1 < end && text.charAt(i + 1) == ' ') {
249 | out.append(" ");
250 | i++;
251 | }
252 |
253 | out.append(' ');
254 | } else {
255 | out.append(c);
256 | }
257 | }
258 | }
259 |
260 | private static String tidy(String html) {
261 | return html.replaceAll("(
)?", "").replaceAll("(
)?", "");
262 | }
263 | }
264 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2015 Matthew Lee
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/knife/src/main/java/io/github/mthli/knife/KnifeText.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Matthew Lee
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.mthli.knife;
18 |
19 | import android.content.Context;
20 | import android.content.res.TypedArray;
21 | import android.graphics.Typeface;
22 | import android.text.Editable;
23 | import android.text.SpannableStringBuilder;
24 | import android.text.Spanned;
25 | import android.text.TextUtils;
26 | import android.text.TextWatcher;
27 | import android.text.style.BulletSpan;
28 | import android.text.style.QuoteSpan;
29 | import android.text.style.StrikethroughSpan;
30 | import android.text.style.StyleSpan;
31 | import android.text.style.URLSpan;
32 | import android.text.style.UnderlineSpan;
33 | import android.util.AttributeSet;
34 | import android.view.inputmethod.InputMethodManager;
35 | import android.widget.EditText;
36 |
37 | import java.util.ArrayList;
38 | import java.util.LinkedList;
39 | import java.util.List;
40 |
41 | public class KnifeText extends EditText implements TextWatcher {
42 | public static final int FORMAT_BOLD = 0x01;
43 | public static final int FORMAT_ITALIC = 0x02;
44 | public static final int FORMAT_UNDERLINED = 0x03;
45 | public static final int FORMAT_STRIKETHROUGH = 0x04;
46 | public static final int FORMAT_BULLET = 0x05;
47 | public static final int FORMAT_QUOTE = 0x06;
48 | public static final int FORMAT_LINK = 0x07;
49 |
50 | private int bulletColor = 0;
51 | private int bulletRadius = 0;
52 | private int bulletGapWidth = 0;
53 | private boolean historyEnable = true;
54 | private int historySize = 100;
55 | private int linkColor = 0;
56 | private boolean linkUnderline = true;
57 | private int quoteColor = 0;
58 | private int quoteStripeWidth = 0;
59 | private int quoteGapWidth = 0;
60 |
61 | private List historyList = new LinkedList<>();
62 | private boolean historyWorking = false;
63 | private int historyCursor = 0;
64 |
65 | private SpannableStringBuilder inputBefore;
66 | private Editable inputLast;
67 |
68 | public KnifeText(Context context) {
69 | super(context);
70 | init(null);
71 | }
72 |
73 | public KnifeText(Context context, AttributeSet attrs) {
74 | super(context, attrs);
75 | init(attrs);
76 | }
77 |
78 | public KnifeText(Context context, AttributeSet attrs, int defStyleAttr) {
79 | super(context, attrs, defStyleAttr);
80 | init(attrs);
81 | }
82 |
83 | @SuppressWarnings("NewApi")
84 | public KnifeText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
85 | super(context, attrs, defStyleAttr, defStyleRes);
86 | init(attrs);
87 | }
88 |
89 | private void init(AttributeSet attrs) {
90 | TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.KnifeText);
91 | bulletColor = array.getColor(R.styleable.KnifeText_bulletColor, 0);
92 | bulletRadius = array.getDimensionPixelSize(R.styleable.KnifeText_bulletRadius, 0);
93 | bulletGapWidth = array.getDimensionPixelSize(R.styleable.KnifeText_bulletGapWidth, 0);
94 | historyEnable = array.getBoolean(R.styleable.KnifeText_historyEnable, true);
95 | historySize = array.getInt(R.styleable.KnifeText_historySize, 100);
96 | linkColor = array.getColor(R.styleable.KnifeText_linkColor, 0);
97 | linkUnderline = array.getBoolean(R.styleable.KnifeText_linkUnderline, true);
98 | quoteColor = array.getColor(R.styleable.KnifeText_quoteColor, 0);
99 | quoteStripeWidth = array.getDimensionPixelSize(R.styleable.KnifeText_quoteStripeWidth, 0);
100 | quoteGapWidth = array.getDimensionPixelSize(R.styleable.KnifeText_quoteCapWidth, 0);
101 | array.recycle();
102 |
103 | if (historyEnable && historySize <= 0) {
104 | throw new IllegalArgumentException("historySize must > 0");
105 | }
106 | }
107 |
108 | @Override
109 | protected void onAttachedToWindow() {
110 | super.onAttachedToWindow();
111 |
112 | addTextChangedListener(this);
113 | }
114 |
115 | @Override
116 | protected void onDetachedFromWindow() {
117 | super.onDetachedFromWindow();
118 | removeTextChangedListener(this);
119 | }
120 |
121 | // StyleSpan ===================================================================================
122 |
123 | public void bold(boolean valid) {
124 | if (valid) {
125 | styleValid(Typeface.BOLD, getSelectionStart(), getSelectionEnd());
126 | } else {
127 | styleInvalid(Typeface.BOLD, getSelectionStart(), getSelectionEnd());
128 | }
129 | }
130 |
131 | public void italic(boolean valid) {
132 | if (valid) {
133 | styleValid(Typeface.ITALIC, getSelectionStart(), getSelectionEnd());
134 | } else {
135 | styleInvalid(Typeface.ITALIC, getSelectionStart(), getSelectionEnd());
136 | }
137 | }
138 |
139 | protected void styleValid(int style, int start, int end) {
140 | switch (style) {
141 | case Typeface.NORMAL:
142 | case Typeface.BOLD:
143 | case Typeface.ITALIC:
144 | case Typeface.BOLD_ITALIC:
145 | break;
146 | default:
147 | return;
148 | }
149 |
150 | if (start >= end) {
151 | return;
152 | }
153 |
154 | getEditableText().setSpan(new StyleSpan(style), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
155 | }
156 |
157 | protected void styleInvalid(int style, int start, int end) {
158 | switch (style) {
159 | case Typeface.NORMAL:
160 | case Typeface.BOLD:
161 | case Typeface.ITALIC:
162 | case Typeface.BOLD_ITALIC:
163 | break;
164 | default:
165 | return;
166 | }
167 |
168 | if (start >= end) {
169 | return;
170 | }
171 |
172 | StyleSpan[] spans = getEditableText().getSpans(start, end, StyleSpan.class);
173 | List list = new ArrayList<>();
174 |
175 | for (StyleSpan span : spans) {
176 | if (span.getStyle() == style) {
177 | list.add(new KnifePart(getEditableText().getSpanStart(span), getEditableText().getSpanEnd(span)));
178 | getEditableText().removeSpan(span);
179 | }
180 | }
181 |
182 | for (KnifePart part : list) {
183 | if (part.isValid()) {
184 | if (part.getStart() < start) {
185 | styleValid(style, part.getStart(), start);
186 | }
187 |
188 | if (part.getEnd() > end) {
189 | styleValid(style, end, part.getEnd());
190 | }
191 | }
192 | }
193 | }
194 |
195 | protected boolean containStyle(int style, int start, int end) {
196 | switch (style) {
197 | case Typeface.NORMAL:
198 | case Typeface.BOLD:
199 | case Typeface.ITALIC:
200 | case Typeface.BOLD_ITALIC:
201 | break;
202 | default:
203 | return false;
204 | }
205 |
206 | if (start > end) {
207 | return false;
208 | }
209 |
210 | if (start == end) {
211 | if (start - 1 < 0 || start + 1 > getEditableText().length()) {
212 | return false;
213 | } else {
214 | StyleSpan[] before = getEditableText().getSpans(start - 1, start, StyleSpan.class);
215 | StyleSpan[] after = getEditableText().getSpans(start, start + 1, StyleSpan.class);
216 | return before.length > 0 && after.length > 0 && before[0].getStyle() == style && after[0].getStyle() == style;
217 | }
218 | } else {
219 | StringBuilder builder = new StringBuilder();
220 |
221 | // Make sure no duplicate characters be added
222 | for (int i = start; i < end; i++) {
223 | StyleSpan[] spans = getEditableText().getSpans(i, i + 1, StyleSpan.class);
224 | for (StyleSpan span : spans) {
225 | if (span.getStyle() == style) {
226 | builder.append(getEditableText().subSequence(i, i + 1).toString());
227 | break;
228 | }
229 | }
230 | }
231 |
232 | return getEditableText().subSequence(start, end).toString().equals(builder.toString());
233 | }
234 | }
235 |
236 | // UnderlineSpan ===============================================================================
237 |
238 | public void underline(boolean valid) {
239 | if (valid) {
240 | underlineValid(getSelectionStart(), getSelectionEnd());
241 | } else {
242 | underlineInvalid(getSelectionStart(), getSelectionEnd());
243 | }
244 | }
245 |
246 | protected void underlineValid(int start, int end) {
247 | if (start >= end) {
248 | return;
249 | }
250 |
251 | getEditableText().setSpan(new UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
252 | }
253 |
254 | protected void underlineInvalid(int start, int end) {
255 | if (start >= end) {
256 | return;
257 | }
258 |
259 | UnderlineSpan[] spans = getEditableText().getSpans(start, end, UnderlineSpan.class);
260 | List list = new ArrayList<>();
261 |
262 | for (UnderlineSpan span : spans) {
263 | list.add(new KnifePart(getEditableText().getSpanStart(span), getEditableText().getSpanEnd(span)));
264 | getEditableText().removeSpan(span);
265 | }
266 |
267 | for (KnifePart part : list) {
268 | if (part.isValid()) {
269 | if (part.getStart() < start) {
270 | underlineValid(part.getStart(), start);
271 | }
272 |
273 | if (part.getEnd() > end) {
274 | underlineValid(end, part.getEnd());
275 | }
276 | }
277 | }
278 | }
279 |
280 | protected boolean containUnderline(int start, int end) {
281 | if (start > end) {
282 | return false;
283 | }
284 |
285 | if (start == end) {
286 | if (start - 1 < 0 || start + 1 > getEditableText().length()) {
287 | return false;
288 | } else {
289 | UnderlineSpan[] before = getEditableText().getSpans(start - 1, start, UnderlineSpan.class);
290 | UnderlineSpan[] after = getEditableText().getSpans(start, start + 1, UnderlineSpan.class);
291 | return before.length > 0 && after.length > 0;
292 | }
293 | } else {
294 | StringBuilder builder = new StringBuilder();
295 |
296 | for (int i = start; i < end; i++) {
297 | if (getEditableText().getSpans(i, i + 1, UnderlineSpan.class).length > 0) {
298 | builder.append(getEditableText().subSequence(i, i + 1).toString());
299 | }
300 | }
301 |
302 | return getEditableText().subSequence(start, end).toString().equals(builder.toString());
303 | }
304 | }
305 |
306 | // StrikethroughSpan ===========================================================================
307 |
308 | public void strikethrough(boolean valid) {
309 | if (valid) {
310 | strikethroughValid(getSelectionStart(), getSelectionEnd());
311 | } else {
312 | strikethroughInvalid(getSelectionStart(), getSelectionEnd());
313 | }
314 | }
315 |
316 | protected void strikethroughValid(int start, int end) {
317 | if (start >= end) {
318 | return;
319 | }
320 |
321 | getEditableText().setSpan(new StrikethroughSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
322 | }
323 |
324 | protected void strikethroughInvalid(int start, int end) {
325 | if (start >= end) {
326 | return;
327 | }
328 |
329 | StrikethroughSpan[] spans = getEditableText().getSpans(start, end, StrikethroughSpan.class);
330 | List list = new ArrayList<>();
331 |
332 | for (StrikethroughSpan span : spans) {
333 | list.add(new KnifePart(getEditableText().getSpanStart(span), getEditableText().getSpanEnd(span)));
334 | getEditableText().removeSpan(span);
335 | }
336 |
337 | for (KnifePart part : list) {
338 | if (part.isValid()) {
339 | if (part.getStart() < start) {
340 | strikethroughValid(part.getStart(), start);
341 | }
342 |
343 | if (part.getEnd() > end) {
344 | strikethroughValid(end, part.getEnd());
345 | }
346 | }
347 | }
348 | }
349 |
350 | protected boolean containStrikethrough(int start, int end) {
351 | if (start > end) {
352 | return false;
353 | }
354 |
355 | if (start == end) {
356 | if (start - 1 < 0 || start + 1 > getEditableText().length()) {
357 | return false;
358 | } else {
359 | StrikethroughSpan[] before = getEditableText().getSpans(start - 1, start, StrikethroughSpan.class);
360 | StrikethroughSpan[] after = getEditableText().getSpans(start, start + 1, StrikethroughSpan.class);
361 | return before.length > 0 && after.length > 0;
362 | }
363 | } else {
364 | StringBuilder builder = new StringBuilder();
365 |
366 | for (int i = start; i < end; i++) {
367 | if (getEditableText().getSpans(i, i + 1, StrikethroughSpan.class).length > 0) {
368 | builder.append(getEditableText().subSequence(i, i + 1).toString());
369 | }
370 | }
371 |
372 | return getEditableText().subSequence(start, end).toString().equals(builder.toString());
373 | }
374 | }
375 |
376 | // BulletSpan ==================================================================================
377 |
378 | public void bullet(boolean valid) {
379 | if (valid) {
380 | bulletValid();
381 | } else {
382 | bulletInvalid();
383 | }
384 | }
385 |
386 | protected void bulletValid() {
387 | String[] lines = TextUtils.split(getEditableText().toString(), "\n");
388 |
389 | for (int i = 0; i < lines.length; i++) {
390 | if (containBullet(i)) {
391 | continue;
392 | }
393 |
394 | int lineStart = 0;
395 | for (int j = 0; j < i; j++) {
396 | lineStart = lineStart + lines[j].length() + 1; // \n
397 | }
398 |
399 | int lineEnd = lineStart + lines[i].length();
400 | if (lineStart >= lineEnd) {
401 | continue;
402 | }
403 |
404 | // Find selection area inside
405 | int bulletStart = 0;
406 | int bulletEnd = 0;
407 | if (lineStart <= getSelectionStart() && getSelectionEnd() <= lineEnd) {
408 | bulletStart = lineStart;
409 | bulletEnd = lineEnd;
410 | } else if (getSelectionStart() <= lineStart && lineEnd <= getSelectionEnd()) {
411 | bulletStart = lineStart;
412 | bulletEnd = lineEnd;
413 | }
414 |
415 | if (bulletStart < bulletEnd) {
416 | getEditableText().setSpan(new KnifeBulletSpan(bulletColor, bulletRadius, bulletGapWidth), bulletStart, bulletEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
417 | }
418 | }
419 | }
420 |
421 | protected void bulletInvalid() {
422 | String[] lines = TextUtils.split(getEditableText().toString(), "\n");
423 |
424 | for (int i = 0; i < lines.length; i++) {
425 | if (!containBullet(i)) {
426 | continue;
427 | }
428 |
429 | int lineStart = 0;
430 | for (int j = 0; j < i; j++) {
431 | lineStart = lineStart + lines[j].length() + 1;
432 | }
433 |
434 | int lineEnd = lineStart + lines[i].length();
435 | if (lineStart >= lineEnd) {
436 | continue;
437 | }
438 |
439 | int bulletStart = 0;
440 | int bulletEnd = 0;
441 | if (lineStart <= getSelectionStart() && getSelectionEnd() <= lineEnd) {
442 | bulletStart = lineStart;
443 | bulletEnd = lineEnd;
444 | } else if (getSelectionStart() <= lineStart && lineEnd <= getSelectionEnd()) {
445 | bulletStart = lineStart;
446 | bulletEnd = lineEnd;
447 | }
448 |
449 | if (bulletStart < bulletEnd) {
450 | BulletSpan[] spans = getEditableText().getSpans(bulletStart, bulletEnd, BulletSpan.class);
451 | for (BulletSpan span : spans) {
452 | getEditableText().removeSpan(span);
453 | }
454 | }
455 | }
456 | }
457 |
458 | protected boolean containBullet() {
459 | String[] lines = TextUtils.split(getEditableText().toString(), "\n");
460 | List list = new ArrayList<>();
461 |
462 | for (int i = 0; i < lines.length; i++) {
463 | int lineStart = 0;
464 | for (int j = 0; j < i; j++) {
465 | lineStart = lineStart + lines[j].length() + 1;
466 | }
467 |
468 | int lineEnd = lineStart + lines[i].length();
469 | if (lineStart >= lineEnd) {
470 | continue;
471 | }
472 |
473 | if (lineStart <= getSelectionStart() && getSelectionEnd() <= lineEnd) {
474 | list.add(i);
475 | } else if (getSelectionStart() <= lineStart && lineEnd <= getSelectionEnd()) {
476 | list.add(i);
477 | }
478 | }
479 |
480 | for (Integer i : list) {
481 | if (!containBullet(i)) {
482 | return false;
483 | }
484 | }
485 |
486 | return true;
487 | }
488 |
489 | protected boolean containBullet(int index) {
490 | String[] lines = TextUtils.split(getEditableText().toString(), "\n");
491 | if (index < 0 || index >= lines.length) {
492 | return false;
493 | }
494 |
495 | int start = 0;
496 | for (int i = 0; i < index; i++) {
497 | start = start + lines[i].length() + 1;
498 | }
499 |
500 | int end = start + lines[index].length();
501 | if (start >= end) {
502 | return false;
503 | }
504 |
505 | BulletSpan[] spans = getEditableText().getSpans(start, end, BulletSpan.class);
506 | return spans.length > 0;
507 | }
508 |
509 | // QuoteSpan ===================================================================================
510 |
511 | public void quote(boolean valid) {
512 | if (valid) {
513 | quoteValid();
514 | } else {
515 | quoteInvalid();
516 | }
517 | }
518 |
519 | protected void quoteValid() {
520 | String[] lines = TextUtils.split(getEditableText().toString(), "\n");
521 |
522 | for (int i = 0; i < lines.length; i++) {
523 | if (containQuote(i)) {
524 | continue;
525 | }
526 |
527 | int lineStart = 0;
528 | for (int j = 0; j < i; j++) {
529 | lineStart = lineStart + lines[j].length() + 1; // \n
530 | }
531 |
532 | int lineEnd = lineStart + lines[i].length();
533 | if (lineStart >= lineEnd) {
534 | continue;
535 | }
536 |
537 | int quoteStart = 0;
538 | int quoteEnd = 0;
539 | if (lineStart <= getSelectionStart() && getSelectionEnd() <= lineEnd) {
540 | quoteStart = lineStart;
541 | quoteEnd = lineEnd;
542 | } else if (getSelectionStart() <= lineStart && lineEnd <= getSelectionEnd()) {
543 | quoteStart = lineStart;
544 | quoteEnd = lineEnd;
545 | }
546 |
547 | if (quoteStart < quoteEnd) {
548 | getEditableText().setSpan(new KnifeQuoteSpan(quoteColor, quoteStripeWidth, quoteGapWidth), quoteStart, quoteEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
549 | }
550 | }
551 | }
552 |
553 | protected void quoteInvalid() {
554 | String[] lines = TextUtils.split(getEditableText().toString(), "\n");
555 |
556 | for (int i = 0; i < lines.length; i++) {
557 | if (!containQuote(i)) {
558 | continue;
559 | }
560 |
561 | int lineStart = 0;
562 | for (int j = 0; j < i; j++) {
563 | lineStart = lineStart + lines[j].length() + 1;
564 | }
565 |
566 | int lineEnd = lineStart + lines[i].length();
567 | if (lineStart >= lineEnd) {
568 | continue;
569 | }
570 |
571 | int quoteStart = 0;
572 | int quoteEnd = 0;
573 | if (lineStart <= getSelectionStart() && getSelectionEnd() <= lineEnd) {
574 | quoteStart = lineStart;
575 | quoteEnd = lineEnd;
576 | } else if (getSelectionStart() <= lineStart && lineEnd <= getSelectionEnd()) {
577 | quoteStart = lineStart;
578 | quoteEnd = lineEnd;
579 | }
580 |
581 | if (quoteStart < quoteEnd) {
582 | QuoteSpan[] spans = getEditableText().getSpans(quoteStart, quoteEnd, QuoteSpan.class);
583 | for (QuoteSpan span : spans) {
584 | getEditableText().removeSpan(span);
585 | }
586 | }
587 | }
588 | }
589 |
590 | protected boolean containQuote() {
591 | String[] lines = TextUtils.split(getEditableText().toString(), "\n");
592 | List list = new ArrayList<>();
593 |
594 | for (int i = 0; i < lines.length; i++) {
595 | int lineStart = 0;
596 | for (int j = 0; j < i; j++) {
597 | lineStart = lineStart + lines[j].length() + 1;
598 | }
599 |
600 | int lineEnd = lineStart + lines[i].length();
601 | if (lineStart >= lineEnd) {
602 | continue;
603 | }
604 |
605 | if (lineStart <= getSelectionStart() && getSelectionEnd() <= lineEnd) {
606 | list.add(i);
607 | } else if (getSelectionStart() <= lineStart && lineEnd <= getSelectionEnd()) {
608 | list.add(i);
609 | }
610 | }
611 |
612 | for (Integer i : list) {
613 | if (!containQuote(i)) {
614 | return false;
615 | }
616 | }
617 |
618 | return true;
619 | }
620 |
621 | protected boolean containQuote(int index) {
622 | String[] lines = TextUtils.split(getEditableText().toString(), "\n");
623 | if (index < 0 || index >= lines.length) {
624 | return false;
625 | }
626 |
627 | int start = 0;
628 | for (int i = 0; i < index; i++) {
629 | start = start + lines[i].length() + 1;
630 | }
631 |
632 | int end = start + lines[index].length();
633 | if (start >= end) {
634 | return false;
635 | }
636 |
637 | QuoteSpan[] spans = getEditableText().getSpans(start, end, QuoteSpan.class);
638 | return spans.length > 0;
639 | }
640 |
641 | // URLSpan =====================================================================================
642 |
643 | public void link(String link) {
644 | link(link, getSelectionStart(), getSelectionEnd());
645 | }
646 |
647 | // When KnifeText lose focus, use this method
648 | public void link(String link, int start, int end) {
649 | if (link != null && !TextUtils.isEmpty(link.trim())) {
650 | linkValid(link, start, end);
651 | } else {
652 | linkInvalid(start, end);
653 | }
654 | }
655 |
656 | protected void linkValid(String link, int start, int end) {
657 | if (start >= end) {
658 | return;
659 | }
660 |
661 | linkInvalid(start, end);
662 | getEditableText().setSpan(new KnifeURLSpan(link, linkColor, linkUnderline), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
663 | }
664 |
665 | // Remove all span in selection, not like the boldInvalid()
666 | protected void linkInvalid(int start, int end) {
667 | if (start >= end) {
668 | return;
669 | }
670 |
671 | URLSpan[] spans = getEditableText().getSpans(start, end, URLSpan.class);
672 | for (URLSpan span : spans) {
673 | getEditableText().removeSpan(span);
674 | }
675 | }
676 |
677 | protected boolean containLink(int start, int end) {
678 | if (start > end) {
679 | return false;
680 | }
681 |
682 | if (start == end) {
683 | if (start - 1 < 0 || start + 1 > getEditableText().length()) {
684 | return false;
685 | } else {
686 | URLSpan[] before = getEditableText().getSpans(start - 1, start, URLSpan.class);
687 | URLSpan[] after = getEditableText().getSpans(start, start + 1, URLSpan.class);
688 | return before.length > 0 && after.length > 0;
689 | }
690 | } else {
691 | StringBuilder builder = new StringBuilder();
692 |
693 | for (int i = start; i < end; i++) {
694 | if (getEditableText().getSpans(i, i + 1, URLSpan.class).length > 0) {
695 | builder.append(getEditableText().subSequence(i, i + 1).toString());
696 | }
697 | }
698 |
699 | return getEditableText().subSequence(start, end).toString().equals(builder.toString());
700 | }
701 | }
702 |
703 | // Redo/Undo ===================================================================================
704 |
705 | @Override
706 | public void beforeTextChanged(CharSequence text, int start, int count, int after) {
707 | if (!historyEnable || historyWorking) {
708 | return;
709 | }
710 |
711 | inputBefore = new SpannableStringBuilder(text);
712 | }
713 |
714 | @Override
715 | public void onTextChanged(CharSequence text, int start, int before, int count) {
716 | // DO NOTHING HERE
717 | }
718 |
719 | @Override
720 | public void afterTextChanged(Editable text) {
721 | if (!historyEnable || historyWorking) {
722 | return;
723 | }
724 |
725 | inputLast = new SpannableStringBuilder(text);
726 | if (text != null && text.toString().equals(inputBefore.toString())) {
727 | return;
728 | }
729 |
730 | if (historyList.size() >= historySize) {
731 | historyList.remove(0);
732 | }
733 |
734 | historyList.add(inputBefore);
735 | historyCursor = historyList.size();
736 | }
737 |
738 | public void redo() {
739 | if (!redoValid()) {
740 | return;
741 | }
742 |
743 | historyWorking = true;
744 |
745 | if (historyCursor >= historyList.size() - 1) {
746 | historyCursor = historyList.size();
747 | setText(inputLast);
748 | } else {
749 | historyCursor++;
750 | setText(historyList.get(historyCursor));
751 | }
752 |
753 | setSelection(getEditableText().length());
754 | historyWorking = false;
755 | }
756 |
757 | public void undo() {
758 | if (!undoValid()) {
759 | return;
760 | }
761 |
762 | historyWorking = true;
763 |
764 | historyCursor--;
765 | setText(historyList.get(historyCursor));
766 | setSelection(getEditableText().length());
767 |
768 | historyWorking = false;
769 | }
770 |
771 | public boolean redoValid() {
772 | if (!historyEnable || historySize <= 0 || historyList.size() <= 0 || historyWorking) {
773 | return false;
774 | }
775 |
776 | return historyCursor < historyList.size() - 1 || historyCursor >= historyList.size() - 1 && inputLast != null;
777 | }
778 |
779 | public boolean undoValid() {
780 | if (!historyEnable || historySize <= 0 || historyWorking) {
781 | return false;
782 | }
783 |
784 | if (historyList.size() <= 0 || historyCursor <= 0) {
785 | return false;
786 | }
787 |
788 | return true;
789 | }
790 |
791 | public void clearHistory() {
792 | if (historyList != null) {
793 | historyList.clear();
794 | }
795 | }
796 |
797 | // Helper ======================================================================================
798 |
799 | public boolean contains(int format) {
800 | switch (format) {
801 | case FORMAT_BOLD:
802 | return containStyle(Typeface.BOLD, getSelectionStart(), getSelectionEnd());
803 | case FORMAT_ITALIC:
804 | return containStyle(Typeface.ITALIC, getSelectionStart(), getSelectionEnd());
805 | case FORMAT_UNDERLINED:
806 | return containUnderline(getSelectionStart(), getSelectionEnd());
807 | case FORMAT_STRIKETHROUGH:
808 | return containStrikethrough(getSelectionStart(), getSelectionEnd());
809 | case FORMAT_BULLET:
810 | return containBullet();
811 | case FORMAT_QUOTE:
812 | return containQuote();
813 | case FORMAT_LINK:
814 | return containLink(getSelectionStart(), getSelectionEnd());
815 | default:
816 | return false;
817 | }
818 | }
819 |
820 | public void clearFormats() {
821 | setText(getEditableText().toString());
822 | setSelection(getEditableText().length());
823 | }
824 |
825 | public void hideSoftInput() {
826 | clearFocus();
827 | InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
828 | imm.hideSoftInputFromWindow(getWindowToken(), 0);
829 | }
830 |
831 | public void showSoftInput() {
832 | requestFocus();
833 | InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
834 | imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
835 | }
836 |
837 | public void fromHtml(String source) {
838 | SpannableStringBuilder builder = new SpannableStringBuilder();
839 | builder.append(KnifeParser.fromHtml(source));
840 | switchToKnifeStyle(builder, 0, builder.length());
841 | setText(builder);
842 | }
843 |
844 | public String toHtml() {
845 | return KnifeParser.toHtml(getEditableText());
846 | }
847 |
848 | protected void switchToKnifeStyle(Editable editable, int start, int end) {
849 | BulletSpan[] bulletSpans = editable.getSpans(start, end, BulletSpan.class);
850 | for (BulletSpan span : bulletSpans) {
851 | int spanStart = editable.getSpanStart(span);
852 | int spanEnd = editable.getSpanEnd(span);
853 | spanEnd = 0 < spanEnd && spanEnd < editable.length() && editable.charAt(spanEnd) == '\n' ? spanEnd - 1 : spanEnd;
854 | editable.removeSpan(span);
855 | editable.setSpan(new KnifeBulletSpan(bulletColor, bulletRadius, bulletGapWidth), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
856 | }
857 |
858 | QuoteSpan[] quoteSpans = editable.getSpans(start, end, QuoteSpan.class);
859 | for (QuoteSpan span : quoteSpans) {
860 | int spanStart = editable.getSpanStart(span);
861 | int spanEnd = editable.getSpanEnd(span);
862 | spanEnd = 0 < spanEnd && spanEnd < editable.length() && editable.charAt(spanEnd) == '\n' ? spanEnd - 1 : spanEnd;
863 | editable.removeSpan(span);
864 | editable.setSpan(new KnifeQuoteSpan(quoteColor, quoteStripeWidth, quoteGapWidth), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
865 | }
866 |
867 | URLSpan[] urlSpans = editable.getSpans(start, end, URLSpan.class);
868 | for (URLSpan span : urlSpans) {
869 | int spanStart = editable.getSpanStart(span);
870 | int spanEnd = editable.getSpanEnd(span);
871 | editable.removeSpan(span);
872 | editable.setSpan(new KnifeURLSpan(span.getURL(), linkColor, linkUnderline), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
873 | }
874 | }
875 | }
876 |
--------------------------------------------------------------------------------