Compare commits

...

73 commits

Author SHA1 Message Date
Scharel Clemens
aa8daf89f5 Remove unneeded interface class 2020-05-07 21:18:40 +02:00
Scharel Clemens
6818edd94a Improved offline mode 2020-05-05 19:44:31 +02:00
Scharel Clemens
054afd4ca2 Implemented two functions that should ease the syncronisation 2020-05-04 20:15:17 +02:00
Scharel Clemens
fe31598042 Further Changed on the QML side to adopt the previous changes on the C++ side 2020-05-03 18:30:39 +02:00
Scharel Clemens
842ea9f699 Prepare sync of offline changed notes 2020-05-03 13:00:36 +02:00
Scharel Clemens
8211acbe51 Changed on the QML side to adopt the previous changes on the C++ side 2020-05-01 12:57:43 +02:00
Scharel Clemens
84d720c7ca Connected signals and slots throught the NotesModel, so this can later handle the synchronisation 2020-04-20 22:48:56 +02:00
Scharel Clemens
cd55e83ae9 Model slots 2020-04-19 19:01:03 +02:00
Scharel Clemens
433a049a14 Updated signals and slots of the modules 2020-04-16 21:25:36 +02:00
Scharel Clemens
312be40fcf Just pushing to github to have the code available somewhere else 2020-04-15 08:31:04 +02:00
Scharel Clemens
4ff667e3d1 Improved communication between the modules. Offline mode seems to work fine now. Some kind of synchronisation of offline changes is now needed 2020-04-13 19:13:14 +02:00
Scharel Clemens
629d752dee Making progess... 2020-04-12 20:27:54 +02:00
Scharel Clemens
34484748f5 Show more debug messages on the console 2020-04-11 19:34:28 +02:00
Scharel Clemens
884a464a37 Improved relations between the data sources 2020-04-11 16:39:30 +02:00
Scharel Clemens
10b9423f35 Clearing NotesModel when changing the account 2020-04-11 15:40:47 +02:00
Scharel Clemens
4ea61c565f NotesStore and NotesApi Classes based on a common interface class. Seems to work fine :) 2020-04-10 20:40:23 +02:00
Scharel Clemens
1d4022bdbd Finished NotesStore class 2020-04-07 00:48:27 +02:00
Scharel Clemens
60e1eb0bdd Implementing new methods for data handling (files and API targets) 2020-04-05 22:59:18 +02:00
Scharel Clemens
ffffd306d6 A somehow working version again 2020-03-29 18:03:05 +02:00
Scharel Clemens
9616dfc6be Used new state info in the Login Dialog 2020-03-26 23:22:45 +01:00
Scharel Clemens
00921391a2 More state informations 2020-03-21 20:09:07 +01:00
Scharel Clemens
601985436d Some improvements in the LoginPage 2020-01-29 18:36:34 +01:00
Scharel Clemens
369cf2c1e9 Began implementing more detailled states for server API requests 2020-01-27 23:05:20 +01:00
Scharel Clemens
7be33026cf Began implementing some kind of state machine for the login 2020-01-27 18:36:43 +01:00
Scharel Clemens
61238c8d08 Improvements in LoginPage 2020-01-20 20:49:36 +01:00
Scharel Clemens
ffe96e2200 Worked on LoginPage 2020-01-19 13:13:29 +01:00
Scharel Clemens
4563e95ef7 Small changes in the LoginDialog 2020-01-16 22:14:47 +01:00
Scharel Clemens
9cb7237e81 Cleaned API C++ code. Small changes in LoginPage. 2020-01-15 23:55:11 +01:00
Scharel Clemens
2be8a2675d Implemented Nextcloud Login Flow v2 2020-01-15 00:27:17 +01:00
Scharel Clemens
ecebd90dcb Further implemented Flow v2 Login 2020-01-14 17:04:09 +01:00
Scharel Clemens
58ae28dbe6 Implemented status.php call in the API. Began implementing Nextcloud Login flow v2. 2020-01-14 14:47:42 +01:00
Scharel Clemens
da29b4b0ff Change notes locally befor committing it to the server 2020-01-12 20:23:51 +01:00
Scharel Clemens
20635dfd6e Only emit dataChanged() when the data actually changed 2020-01-12 16:01:54 +01:00
Scharel Clemens
73adff15ca Implemented setData() and setItemData() functions of the model for later use 2020-01-12 15:46:54 +01:00
Scharel Clemens
21cccf2f6e Just small fixes 2020-01-11 13:32:26 +01:00
Scharel Clemens
3e32fb94f9 Added notifications on error 2020-01-05 13:25:13 +01:00
Scharel Clemens
385cdc4cca Write notes to local files for upcoming offline mode 2020-01-04 16:08:40 +01:00
Scharel Clemens
f7bc0ed9b8 Always provide the attribute \'modified\' when creating or modifying a note to allow the API to handle conflicts 2020-01-04 14:53:50 +01:00
Scharel Clemens
52132195a5 Implemented sync-time capturing and offline detection 2020-01-03 14:00:07 +01:00
Scharel Clemens
4341b2bd01 Bugfix when deleting a note 2019-12-30 19:58:50 +01:00
Scharel Clemens
426f7ea509 Changed internal data handling to QJson___ for easier conversion to raw output to save the notes to files. 2019-12-30 18:14:38 +01:00
Scharel Clemens
e2aaa47a7e Small fix in account deleting 2019-12-18 20:21:47 +01:00
Scharel Clemens
74ae7bd213 Began implementing offline mode 2019-12-07 13:42:37 +01:00
Scharel Clemens
5fc566749f Small fixes on NotesPage and EditPage 2019-11-14 23:15:33 +01:00
Scharel Clemens
5f246cce20 Using QSortFilterProxyModel, so searching and sorting works now 2019-11-14 00:47:38 +01:00
Scharel Clemens
2ff9b06c99 Sorting order for "modified" 2019-11-13 13:22:20 +01:00
Scharel Clemens
cefa7259ad Implemented QSortFilterProxyModel 2019-11-11 23:23:41 +01:00
Scharel Clemens
3f128bcd63 Implemented API in C++. Next: I discovered QSortFilterProxyModel :) 2019-11-10 23:04:42 +01:00
Scharel Clemens
a026c2ee8d Implemented the API in C++. Still plenty bugs. 2019-11-10 03:35:33 +01:00
Scharel Clemens
85b33a9e37 Fixed a small bug while removing accounts 2019-10-27 17:53:38 +01:00
Scharel Clemens
5156f1e629 Improved C++ NotedModel and some small visual thinks 2019-06-21 17:49:54 +02:00
Scharel Clemens
3b1e1cca8c Still no big changes 2019-06-20 20:25:32 +02:00
Scharel Clemens
1e7203d1a2 Still no big changes 2019-06-20 20:13:46 +02:00
Scharel Clemens
66b56d0ed2 Worked on the c++ model 2019-05-13 23:32:37 +02:00
Scharel Clemens
52147548cc Just pushing to transport the current code to another computer 2019-05-13 18:39:45 +02:00
Scharel Clemens
a841a96e76 Began ggoing through the code to clean it. 2019-05-10 18:38:52 +02:00
Scharel Clemens
159ef73315 Fixed sorting by date 2019-04-07 12:28:38 +02:00
Scharel Clemens
c4268f6212 Integrated Showdown as a git submodule 2019-03-11 21:53:04 +01:00
Scharel Clemens
0de7aec681 Integrated Showdown as a git submodule 2019-03-11 21:43:31 +01:00
Scharel Clemens
87f7ba83fd Worked on the C++ model and its integration 2019-03-10 20:20:41 +01:00
Scharel Clemens
fc8072bb60 Just some small changes. 2019-02-24 16:40:47 +01:00
Scharel Clemens
2941f32eb4 Removed some old code 2019-02-01 19:17:07 +01:00
Scharel Clemens
c20d7408d2 Worked on C++ implementation of the Model. It seems to work somehow. 2019-01-28 23:15:53 +01:00
Scharel Clemens
ddb778795b Began testing the new C++ Model. 2019-01-26 18:09:28 +01:00
Scharel Clemens
6419b45f52 Worked on C++ implementation of the model. 2019-01-06 11:35:28 +01:00
scharel
72f3b3f44c Further worked on C++ implementation of the notes Model. 2018-12-30 15:16:23 +01:00
scharel
86a3755ad2 Began implementing the data model in C++ 2018-12-29 01:40:11 +01:00
scharel
03098b7354 Implemented #24 and #32 (not tested) 2018-12-27 20:38:14 +01:00
scharel
3cd7be99cd Merged swedish translation. 2018-12-27 09:17:11 +01:00
scharel
c38727e77e Improved workaround for #40 2018-12-26 21:51:20 +01:00
Scharel
40aa889e07 Fixed #39 and workaround for #40. Some other changes 2018-12-23 01:59:01 +01:00
Scharel
41f530c0f6 Small changes 2018-12-22 08:03:15 +01:00
Scharel Clemens
99a184697b Just pushing befor travaling home for xmas 2018-12-20 18:53:29 +01:00
108 changed files with 3753 additions and 17819 deletions

3
.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "qml/js/showdown"]
path = qml/js/showdown
url = git@github.com:showdownjs/showdown.git

View file

@ -1,54 +1,61 @@
# NOTICE:
#
# Application name defined in TARGET has a corresponding QML filename.
# If name defined in TARGET is changed, the following needs to be done
# to match new name:
# - corresponding QML filename must be changed
# - desktop icon filename must be changed
# - desktop filename must be changed
# - icon definition filename in desktop file must be changed
# - translation filenames have to be changed
# The name of your application
TARGET = harbour-nextcloudnotes
CONFIG += sailfishapp
DEFINES += APP_VERSION=\\\"$$VERSION\\\"
SOURCES += src/harbour-nextcloudnotes.cpp
DISTFILES += qml/harbour-nextcloudnotes.qml \
qml/cover/CoverPage.qml \
rpm/harbour-nextcloudnotes.changes.run.in \
rpm/harbour-nextcloudnotes.changes \
rpm/harbour-nextcloudnotes.spec \
rpm/harbour-nextcloudnotes.yaml \
translations/*.ts \
harbour-nextcloudnotes.desktop \
qml/pages/NotePage.qml \
qml/pages/NotesPage.qml \
qml/pages/LoginDialog.qml \
qml/pages/EditPage.qml \
qml/pages/SettingsPage.qml \
qml/pages/AboutPage.qml \
qml/pages/UnencryptedDialog.qml \
qml/pages/NotesApi.qml \
qml/pages/MITLicense.qml \
qml/pages/GPLLicense.qml \
qml/pages/SyntaxPage.qml
SAILFISHAPP_ICONS = 86x86 108x108 128x128 172x172
# to disable building translations every time, comment out the
# following CONFIG line
CONFIG += sailfishapp_i18n
# German translation is enabled as an example. If you aren't
# planning to localize your app, remember to comment out the
# following TRANSLATIONS line. And also do not forget to
# modify the localized app name in the the .desktop file.
TRANSLATIONS += translations/harbour-nextcloudnotes-de.ts \
translations/harbour-nextcloudnotes-sv.ts
HEADERS +=
# NOTICE:
#
# Application name defined in TARGET has a corresponding QML filename.
# If name defined in TARGET is changed, the following needs to be done
# to match new name:
# - corresponding QML filename must be changed
# - desktop icon filename must be changed
# - desktop filename must be changed
# - icon definition filename in desktop file must be changed
# - translation filenames have to be changed
# The name of your application
TARGET = harbour-nextcloudnotes
CONFIG += sailfishapp
DEFINES += APP_VERSION=\\\"$$VERSION\\\"
HEADERS += src/note.h \
src/notesapi.h \
src/notesmodel.h \
src/notesstore.h
SOURCES += src/harbour-nextcloudnotes.cpp \
src/note.cpp \
src/notesapi.cpp \
src/notesmodel.cpp \
src/notesstore.cpp
DISTFILES += qml/harbour-nextcloudnotes.qml \
qml/cover/CoverPage.qml \
qml/pages/LoginPage.qml \
rpm/harbour-nextcloudnotes.changes.run.in \
rpm/harbour-nextcloudnotes.changes \
rpm/harbour-nextcloudnotes.spec \
rpm/harbour-nextcloudnotes.yaml \
translations/*.ts \
harbour-nextcloudnotes.desktop \
qml/pages/NotePage.qml \
qml/pages/NotesPage.qml \
qml/pages/EditPage.qml \
qml/pages/SettingsPage.qml \
qml/pages/AboutPage.qml \
qml/pages/UnencryptedDialog.qml \
qml/pages/NotesApi.qml \
qml/pages/MITLicense.qml \
qml/pages/GPLLicense.qml \
qml/pages/SyntaxPage.qml
SAILFISHAPP_ICONS = 86x86 108x108 128x128 172x172
# to disable building translations every time, comment out the
# following CONFIG line
CONFIG += sailfishapp_i18n
# German translation is enabled as an example. If you aren't
# planning to localize your app, remember to comment out the
# following TRANSLATIONS line. And also do not forget to
# modify the localized app name in the the .desktop file.
TRANSLATIONS += translations/harbour-nextcloudnotes-de.ts \
translations/harbour-nextcloudnotes-sv.ts

View file

@ -1,4 +1,4 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
CoverBackground {

View file

@ -1,33 +1,74 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
import Nemo.Configuration 1.0
import Nemo.Notifications 1.0
import "pages"
ApplicationWindow
{
id: appWindow
// All configured accounts
ConfigurationValue {
id: accounts
key: appSettings.path + "/accountIDs"
defaultValue: [ ]
}
// Current account in use
ConfigurationGroup {
id: account
path: "/apps/harbour-nextcloudnotes/accounts/" + appSettings.currentAccount
property string name: value("name", "", String)
property url server: value("server", "", String)
property string version: value("version", "v0.2", String)
property string username: value("username", "", String)
property string password: account.value("password", "", String)
property bool doNotVerifySsl: account.value("doNotVerifySsl", false, Boolean)
property bool allowUnecrypted: account.value("allowUnecrypted", false, Boolean)
property date update: value("update", "", Date)
onServerChanged: notesApi.server = server
onUsernameChanged: {
console.log("Username: " + username)
notesApi.username = username
}
onPasswordChanged: notesApi.password = password
onDoNotVerifySslChanged: notesApi.verifySsl = !doNotVerifySsl
onNameChanged: console.log("Using account: " + name)
}
// General settings of the app
ConfigurationGroup {
id: appSettings
path: "/apps/harbour-nextcloudnotes/settings"
//synchronous: true
property string currentAccount: value("currentAccount", "")
property var accountIDs: value("accountIDs", [ ])
property int autoSyncInterval: value("autoSyncInterval", 0)
property int previewLineCount: value("previewLineCount", 4)
property string sortBy: value("sortBy", "date")
property bool showSeparator: value("showSeparator", false)
property bool useMonoFont: value("useMonoFont", false)
property bool useCapitalX: value("useCapitalX", false)
property bool initialized: false
property string currentAccount: value("currentAccount", "", String)
property int autoSyncInterval: value("autoSyncInterval", 0, Number)
property int previewLineCount: value("previewLineCount", 4, Number)
property bool favoritesOnTop: value("favoritesOnTop", true, Boolean)
property string sortBy: value("sortBy", "modifiedString", String)
property bool showSeparator: value("showSeparator", false, Boolean)
property bool useMonoFont: value("useMonoFont", false, Boolean)
property bool useCapitalX: value("useCapitalX", false, Boolean)
onCurrentAccountChanged: api.uuid = currentAccount
onCurrentAccountChanged: {
notesProxyModel.sourceModel.clear()
account.path = "/apps/harbour-nextcloudnotes/accounts/" + currentAccount
notesStore.account = currentAccount
notesModel.getAllNotes()
}
onSortByChanged: {
if (sortBy == "none")
notesProxyModel.invalidate()
else
notesProxyModel.sortRole = notesProxyModel.roleFromName(sortBy)
}
onFavoritesOnTopChanged: {
notesProxyModel.favoritesOnTop = favoritesOnTop
}
function addAccount() {
var uuid = uuidv4()
@ -37,26 +78,36 @@ ApplicationWindow
accounts.sync()
return uuid
}
ConfigurationGroup {
id: removeHelperConfGroup
}
function removeAccount(uuid) {
autoSyncTimer.stop()
var tmpAccouunt = currentAccount
currentAccount = uuid
api.clear()
currentAccount = tmpAccouunt
var newIds = [ ]
accountIDs.forEach(function(currentValue) {
if (currentValue !== uuid) {
newIds.push(currentValue)
var tmpIDs = accounts.value
removeHelperConfGroup.path = "/apps/harbour-nextcloudnotes/accounts/" + uuid
for (var i = tmpIDs.length-1; i >= 0; i--) {
console.log(tmpIDs)
console.log("Checking:" + tmpIDs[i])
if (tmpIDs[i] === uuid) {
console.log("Found! Removing ...")
tmpIDs.splice(i, 1)
}
})
accounts.value = newIds
for (var i = accountIDs.length-1; i > 0; i--) {
if (accountIDs[i] !== uuid) {
api.uuid = accountIDs[i]
break
console.log(tmpIDs)
}
if (appSettings.currentAccount === uuid) {
appSettings.currentAccount = ""
for (var i = tmpIDs.length-1; i >= 0 && appSettings.currentAccount === ""; i--) {
if (tmpIDs[i] !== uuid) {
appSettings.currentAccount = tmpIDs[i]
}
}
}
autoSyncTimer.start()
removeHelperConfGroup.clear()
if (autoSyncInterval > 0 && appWindow.visible) {
autoSyncTimer.start()
}
accounts.value = tmpIDs
accounts.sync()
}
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
@ -66,76 +117,94 @@ ApplicationWindow
}
}
Notification {
id: offlineNotification
expireTimeout: 0
appName: "Nextcloud " + qsTr("Notes")
summary: qsTr("Offline")
body: qsTr("Synced") + ": " + new Date(account.update).toLocaleString(Qt.locale())
Component.onDestruction: close()
}
Notification {
id: storeErrorNotification
appName: offlineNotification.appName
summary: qsTr("File error")
Component.onDestruction: close()
}
Notification {
id: apiErrorNotification
appName: offlineNotification.appName
summary: qsTr("API error")
Component.onDestruction: close()
}
Timer {
id: autoSyncTimer
interval: appSettings.autoSyncInterval * 1000
repeat: true
running: interval > 0 && appWindow.visible
running: interval > 0 && notesApi.networkAccessible && appWindow.visible
triggeredOnStart: true
onTriggered: {
if (!api.busy) {
api.getNotes()
notesModel.getAllNotes()
}
onIntervalChanged: {
if (interval > 0) {
console.log("Auto-Sync every " + interval / 1000 + " seconds")
}
}
}
Connections {
target: notesStore
onNoteError: {
storeErrorNotification.close()
if (error) {
console.log("Notes Store error (" + error + "): " + notesStore.errorMessage(error))
storeErrorNotification.body = notesStore.errorMessage(error)
storeErrorNotification.publish()
}
}
}
Connections {
target: notesApi
onNetworkAccessibleChanged: {
console.log("Device is " + (accessible ? "online" : "offline"))
if (accessible) {
offlineNotification.close(Notification.Closed)
getAllNotes()
}
else {
triggeredOnStart = false
restart()
triggeredOnStart = true
offlineNotification.publish()
}
}
onIntervalChanged: console.log("Auto-Sync every " + interval / 1000 + " seconds")
}
NotesApi {
id: api
uuid: appSettings.currentAccount
}
/*ConfigurationValue {
id: nextcloudUUIDs
key: "/apps/harbour-nextcloudnotes/settings/accountIDs"
defaultValue: []
onValueChanged: {
nextcloudAccounts.model = value
}
Component.onCompleted: nextcloudAccounts.model = value
}
Repeater {
id: nextcloudAccounts
delegate: NotesApi {
uuid: nextcloudUUIDs.value[index]
saveFile: true
}
function add() {
push(uuidv4())
}
function remove(uuid) {
for (var i = 0; i < count; i++) {
if (itemAt(i).uuid === uuid) {
itemAt(i).clear()
}
onNoteError: {
apiErrorNotification.close()
if (error)
console.log("Notes API error (" + error + "): " + notesApi.errorMessage(error))
if (error && notesApi.networkAccessible) {
apiErrorNotification.body = notesApi.errorMessage(error)
apiErrorNotification.publish()
}
var newIds = [ ]
nextcloudUUIDs.value.forEach(function(currentValue) {
if (currentValue !== uuid) {
newIds.push(currentValue)
}
})
nextcloudUUIDs.value = newIds
if (nextcloudUUIDs.value[appSettings.currentAccount] === uuid)
appSettings.currentAccount = nextcloudUUIDs.value.length-1
}
function push(uuid) {
var accountIDs = nextcloudUUIDs.value
accountIDs.push(uuid)
nextcloudUUIDs.value = accountIDs
onLastSyncChanged: {
console.log("Last API sync: " + lastSync)
account.update = lastSync
}
function pop() {
var accountIDs = nextcloudUUIDs.value
accountIDs.pop()
nextcloudUUIDs.value = accountIDs
}
}*/
}
Component.onCompleted: {
}
Component.onDestruction: {
offlineNotification.close()
storeErrorNotification.close()
apiErrorNotification.close()
}
initialPage: Component { NotesPage { } }
cover: Qt.resolvedUrl("cover/CoverPage.qml")

1
qml/js/showdown Submodule

@ -0,0 +1 @@
Subproject commit 483e51f7a624c94c95787a14cbf577c053f8076f

View file

@ -1,773 +0,0 @@
<a name="1.9.0"></a>
# [1.9.0](https://github.com/showdownjs/showdown/compare/1.8.7...1.9.0) (2018-11-10)
### Bug Fixes
* **italicsAndBold:** fix issue with consecutive spans ([#608](https://github.com/showdownjs/showdown/issues/608)) ([5c0d67e](https://github.com/showdownjs/showdown/commit/5c0d67e)), closes [#544](https://github.com/showdownjs/showdown/issues/544)
* **underline**: fix issue with consecutive spans ([81edc70](https://github.com/showdownjs/showdown/commit/81edc70))
### Features
* **converter.makeMarkdown:** [EXPERIMENTAL] add an HTML to MD converter ([e4b0e69](https://github.com/showdownjs/showdown/commit/e4b0e69)), closes [#388](https://github.com/showdownjs/showdown/issues/388) [#233](https://github.com/showdownjs/showdown/issues/233)
<a name="1.8.7"></a>
## [1.8.7](https://github.com/showdownjs/showdown/compare/1.8.6...1.8.7) (2018-10-16)
### Bug Fixes
* **emojis:** fix emoji excessive size ([4aca41c](https://github.com/showdownjs/showdown/commit/4aca41c))
* **gfm-codeblocks:**
* add support for spaces before language declaration ([24bf7b1](https://github.com/showdownjs/showdown/commit/24bf7b1)), closes [#569](https://github.com/showdownjs/showdown/issues/569)
* leading space no longer breaks gfm codeblocks ([828c32f](https://github.com/showdownjs/showdown/commit/828c32f)), closes [#523](https://github.com/showdownjs/showdown/issues/523)
* **images:** fix js error when using image references ([980e702](https://github.com/showdownjs/showdown/commit/980e702)), closes [#585](https://github.com/showdownjs/showdown/issues/585)
* **literalMidWordAsterisks:** now parses single characters enclosed by * correctly ([fe70e45](https://github.com/showdownjs/showdown/commit/fe70e45)), closes [#478](https://github.com/showdownjs/showdown/issues/478)
* **mentions:** allow for usernames with dot, underscore and dash ([dfeb1e2](https://github.com/showdownjs/showdown/commit/dfeb1e2)), closes [#574](https://github.com/showdownjs/showdown/issues/574)
* **nbsp:** fix replacing of nbsp with regular spaces ([8bc1f42](https://github.com/showdownjs/showdown/commit/8bc1f42))
<a name="1.8.6"></a>
## [1.8.6](https://github.com/showdownjs/showdown/compare/1.8.5...1.8.6) (2017-12-22)
### Features
* **splitAdjacentBlockquotes:** add option to split adjacent blockquote blocks ([da328f2](https://github.com/showdownjs/showdown/commit/da328f2)), closes [#477](https://github.com/showdownjs/showdown/issues/477)
<a name="1.8.5"></a>
# [1.8.5](https://github.com/showdownjs/showdown/compare/1.8.4...1.8.5) (2017-12-10)
### Features
* **completeHTMLDocument:** add option to output a complete HTML document ([a8427c9](https://github.com/showdownjs/showdown/commit/a8427c9))
* **metadata:** add support for embedded metadata ([63d949f](https://github.com/showdownjs/showdown/commit/63d949f)), closes [#260](https://github.com/showdownjs/showdown/issues/260)
<a name="1.8.4"></a>
## [1.8.4](https://github.com/showdownjs/showdown/compare/1.8.3...1.8.4) (2017-12-05)
### Bug Fixes
* **tables:** raw html inside code tags in tables no longer breaks tables ([4ef4c5e](https://github.com/showdownjs/showdown/commit/4ef4c5e)), closes [#471](https://github.com/showdownjs/showdown/issues/471)
<a name="1.8.3"></a>
## [1.8.3](https://github.com/showdownjs/showdown/compare/1.8.2...1.8.3) (2017-11-28)
### Bug Fixes
* **literalMidWordAsterisks:** no longer treats colon as alphanumeric char ([21194c8](https://github.com/showdownjs/showdown/commit/21194c8)), closes [#461](https://github.com/showdownjs/showdown/issues/461)
* **spanGamut:** code spans are hashed after parsing ([f4f63c5](https://github.com/showdownjs/showdown/commit/f4f63c5)), closes [#464](https://github.com/showdownjs/showdown/issues/464)
* **tables:** pipe character in code spans no longer breaks table ([0c933a0](https://github.com/showdownjs/showdown/commit/0c933a0)), closes [#465](https://github.com/showdownjs/showdown/issues/465)
<a name="1.8.2"></a>
## [1.8.2](https://github.com/showdownjs/showdown/compare/1.8.1...1.8.2) (2017-11-11)
### Bug Fixes
* **fenced codeblocks:** add tilde as fenced code block delimiter ([c956ede](https://github.com/showdownjs/showdown/commit/c956ede)), closes [#456](https://github.com/showdownjs/showdown/issues/456)
* **openLinksInNewWindow:** hash links are not affected by the option ([11936ec](https://github.com/showdownjs/showdown/commit/11936ec)), closes [#457](https://github.com/showdownjs/showdown/issues/457)
<a name="1.8.1"></a>
## [1.8.1](https://github.com/showdownjs/showdown/compare/1.8.0...1.8.1) (2017-11-01)
### Dependencies update
* **package:** update yargs to version 10.0.3 ([#447](https://github.com/showdownjs/showdown/issues/447)) ([906b26d](https://github.com/showdownjs/showdown/commit/906b26d))
### Bug Fixes
* **CDNjs:** bump version to fix version missmatch with CDNjs ([#452](https://github.com/showdownjs/showdown/issues/452))
<a name="1.8.0"></a>
# [1.8.0](https://github.com/showdownjs/showdown/compare/1.7.6...1.8.0) (2017-10-24)
### NOTICE
Don't use the CDNjs version of this release. See issue [#452](https://github.com/showdownjs/showdown/issues/452) for more details.
### Bug Fixes
* **autolinks:** prevent _ and * to be parsed in links ([61929bb](https://github.com/showdownjs/showdown/commit/61929bb)), closes [#444](https://github.com/showdownjs/showdown/issues/444)
### Features
* **ellipsis:** add auto-ellipsis support ([25f1978](https://github.com/showdownjs/showdown/commit/25f1978))
- *Example:*
input
```md
this is an ellipsis...
```
output
```html
<p>this is an ellipsis…</p>
```
* **emoji:** add emoji support through option `emoji`([5b8f1d3](https://github.com/showdownjs/showdown/commit/5b8f1d3)), closes [#448](https://github.com/showdownjs/showdown/issues/448)
- *Usage:*
```js
var conv = new showdown.Converter({emoji: true});
```
- *Example:*
input
```md
this is a smile :smile: emoji
```
output
```html
<p>this is a smile 😄 emoji</p>
```
* **start ordered lists at an arbitrary number:** add support for defining the first item number of ordered lists ([9cdc35e](https://github.com/showdownjs/showdown/commit/9cdc35e)), closes [#377](https://github.com/showdownjs/showdown/issues/377)
- *Example:*
input
```md
3. foo
4. bar
5. baz
```
output
```html
<ol start="3">
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ol>
```
* **underline:** add EXPERIMENTAL support for underline ([084b819](https://github.com/showdownjs/showdown/commit/084b819)), closes [#450](https://github.com/showdownjs/showdown/issues/450)
- *Usage:*
```js
var conv = new showdown.Converter({underline: true});
```
- *Example:*
input
```md
this is __underlined__ and this is ___also underlined___
```
output
```html
<p>this is <u>underlined</u> and this is <u>also underlined</u></p>
```
- *Note:* With this option enabled, underscore no longer parses as `<em>` or `<strong>`
### BREAKING CHANGES
* start ordered lists at an arbitrary number: Since showdown now supports starting ordered lists at an arbitrary number,
list output may differ.
<a name="1.7.6"></a>
## [1.7.6](https://github.com/showdownjs/showdown/compare/1.7.5...1.7.6) (2017-10-06)
### Bug Fixes
* **tables:** tables are properly rendered when followed by a single linebreak and a list ([d88b095](https://github.com/showdownjs/showdown/commit/d88b095)), closes [#443](https://github.com/showdownjs/showdown/issues/443)
* **tables:** trailing spaces no longer prevent table parsing ([66bdd21](https://github.com/showdownjs/showdown/commit/66bdd21)), closes [#442](https://github.com/showdownjs/showdown/issues/442)
<a name="1.7.5"></a>
## [1.7.5](https://github.com/showdownjs/showdown/compare/1.7.4...1.7.5) (2017-10-02)
### Bug Fixes
* **html-comments:** changed regex to precent malformed long comment to freeze showdown ([3efcd10](https://github.com/showdownjs/showdown/commit/3efcd10)), closes [#439](https://github.com/showdownjs/showdown/issues/439)
<a name="1.7.4"></a>
## [1.7.4](https://github.com/showdownjs/showdown/compare/1.7.3...1.7.4) (2017-09-08)
### Bug Fixes
* **helper.isArray:** replace a.constructor === Array with Array.isArray ([466a2eb](https://github.com/showdownjs/showdown/commit/466a2eb)), closes [#425](https://github.com/showdownjs/showdown/issues/425)
* **loader:** allow AMD loader to be used within Node env ([ff24bdb](https://github.com/showdownjs/showdown/commit/ff24bdb))
### Features
* **base64-wrapping:** support for wrapping base64 strings ([8c593a4](https://github.com/showdownjs/showdown/commit/8c593a4)), closes [#429](https://github.com/showdownjs/showdown/issues/429)
<a name="1.7.3"></a>
## [1.7.3](https://github.com/showdownjs/showdown/compare/1.7.2...1.7.3) (2017-08-23)
### Bug Fixes
* **github flavor:** add backslashEscapesHTMLTags to GFM flavor ([5284439](https://github.com/showdownjs/showdown/commit/5284439))
* **literalMidWordAsterisks:** option no longer treats punctuation as word character ([8f05be7](https://github.com/showdownjs/showdown/commit/8f05be7)), closes [#398](https://github.com/showdownjs/showdown/issues/398)
* **tables:** allow for one column table ([fef110c](https://github.com/showdownjs/showdown/commit/fef110cccb2d02b218183398d9baa0ae256a7283)), closes [#406](https://github.com/showdownjs/showdown/issues/406)
### Features
* **rawHeaderId:** Remove only spaces, ' and " from generated header ids ([1791cf0](https://github.com/showdownjs/showdown/commit/1791cf0)), closes [#409](https://github.com/showdownjs/showdown/issues/409)
* **rawPrefixHeaderId:** add option to prevent showdown from modifying the prefix ([ff26c08](https://github.com/showdownjs/showdown/commit/ff26c08)), closes [#409](https://github.com/showdownjs/showdown/issues/409)
<a name="1.7.2"></a>
## [1.7.2](https://github.com/showdownjs/showdown/compare/1.7.1...1.7.2) (2017-08-05)
### Bug Fixes
* **githubMentions:** githubMentions now works with openLinksInNewWindow options ([1194d88](https://github.com/showdownjs/showdown/commit/1194d88)), closes [#403](https://github.com/showdownjs/showdown/issues/403)
* **lists:** fix multi paragraph lists with sublists ([a2259c0](https://github.com/showdownjs/showdown/commit/a2259c0)), closes [#397](https://github.com/showdownjs/showdown/issues/397)
* **tablesHeaderId:** fix missmatch of option name ([51e4693](https://github.com/showdownjs/showdown/commit/51e4693)), closes [#412](https://github.com/showdownjs/showdown/issues/412)
### Features
* **backslashEscapesHTMLTags:** backslash escapes HTML tags ([5a5aff6](https://github.com/showdownjs/showdown/commit/5a5aff6)), closes [#374](https://github.com/showdownjs/showdown/issues/374)
<a name="1.7.1"></a>
## [1.7.1](https://github.com/showdownjs/showdown/compare/1.7.0...1.7.1) (2017-06-02)
Important HOTFIX
### Bug Fixes
* **HTML Parser:** fix nasty bug where malformed HTML would hang showdown ([6566c72](https://github.com/showdownjs/showdown/commit/6566c72)), closes [#393](https://github.com/showdownjs/showdown/issues/393)
<a name="1.7.0"></a>
## [1.7.0](https://github.com/showdownjs/showdown/compare/1.6.4...1.7.0) (2017-06-01)
(DEPRECATED)
### Bug Fixes
* **anchors:** fix issue with brackets in link URL ([7ba18dd](https://github.com/showdownjs/showdown/commit/7ba18dd)), closes [#390](https://github.com/showdownjs/showdown/issues/390)
* **excludeTrailingPunctuationFromURL:** add comma to punctuation list ([fa35fd5](https://github.com/showdownjs/showdown/commit/fa35fd5)), closes [#354](https://github.com/showdownjs/showdown/issues/354)
* **excludeTrailingPunctuationFromURLs:** fix weird character when this option with simplifiedAutoLinks ([71acff5](https://github.com/showdownjs/showdown/commit/71acff5)), closes [#378](https://github.com/showdownjs/showdown/issues/378)
* **HTML parsing:** fix HTML parsing issues with nested tags ([6fbc072](https://github.com/showdownjs/showdown/commit/6fbc072)), closes [#357](https://github.com/showdownjs/showdown/issues/357) [#387](https://github.com/showdownjs/showdown/issues/387)
* **openLinksInNewWindow:** encode _ to prevent clash with em ([813f832](https://github.com/showdownjs/showdown/commit/813f832)), closes [#379](https://github.com/showdownjs/showdown/issues/379)
* **package:** update yargs to version 7.0.1 ([#349](https://github.com/showdownjs/showdown/issues/349)) ([9308d7b](https://github.com/showdownjs/showdown/commit/9308d7b))
* **package:** update yargs to version 8.0.1 ([#385](https://github.com/showdownjs/showdown/issues/385)) ([5fd847b](https://github.com/showdownjs/showdown/commit/5fd847b))
* **simpleAutoLinks:** URLs with emphasis/strikethrough are parsed ([5c50675](https://github.com/showdownjs/showdown/commit/5c50675)), closes [#347](https://github.com/showdownjs/showdown/issues/347)
* **tables:** pipe char can now be escaped ([1ebc195](https://github.com/showdownjs/showdown/commit/1ebc195)), closes [#345](https://github.com/showdownjs/showdown/issues/345)
* **url parsing:** fix url edge case parsing in images and links ([30aa18c](https://github.com/showdownjs/showdown/commit/30aa18c))
### Features
* **customizeHeaderId:** add option for customizing header ids ([94c570a](https://github.com/showdownjs/showdown/commit/94c570a)), closes [#383](https://github.com/showdownjs/showdown/issues/383)
* **images:** add support for image's implicit reference syntax ([0c6c07b](https://github.com/showdownjs/showdown/commit/0c6c07b)), closes [#366](https://github.com/showdownjs/showdown/issues/366)
* **literalMidWordAsterisks:** add option for mid word asterisks ([5bec8f9](https://github.com/showdownjs/showdown/commit/5bec8f9))
* **openLinksInNewWindow:** add option to open all links in a new window ([50235d6](https://github.com/showdownjs/showdown/commit/50235d6)), closes [#362](https://github.com/showdownjs/showdown/issues/362) [#337](https://github.com/showdownjs/showdown/issues/337) [#249](https://github.com/showdownjs/showdown/issues/249) [#247](https://github.com/showdownjs/showdown/issues/247) [#222](https://github.com/showdownjs/showdown/issues/222)
<a name="1.6.4"></a>
## [1.6.4](https://github.com/showdownjs/showdown/compare/1.6.3...1.6.4) (2017-02-06)
### Bug Fixes
* **encodeAmpsAndAngles:** fix > and < encoding ([7f43b79](https://github.com/showdownjs/showdown/commit/7f43b79)), closes [#236](https://github.com/showdownjs/showdown/issues/236)
* **encodeEmail:** now produces valid emails ([605d8b7](https://github.com/showdownjs/showdown/commit/605d8b7)), closes [#340](https://github.com/showdownjs/showdown/issues/340)
* **flavor: github:** new version of github does not use prefix 'user-content' in headers ([368f0b6](https://github.com/showdownjs/showdown/commit/368f0b6))
* **hashCodeTags:** escape code tags ([41cb3f6](https://github.com/showdownjs/showdown/commit/41cb3f6)), closes [#339](https://github.com/showdownjs/showdown/issues/339)
* **italicsAndBold:** fix double emphasis edge case ([1832b7f](https://github.com/showdownjs/showdown/commit/1832b7f))
* **paragraph:** workaround QML bug ([f7a429e](https://github.com/showdownjs/showdown/commit/f7a429e)), closes [#246](https://github.com/showdownjs/showdown/issues/246) [#338](https://github.com/showdownjs/showdown/issues/338)
* **prefixHeaderId:** make `prefixHeaderId` string be parsed along the generated id ([f641a7d](https://github.com/showdownjs/showdown/commit/f641a7d))
### Features
* **flavor: ghost:** add Ghost flavor ([6374b5b](https://github.com/showdownjs/showdown/commit/6374b5b))
* **flavor: original:** add John Gruber's markdown flavor ([6374b5b](https://github.com/showdownjs/showdown/commit/6374b5b))
<a name="1.6.3"></a>
## [1.6.3](https://github.com/showdownjs/showdown/compare/1.6.2...1.6.3) (2017-01-30)
### Bug Fixes
* **codeSpans:** add - and = to escaped chars inside code spans ([4243a31](https://github.com/showdownjs/showdown/commit/4243a31))
* **italicsAndBold:** fix inconsistency in italicsAndBold parsing ([a4f05d4](https://github.com/showdownjs/showdown/commit/a4f05d4)), closes [#332](https://github.com/showdownjs/showdown/issues/332)
* **literalMidWordUnderscores:** fix inconsistent behavior of emphasis and strong with literalMidWordUndescores ([0292ae0](https://github.com/showdownjs/showdown/commit/0292ae0)), closes [#333](https://github.com/showdownjs/showdown/issues/333)
* **paragraphs:** fix empty lines generating empty paragraphs ([54bf744](https://github.com/showdownjs/showdown/commit/54bf744)), closes [#334](https://github.com/showdownjs/showdown/issues/334)
* **strikethrough:** fix striketrough being wrongly parsed inside codeSpans ([169cbe8](https://github.com/showdownjs/showdown/commit/169cbe8))
### Features
* **events:** add events to all subparsers ([7d63a3e](https://github.com/showdownjs/showdown/commit/7d63a3e))
<a name="1.6.2"></a>
## [1.6.2](https://github.com/showdownjs/showdown/compare/1.6.1...1.6.2) (2017-01-29)
### Bug Fixes
* **escapeSpecialCharsWithinTagAttributes:** add ~ and = to escaped chars ([bfcc0e4](https://github.com/showdownjs/showdown/commit/bfcc0e4))
* **strikethrough:** allow escapinging tilde char ([24d47d7](https://github.com/showdownjs/showdown/commit/24d47d7)), closes [#331](https://github.com/showdownjs/showdown/issues/331)
### Features
* **ghMentionsLink:** add ability to define the generated url in @mentions ([a4c24c9](https://github.com/showdownjs/showdown/commit/a4c24c9))
<a name="1.6.1"></a>
## [1.6.1](https://github.com/showdownjs/showdown/compare/1.6.0...1.6.1) (2017-01-28)
### Bug Fixes
* **simplifiedAutoLink:** fix missing spaces before and after email addresses ([5190b6a](https://github.com/showdownjs/showdown/commit/5190b6a)), closes [#330](https://github.com/showdownjs/showdown/issues/330)
### Features
* **encodeEmail:** add option to enable/disable mail obfuscation ([90c52b8](https://github.com/showdownjs/showdown/commit/90c52b8))
### Notes
This release also improves performance a bit (around 8%)
<a name="1.6.0"></a>
## [1.6.0](https://github.com/showdownjs/showdown/compare/1.5.5...1.6.0) (2017-01-09)
### Bug Fixes
* **ghCompatibleHeaderId:** improve the number of removed chars ([d499feb](https://github.com/showdownjs/showdown/commit/d499feb))
* **IE8:** fix for IE8 error on using isUndefined function ([561dc5f](https://github.com/showdownjs/showdown/commit/561dc5f)), closes [#280](https://github.com/showdownjs/showdown/issues/280)
* **options:** fix ghCompatibleHeaderId that was set as string instead of boolean ([de7c37e](https://github.com/showdownjs/showdown/commit/de7c37e))
* **simpleLineBreaks:** fix simpleLineBreaks option not working with non-ASCII chars and markdown delimiters ([b1c458a](https://github.com/showdownjs/showdown/commit/b1c458a)), closes [#318](https://github.com/showdownjs/showdown/issues/318) [#323](https://github.com/showdownjs/showdown/issues/323)
### Features
* **CLI:** add -q (quiet) and -m (mute) mode to CLI ([f3b86f0](https://github.com/showdownjs/showdown/commit/f3b86f0))
* **CLI:flavor:** add flavor option to CLI ([2d6cd1e](https://github.com/showdownjs/showdown/commit/2d6cd1e))
* **getFlavor:** add getFlavor method to showdown and Converter ([0eaf105](https://github.com/showdownjs/showdown/commit/0eaf105))
* **ghMentions:** add support for github's @mentions ([f2671c0](https://github.com/showdownjs/showdown/commit/f2671c0)), closes [#51](https://github.com/showdownjs/showdown/issues/51)
### BREAKING CHANGES:
* CLI tool now uses the same option defaults as showdown main library. This mean
the default flavor is vanilla and ghCodeBlocks options is enabled by default.
To update, add `--ghCodeBlocks="false"` to the command.
<a name="1.5.5"></a>
## [1.5.5](https://github.com/showdownjs/showdown/compare/1.5.4...1.5.5) (2016-12-30)
### Features
* **ghCompatibleHeaderId:** generate header ids compatible with github ([db97a90](https://github.com/showdownjs/showdown/commit/db97a90)), closes [#320](https://github.com/showdownjs/showdown/issues/320) [#321](https://github.com/showdownjs/showdown/issues/321)
<a name="1.5.4"></a>
## [1.5.4](https://github.com/showdownjs/showdown/compare/1.5.3...1.5.4) (2016-12-21)
### Bug Fixes
* **horizontal rule:** revert backwards incompatibility change ([113f5f6](https://github.com/showdownjs/showdown/commit/113f5f6)), closes [#317](https://github.com/showdownjs/showdown/issues/317)
* **simpleLineBreaks:** fix simpleLineBreak option breaking lists html ([ed4c33f](https://github.com/showdownjs/showdown/commit/ed4c33f)), closes [#316](https://github.com/showdownjs/showdown/issues/316)
<a name="1.5.3"></a>
## [1.5.3](https://github.com/showdownjs/showdown/compare/1.5.2...1.5.3) (2016-12-19)
### Bug Fixes
* parser slowness with certain inputs ([da8fb53](https://github.com/showdownjs/showdown/commit/da8fb53)), closes [#315](https://github.com/showdownjs/showdown/issues/315)
### Features
* **requireSpaceBeforeHeadingText:** option to make space between `#` and header text mandatory ([5d19877](https://github.com/showdownjs/showdown/commit/5d19877)), closes [#277](https://github.com/showdownjs/showdown/issues/277)
<a name="1.5.2"></a>
## [1.5.2](https://github.com/showdownjs/showdown/compare/1.5.1...1.5.2) (2016-12-17)
### Bug Fixes
* **listeners:** fix listeners typo ([f0d25b7](https://github.com/showdownjs/showdown/commit/f0d25b7)), closes [#290](https://github.com/showdownjs/showdown/issues/290)
* **lists:** lines with mutiple dashes being parsed as multilists ([10b3410](https://github.com/showdownjs/showdown/commit/10b3410)), closes [#312](https://github.com/showdownjs/showdown/issues/312)
* **nbsp:** nbsp are replaced with simple spaces ([6e90f7c](https://github.com/showdownjs/showdown/commit/6e90f7c))
<a name="1.5.1"></a>
## [1.5.1](https://github.com/showdownjs/showdown/compare/1.5.0...1.5.1) (2016-12-01)
### Features
* **simpleLineBreaks:** option that parses linebreaks as <br />. This option enables linebreaks to always be treated as `<br />` tags
without needing to add spaces in front of the line, the same way GitHub does. ([0942b5e](https://github.com/showdownjs/showdown/commit/0942b5e)), closes [#206](https://github.com/showdownjs/showdown/issues/206)
* **excludeTrailingPunctuationFromURLs:** option that excludes trailing punctuation from auto linked URLs. ([d2fc2a0](https://github.com/showdownjs/showdown/commit/d2fc2a0)), closes [#266](https://github.com/showdownjs/showdown/issues/266) [#308](https://github.com/showdownjs/showdown/issues/308)
<a name="1.5.0"></a>
## [1.5.0](https://github.com/showdownjs/showdown/compare/1.4.4...1.5.0) (2016-11-11)
### Bug Fixes
* **lists:** enforce 4 space indentation in sublists ([d51be6e](https://github.com/showdownjs/showdown/commit/d51be6e))
* **lists:** fix sublists inconsistent behavior ([9cfe8b1](https://github.com/showdownjs/showdown/commit/9cfe8b1)), closes [#299](https://github.com/showdownjs/showdown/issues/299)
### Features
* **disableForced4SpacesIndentedSublists:** option that disables the requirement of indenting nested sublists by 4 spaces. The option is disabled by default ([0be39bc](https://github.com/showdownjs/showdown/commit/0be39bc))
### BREAKING CHANGES
* syntax for sublists is now more restrictive. Before, sublists SHOULD be indented by 4 spaces, but indenting at least 2 spaces would work.
Now, sublists MUST be indented 4 spaces or they won't work.
With this input:
```md
* one
* two
* three
```
Before (ouput):
```html
<ul>
<li>one
<ul>
<li>two
<ul><li>three</li></ul>
<li>
</ul>
</li>
<ul>
```
After (output):
```html
<ul>
<li>one</li>
<li>two
<ul><li>three</li></ul>
</li>
</ul>
```
To migrate either fix source md files or activate the option `disableForced4SpacesIndentedSublists`:
```md
showdown.setOption('disableForced4SpacesIndentedSublists', true);
```
<a name="1.4.4"></a>
## [1.4.4](https://github.com/showdownjs/showdown/compare/1.4.3...1.4.4) (2016-11-02)
### Bug Fixes
* make some regexes a bit faster and make tab char equivalent to 4 spaces ([b7e7560](https://github.com/showdownjs/showdown/commit/b7e7560))
* **double linebreaks:** fix double linebreaks in html output ([f97e072](https://github.com/showdownjs/showdown/commit/f97e072)), closes [#291](https://github.com/showdownjs/showdown/issues/291)
* **lists linebreaks:** fix lists linebreaks in html output ([2b813cd](https://github.com/showdownjs/showdown/commit/2b813cd)), closes [#291](https://github.com/showdownjs/showdown/issues/291)
* **parser:** fix issue with comments inside nested code blocks ([799abea](https://github.com/showdownjs/showdown/commit/799abea)), closes [#288](https://github.com/showdownjs/showdown/issues/288)
<a name="1.4.3"></a>
## [1.4.3](https://github.com/showdownjs/showdown/compare/1.4.2...1.4.3) (2016-08-19)
### Bug Fixes
* **bower:** fix sourceMappingURL errors in bower by including source ([9b5a233](https://github.com/showdownjs/showdown/commit/9b5a233)), closes [#200](https://github.com/showdownjs/showdown/issues/200)
* **comments:** Fix html comment parser ([238726c](https://github.com/showdownjs/showdown/commit/238726c)), closes [#276](https://github.com/showdownjs/showdown/issues/276)
* **ie8 compatibility:** Improve ie8 compatibility ([984942e](https://github.com/showdownjs/showdown/commit/984942e)), closes [#275](https://github.com/showdownjs/showdown/issues/275) [#271](https://github.com/showdownjs/showdown/issues/271)
* **simplifiedAutoLink:** fix simplified autolink to match GFM behavior ([0cc55b0](https://github.com/showdownjs/showdown/commit/0cc55b0)), closes [#284](https://github.com/showdownjs/showdown/issues/284) [#285](https://github.com/showdownjs/showdown/issues/285)
<a name="1.4.2"></a>
## [1.4.2](https://github.com/showdownjs/showdown/compare/1.4.1...1.4.2) (2016-06-21)
### Bug Fixes
* **image-parser:** fix ref style imgs after inline style imgs not parsing correctly ([73206b0](https://github.com/showdownjs/showdown/commit/73206b0)), closes [#261](https://github.com/showdownjs/showdown/issues/261)
* **tables:** add check for undefined on text due to failing to parse tables ([6e30a48](https://github.com/showdownjs/showdown/commit/6e30a48)), author [stewartmckee](https://github.com/stewartmckee), closes [#257](https://github.com/showdownjs/showdown/pull/247)
### Features
* **smart-indent-fix:** fix for es6 indentation problems ([261f127](https://github.com/showdownjs/showdown/commit/261f127)), closes [#259](https://github.com/showdownjs/showdown/issues/259)
<a name="1.4.1"></a>
## [1.4.1](https://github.com/showdownjs/showdown/compare/1.4.0...1.4.1) (2016-05-17)
### Bug Fixes
* **tables:** fix table heading separators requiring 3 dashes instead of 2 ([ddaacfc](https://github.com/showdownjs/showdown/commit/ddaacfc)), closes [#256](https://github.com/showdownjs/showdown/issues/256)
<a name="1.4.0"></a>
## [1.4.0](https://github.com/showdownjs/showdown/compare/1.3.0...1.4.0) (2016-05-13)
### Bug Fixes
* **hashHTMLBlock:** fix issue with html breaking markdown parsing ([2746949](https://github.com/showdownjs/showdown/commit/2746949)), closes [#220](https://github.com/showdownjs/showdown/issues/220)
* **HTMLParser:** fix code tags parsing ([71a5873](https://github.com/showdownjs/showdown/commit/71a5873)), closes [#231](https://github.com/showdownjs/showdown/issues/231)
* **HTMLParser:** fix ghCodeBlocks being parsed inside code tags ([7d0436d](https://github.com/showdownjs/showdown/commit/7d0436d)), closes [#229](https://github.com/showdownjs/showdown/issues/229)
* **strikethrough:** Fix strikethrough issue with escaped chars ([5669317](https://github.com/showdownjs/showdown/commit/5669317)), closes [#214](https://github.com/showdownjs/showdown/issues/214)
* **tables:** fix tables to match github's md spec ([f58f014](https://github.com/showdownjs/showdown/commit/f58f014)), closes [#230](https://github.com/showdownjs/showdown/issues/230)
### Features
* **markdown="1":** enable parsing markdown inside HTML blocks ([c97f1dc](https://github.com/showdownjs/showdown/commit/c97f1dc)), closes [#178](https://github.com/showdownjs/showdown/issues/178)
<a name="1.3.0"></a>
## [1.3.0](https://github.com/showdownjs/showdown/compare/1.2.3...1.3.0) (2015-10-19)
### Bug Fixes
* **literalMidWordUnderscores:** fix different behavior with asterisks ([e86aea8](https://github.com/showdownjs/showdown/commit/e86aea8)), closes [#198](https://github.com/showdownjs/showdown/issues/198)
* **simpleautolink:** fix mail simpleAutoLink to ignore urls with @ symbol ([8ebb25e](https://github.com/showdownjs/showdown/commit/8ebb25e)), closes [#204](https://github.com/showdownjs/showdown/issues/204)
### Features
* **eventDispatcher:** add an event dispatcher to converter ([2734326](https://github.com/showdownjs/showdown/commit/2734326))
* **hashHTMLSpans:** add support for hashing span elements ([3097bd4](https://github.com/showdownjs/showdown/commit/3097bd4)), closes [#196](https://github.com/showdownjs/showdown/issues/196) [#175](https://github.com/showdownjs/showdown/issues/175)
<a name"1.2.3"></a>
## [1.2.3](https://github.com/showdownjs/showdown/compare/1.2.2...1.2.3) (2015-08-27)
### Bug Fixes
* **blockGamut:** fix for headings inside blockquotes ([3df70624](http://github.com/showdownjs/showdown/commit/3df70624), closes [#191](http://github.com/showdownjs/showdown/issues/191))
* **blockQuote:** fix 'github style codeblocks' not being parsed inside 'blockquote' ([ed2cf595](http://github.com/showdownjs/showdown/commit/ed2cf595), closes [#192](http://github.com/showdownjs/showdown/issues/192))
* **simpleAutoLinks:** fix emails being treated as simple urls ([7dc3fb1d](http://github.com/showdownjs/showdown/commit/7dc3fb1d), closes [#187](http://github.com/showdownjs/showdown/issues/187))
* **tables:** fix md tables being parsed inside indented code blocks. ([50256233](http://github.com/showdownjs/showdown/commit/50256233), closes [#193](http://github.com/showdownjs/showdown/issues/193))
<a name"1.2.2"></a>
## [1.2.2](https://github.com/showdownjs/showdown/compare/1.2.1...1.2.2) (2015-08-02)
### Bug Fixes
* **lists:** fix github code blocks not being parsed inside lists ([7720c88b](http://github.com/showdownjs/showdown/commit/7720c88b), closes [#142](http://github.com/showdownjs/showdown/issues/142), [#183](http://github.com/showdownjs/showdown/issues/183), [#184](http://github.com/showdownjs/showdown/issues/184))
<a name"1.2.1"></a>
## [1.2.1](https://github.com/showdownjs/showdown/compare/1.2.0...1.2.1) (2015-07-22)
### Features
* **smoothLivePreview:** fix weird effects due to parsing incomplete input ([62ba3733](http://github.com/showdownjs/showdown/commit/62ba3733))
* **subParsers/githubCodeBlock:** add extra language class to conform to html5 spec ([b7f5e32](http://github.com/showdownjs/showdown/commit/b7f5e32))
### Bug Fixes
* **tables:**
* fix undefined error in malformed tables ([6176977](http://github.com/showdownjs/showdown/commit/6176977))
* add support for md span elements in table headers ([789dc18](http://github.com/showdownjs/showdown/commit/789dc18)), closes [#179](http://github.com/showdownjs/showdown/issues/179)
* **italicsAndBold:**
* fix broken em/strong tags when used with literalMidWordUnderscores ([7ee2017](http://github.com/showdownjs/showdown/commit/7ee2017)), closes [#179](http://github.com/showdownjs/showdown/issues/179)
* fix underscores not being correctly parsed when used in conjunction with literalMidWordsUnderscores option ([c9e85f1](http://github.com/showdownjs/showdown/commit/c9e85f1))
* **codeSpans:** Fix issue with code html tags not being correctly escaped ([5f043ca](http://github.com/showdownjs/showdown/commit/5f043ca))
* **images:** fix alt attribute not being escaped correctly ([542194e](http://github.com/showdownjs/showdown/commit/542194e))
<a name"1.2.0"></a>
## [1.2.0](https://github.com/showdownjs/showdown/compare/1.1.0...1.2.0) (2015-07-13)
This release moves some of the most popular extensions (such as table-extension and github-extension) to core.
Also introduces a simple cli tool that you can use to quickly convert markdown files into html.
### Bug Fixes
* **headerLevelStart:** fix for NaN error when specifying a non number as headerLevelStart param ([be72b487](http://github.com/showdownjs/showdown/commit/be72b487))
### Features
* **CLI:** simple cli tool (ALPHA) ([f6a33e40](http://github.com/showdownjs/showdown/commit/f6a33e40))
* **flavours:** add markdown presets/flavors ([7e55bceb](http://github.com/showdownjs/showdown/commit/7e55bceb), closes [#164](http://github.com/showdownjs/showdown/issues/164))
* **ghCodeBlocks:** add option to disable GH codeblocks ([c33f9888](http://github.com/showdownjs/showdown/commit/c33f9888))
* **literalMidWordUnderscores:** add support for GFM literal midword underscores ([0c0cd7db](http://github.com/showdownjs/showdown/commit/0c0cd7db))
* **simplifiedAutoLink:** add support for GFM autolinks ([cff02372](http://github.com/showdownjs/showdown/commit/cff02372))
* **strikethrough:** add support for GFM strikethrough ([43e9448d](http://github.com/showdownjs/showdown/commit/43e9448d))
* **tables:** add support for GFM tables ([3a924e3c](http://github.com/showdownjs/showdown/commit/3a924e3c))
* **tasklists:** add support for GFM tasklists ([dc72403a](http://github.com/showdownjs/showdown/commit/dc72403a))
<a name"1.1.0"></a>
## [1.1.0](https://github.com/showdownjs/showdown/compare/1.0.2...1.1.0) (2015-06-18)
### Bug Fixes
* **converter.js:** add error if the passed constructor argument is not an object ([d86ed450](http://github.com/showdownjs/showdown/commit/d86ed450))
* **output modifiers:** fix for output modifiers running twice ([dcbdc61e](http://github.com/showdownjs/showdown/commit/dcbdc61e))
### Features
* **headerLevelStart:** add support for setting the header starting level ([b84ac67d](http://github.com/showdownjs/showdown/commit/b84ac67d), closes [#69](http://github.com/showdownjs/showdown/issues/69))
* **image dimensions:** add support for setting image dimensions within markdown syntax ([af82c2b6](http://github.com/showdownjs/showdown/commit/af82c2b6), closes [#143](http://github.com/showdownjs/showdown/issues/143))
* **noHeaderId:** add option to suppress automatic generation of ids in headers ([7ac893e9](http://github.com/showdownjs/showdown/commit/7ac893e9))
* **showdown.getDefaultOptions:** add method to retrieve default global options keypairs ([2de53a7d](http://github.com/showdownjs/showdown/commit/2de53a7d))
### Breaking Changes
* Deprecates `showdown.extensions` property. To migrate, extensions should use the new method `showdown.extension(<ext name>, <extension>)` to register.
For more information on the new extension loading mechanism, please check the wiki pages.
([4ebd0caa](http://github.com/showdownjs/showdown/commit/4ebd0caa))
<a name"1.0.2"></a>
## [1.0.2](https://github.com/showdownjs/showdown/compare/1.0.1...1.0.2) (2015-05-28)
### Bug Fixes
* **Gruntfile.js** add missing comma in footer. This bug prevented concatenating other js scripts and libraries
with showdown([5315508](http://github.com/showdownjs/showdown/commit/5315508). Credits to Alexandre Courtiol.
<a name"1.0.1"></a>
## [1.0.1](https://github.com/showdownjs/showdown/compare/1.0.0...1.0.1) (2015-05-27)
### Bug Fixes
* **bower.json:** update bower.json main attribute to point to dist directory ([bc3a092f](http://github.com/showdownjs/showdown/commit/bc3a092f))
<a name"1.0.0"></a>
## [1.0.0](https://github.com/showdownjs/showdown/compare/0.3.4...1.0.0) (2015-05-27)
### Release Information
This is a major code refactor with some big changes such as:
- showdown.js file was split in several files, called sub-parsers. This should improve code maintainability.
- angular integration was removed from core and move to its own repository, similar to what was done with extensions
- A new extension registering system is on the "cooks" that should reduce errors when using extensions. The old mechanism
is kept so old extensions should be compatible.
### Bug Fixes
* **extensions:** support for old extension loading mechanism ([95ed7c68](http://github.com/showdownjs/showdown/commit/95ed7c68))
* **helpers:** fix wrong function call 'escapeCharacters' due to old strayed code ([18ba4e75](http://github.com/showdownjs/showdown/commit/18ba4e75))
* **showdown.js:**
- fix showdown extension loader ([a38c76d2](http://github.com/showdownjs/showdown/commit/a38c76d2)),
closes [#50](http://github.com/showdownjs/showdown/issues/50),[#56](http://github.com/showdownjs/showdown/issues/56),
[#104](http://github.com/showdownjs/showdown/issues/104), [#108](http://github.com/showdownjs/showdown/issues/108),
[#109](http://github.com/showdownjs/showdown/issues/109), [#111](http://github.com/showdownjs/showdown/issues/111),
[#118](http://github.com/showdownjs/showdown/issues/118), [#122](http://github.com/showdownjs/showdown/issues/122)
- add unique id prefix and suffix to headers ([c367a4b9](http://github.com/showdownjs/showdown/commit/c367a4b9), closes [#81](http://github.com/showdownjs/showdown/issues/81), [#82](http://github.com/showdownjs/showdown/issues/82))
* **options.omitExtraWLInCodeBlocks:** fix for options.omitExtraWLInCodeBlocks only applying in gitHub flavoured code b ([e6f40e19](http://github.com/showdownjs/showdown/commit/e6f40e19))
* **showdown:** fix for options merging into globalOptions ([ddd6011d](http://github.com/showdownjs/showdown/commit/ddd6011d), closes [#153](http://github.com/showdownjs/showdown/issues/153))
### Features
* **registerExtension():** new extension loading mechanism. Now extensions can be registered using this function.
The system, however, is not final and will probably be changed until the final version([0fd10cb] (http://github.com/showdownjs/showdown/commit/0fd10cb))
* **allowBlockIndents:** indented inline block elements can now be parsed as markdown ([f6326b84](http://github.com/showdownjs/showdown/commit/f6326b84))
* **omitExtraWLInCodeBlocks:** add option to omit extra newline at the end of codeblocks ([141e3f5](http://github.com/showdownjs/showdown/commit/141e3f5))
* **prefixHeaderId:** add options to prefix header ids to prevent id clash ([141e3f5](http://github.com/showdownjs/showdown/commit/141e3f5))
* **Converter.options:** add getOption(), setOption() and getOptions() to Converter object ([db6f79b0](http://github.com/showdownjs/showdown/commit/db6f79b0))
### Breaking Changes
* **NAMESPACE:** showdown's namespace changed.
To migrate your code you should update all references to `Showdown` with `showdown`.
* **Converter:** converter reference changed from `converter` to `Converter`.
To migrate you should update all references to `Showdown.converter` with `showdown.Converter`
* **angular:** angular integration was removed from core and now lives in it's own [repository](http://github.com/showdownjs/angular/).
If you're using angular integration, you should install ng-showdown. Ex: `bower install ng-showdown`
* **extensions:** showdown extensions were removed from core package and now live in their own repository. See the [project's github page](https://github.com/showdownjs) for available extensions

View file

@ -1,74 +0,0 @@
Contributing
============
If you wish to contribute please read the following quick guide.
# Issues (bug reporting)
Generally, bug reports should be in the following format:
1. Description (Brief description of the problem)
2. Input (input that is causing problems)
3. Expected Output (Output that is expected)
4. Actual Output (Actual showdown output)
ex:
**Description:**
Double asterisks do not parse as bold
**Input:**
hello **world**!
**Expected output:**
<p>hello <b>world</b>!
**Actual Output:**
<p>hello **world**!</p>
# Want a Feature?
You can request a new feature by submitting an issue. If you would like to implement a new feature feel free to issue a
Pull Request.
# Pull requests (PRs)
PRs are awesome. However, before you submit your pull request consider the following guidelines:
- Search GitHub for an open or closed Pull Request that relates to your submission. You don't want to duplicate effort.
- When issuing PRs that change code, make your changes in a new git branch based on develop:
```bash
git checkout -b my-fix-branch develop
```
- Run the full test suite before submitting and make sure all tests pass (obviously =P).
- Try to follow our [**coding style rules**](https://github.com/showdownjs/code-style/blob/master/README.md).
Breaking them prevents the PR to pass the tests.
- Refrain from fixing multiple issues in the same pull request. It's preferable to open multiple small PRs instead of one
hard to review big one. Also, don't reuse old forks (or PRs) to fix new issues.
- If the PR introduces a new feature or fixes an issue, please add the appropriate test case.
- We use commit notes to generate the changelog. It's extremely helpful if your commit messages adhere to the
[**AngularJS Git Commit Guidelines**](https://github.com/showdownjs/code-style/blob/master/README.md#commit-message-convention).
- If we suggest changes then:
- Make the required updates.
- Re-run the Angular test suite to ensure tests are still passing.
- Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
```bash
git rebase develop -i
git push origin my-fix-branch -f
```
- After your pull request is merged, you can safely delete your branch.
If you have time to contribute to this project, we feel obliged that you get credit for it.
These rules enable us to review your PR faster and will give you appropriate credit in your GitHub profile.
We thank you in advance for your contribution!
# Joining the team
We're looking for members to help maintaining Showdown.
Please see [this issue](https://github.com/showdownjs/showdown/issues/114) to express interest or comment on this note.

View file

@ -1,48 +0,0 @@
Credits
=======
- Showdown v1
* [Estevão Santos](https://github.com/tivie)
* [Pascal Deschênes](https://github.com/pdeschen)
- Showdown v0
* [Corey Innis](http://github.com/coreyti):<br/>
Original GitHub project maintainer
* [Remy Sharp](https://github.com/remy/):<br/>
CommonJS-compatibility and more
* [Konstantin Käfer](https://github.com/kkaefer/):<br/>
CommonJS packaging
* [Roger Braun](https://github.com/rogerbraun):<br/>
Github-style code blocks
* [Dominic Tarr](https://github.com/dominictarr):<br/>
Documentation
* [Cat Chen](https://github.com/CatChen):<br/>
Export fix
* [Titus Stone](https://github.com/tstone):<br/>
Mocha tests, extension mechanism, and bug fixes
* [Rob Sutherland](https://github.com/roberocity):<br/>
The idea that lead to extensions
* [Pavel Lang](https://github.com/langpavel):<br/>
Code cleanup
* [Ben Combee](https://github.com/unwiredben):<br/>
Regex optimization
* [Adam Backstrom](https://github.com/abackstrom):<br/>
WebKit bugfix
* [Pascal Deschênes](https://github.com/pdeschen):<br/>
Grunt support, extension fixes + additions, packaging improvements, documentation
* [Estevão Santos](https://github.com/tivie)<br/>
Bug fixing and late maintainer
* [Hannah Wolfe](https://github.com/ErisDS)<br/>
Bug fixes
* [Alexandre Courtiol](https://github.com/acourtiol)<br/>
Bug fixes and build optimization
* [Karthik Balakrishnan](https://github.com/torcellite)<br/>
Support for table alignment
* [rheber](https://github.com/rheber)<br/>
Cli
- Original Project
* [John Gruber](http://daringfireball.net/projects/markdown/)<br/>
Author of Markdown
* [John Fraser](http://attacklab.net/)<br/>
Author of Showdown

View file

@ -1,57 +0,0 @@
We would like to thank everyone that contributed to this library. If you find our library useful and wish to donate as well, you can do so [through patreon](https://www.patreon.com/showdownjs) or directly [through paypal](https://www.paypal.me/tiviesantos)!! Your contribution will be greatly appreciated.
# Sponsors
## Platinum Supporters
## Gold Supporters
## Silver Supporters
# Patron Supporters
## Awesome Supporter
## Cool Supporter
## Supporter
- Ricardo Jordão
- Tiago Silva
---
# One Time Donors
- [**Learn on demand Systems**](http://www.learnondemandsystems.com/) (1000$)
- **Nothing AG** (25€)
> Thank you for developing Showdown :)
- **Sam Huffman** (15$)
> Thanks for the great work on showdown.js! I've been looking for a good solution to serve wiki-like text to a browser and render as
HTML but nearly gave up after mixed success with wikitext. Your library gets me very close to where I want to be.
- **Maya Lekova** (10$)
> Great work with the showdown library! I just used it and it worked exactly the way I expected
(given a complex inline HTML inside the Markdown, which renders fine with other viewers).
The other libraries I've tried (markdown-it and marked) produced a lot of bogus output. Y
our library saved me at least half a day, thanks! Good luck :)
- **Lin Wang** (10$)
- **Walter Schnell** (10$)
- **ivanhjc** (5$)
- **Asbjørn Ulsberg** (5$)
> Thanks for the ShowdownJS support!
- **Juan Marcelo Russo** (1$)

View file

@ -1,549 +0,0 @@
![Showdown][sd-logo]
[![Build Status: Linux](https://travis-ci.org/showdownjs/showdown.svg?branch=master)](https://travis-ci.org/showdownjs/showdown)
[![Build Status: Windows](https://ci.appveyor.com/api/projects/status/github/showdownjs/showdown?branch=master&svg=true)](https://ci.appveyor.com/project/tivie/showdown/branch/master)
[![npm version](https://badge.fury.io/js/showdown.svg)](http://badge.fury.io/js/showdown)
[![Bower version](https://badge.fury.io/bo/showdown.svg)](http://badge.fury.io/bo/showdown)
[![Join the chat at https://gitter.im/showdownjs/showdown](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/showdownjs/showdown?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Greenkeeper badge](https://badges.greenkeeper.io/showdownjs/showdown.svg)](https://greenkeeper.io/)
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/tiviesantos)
------
Showdown is a Javascript Markdown to HTML converter, based on the original works by John Gruber.
Showdown can be used client side (in the browser) or server side (with NodeJs).
## Live DEMO
Check a live Demo here http://demo.showdownjs.com/
## [![Patreon](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/bePatron?u=11141581)
As you know, ShowdownJS is a free library and it will remain free forever. However, maintaining and improving the library costs time and money.
If you like our work and find our library useful, please donate through [patreon](https://www.patreon.com/showdownjs) or directly through [paypal](https://www.paypal.me/tiviesantos)!! Your contribution will be greatly appreciated and help me continue to develop this awesome library.
## License
Showdown 1.x is released under GPL 2.0
## Who uses Showdown (or a fork)
- [GoogleCloudPlatform](https://github.com/GoogleCloudPlatform)
- [Meteor](https://www.meteor.com/)
- [Stackexchange](http://stackexchange.com/) - forked as [PageDown](https://code.google.com/p/pagedown/)
- [docular](https://github.com/Vertafore/docular)
- [md-page](https://github.com/oscarmorrison/md-page)
- [and some others...](https://www.npmjs.com/browse/depended/showdown)
## Installation
### Download tarball
You can download the latest release tarball directly from [releases][releases]
### Bower
bower install showdown
### npm (server-side)
npm install showdown
### NuGet package
PM> Install-Package showdownjs
The NuGet Packages can be [found here](https://www.nuget.org/packages/showdownjs/).
### CDN
You can also use one of several CDNs available:
* github CDN
https://cdn.rawgit.com/showdownjs/showdown/<version tag>/dist/showdown.min.js
* cdnjs
https://cdnjs.cloudflare.com/ajax/libs/showdown/<version tag>/showdown.min.js
## Browser Compatibility
Showdown has been tested successfully with:
* Firefox 1.5 and 2.0
* Chrome 12.0
* Internet Explorer 6 and 7
* Safari 2.0.4
* Opera 8.54 and 9.10
* Netscape 8.1.2
* Konqueror 3.5.4
In theory, Showdown will work in any browser that supports ECMA 262 3rd Edition (JavaScript 1.5).
The converter itself might even work in things that aren't web browsers, like Acrobat. No promises.
## Node compatibility
Showdown has been tested with node 6, 8 and 10. However, it should work with previous versions, such as node 0.12.
## Legacy version
If you're looking for showdown v<1.0.0, you can find it in the [**legacy branch**][legacy-branch].
## Changelog
You can check the full [changelog][changelog]
## Extended documentation
Check our [wiki pages][wiki] for examples and a more in-depth documentation.
## Quick Example
### Node
**Markdown to HTML**
```js
var showdown = require('showdown'),
converter = new showdown.Converter(),
text = '# hello, markdown!',
html = converter.makeHtml(text);
```
**HTML to Markdown**
```js
var showdown = require('showdown'),
converter = new showdown.Converter(),
html = '<a href="https://patreon.com/showdownjs">Please Support us!</a>',
md = converter.makeMarkdown(text);
```
### Browser
```js
var converter = new showdown.Converter(),
html = converter.makeHtml('# hello, markdown!'),
md = converter.makeMd('<a href="https://patreon.com/showdownjs">Please Support us!</a>');
```
### Output
Both examples should output...
```html
<h1 id="hellomarkdown">hello, markdown!</h1>
```
```md
[Please Support us!](https://patreon.com/showdownjs)
```
## Options
You can change some of showdown's default behavior through options.
### Setting options
Options can be set:
#### Globally
Setting a "global" option affects all instances of showdown
```js
showdown.setOption('optionKey', 'value');
```
#### Locally
Setting a "local" option only affects the specified Converter object.
Local options can be set:
* **through the constructor**
```js
var converter = new showdown.Converter({optionKey: 'value'});
```
* **through the setOption() method**
```js
var converter = new showdown.Converter();
converter.setOption('optionKey', 'value');
```
### Getting an option
Showdown provides 2 methods (both local and global) to retrieve previous set options.
#### getOption()
```js
// Global
var myOption = showdown.getOption('optionKey');
//Local
var myOption = converter.getOption('optionKey');
```
#### getOptions()
```js
// Global
var showdownGlobalOptions = showdown.getOptions();
//Local
var thisConverterSpecificOptions = converter.getOptions();
```
### Retrieve the default options
You can get showdown's default options with:
```js
var defaultOptions = showdown.getDefaultOptions();
```
### Valid Options
* **omitExtraWLInCodeBlocks**: (boolean) [default false] Omit the trailing newline in a code block. Ex:
This:
```html
<code><pre>var foo = 'bar';
</pre></code>
```
Becomes this:
```html
<code><pre>var foo = 'bar';</pre></code>
```
* **noHeaderId**: (boolean) [default false] Disable the automatic generation of header ids.
Setting to true overrides **prefixHeaderId**
* **customizedHeaderId**: (boolean) [default false] Use text in curly braces as header id. **(since v1.7.0)**
Example:
```
## Sample header {real-id} will use real-id as id
```
* **ghCompatibleHeaderId**: (boolean) [default false] Generate header ids compatible with github style
(spaces are replaced with dashes and a bunch of non alphanumeric chars are removed) **(since v1.5.5)**
* **prefixHeaderId**: (string/boolean) [default false] Add a prefix to the generated header ids.
Passing a string will prefix that string to the header id. Setting to `true` will add a generic 'section' prefix.
* **rawPrefixHeaderId**: (boolean) [default false] Setting this option to true will prevent showdown from modifying the prefix.
This might result in malformed IDs (if, for instance, the " char is used in the prefix).
Has no effect if prefixHeaderId is set to false. **(since v 1.7.3)**
* **rawHeaderId**: (boolean) [default false] Remove only spaces, ' and " from generated header ids (including prefixes),
replacing them with dashes (-). WARNING: This might result in malformed ids **(since v1.7.3)**
* **parseImgDimensions**: (boolean) [default false] Enable support for setting image dimensions from within markdown syntax.
Examples:
```
![foo](foo.jpg =100x80) simple, assumes units are in px
![bar](bar.jpg =100x*) sets the height to "auto"
![baz](baz.jpg =80%x5em) Image with width of 80% and height of 5em
```
* **headerLevelStart**: (integer) [default 1] Set the header starting level. For instance, setting this to 3 means that
```md
# foo
```
will be parsed as
```html
<h3>foo</h3>
```
* **simplifiedAutoLink**: (boolean) [default false] Turning this option on will enable automatic linking to urls.
This means that:
```md
some text www.google.com
```
will be parsed as
```html
<p>some text <a href="www.google.com">www.google.com</a>
```
* **excludeTrailingPunctuationFromURLs**: (boolean) [default false] This option excludes trailing punctuation from autolinking urls.
Punctuation excluded: `. ! ? ( )`. Only applies if **simplifiedAutoLink** option is set to `true`.
```md
check this link www.google.com!
```
will be parsed as
```html
<p>check this link <a href="www.google.com">www.google.com</a>!</p>
```
* **literalMidWordUnderscores**: (boolean) [default false] Turning this on will stop showdown from interpreting
underscores in the middle of words as `<em>` and `<strong>` and instead treat them as literal underscores.
Example:
```md
some text with__underscores__in middle
```
will be parsed as
```html
<p>some text with__underscores__in middle</p>
```
* **literalMidWordAsterisks**: (boolean) [default false] Turning this on will stop showdown from interpreting asterisks
in the middle of words as `<em>` and `<strong>` and instead treat them as literal asterisks.
Example:
```md
some text with**underscores**in middle
```
will be parsed as
```html
<p>some text with**underscores**in middle</p>
```
* **strikethrough**: (boolean) [default false] Enable support for strikethrough syntax.
`~~strikethrough~~` as `<del>strikethrough</del>`
* **tables**: (boolean) [default false] Enable support for tables syntax. Example:
```md
| h1 | h2 | h3 |
|:------|:-------:|--------:|
| 100 | [a][1] | ![b][2] |
| *foo* | **bar** | ~~baz~~ |
```
See the wiki for more info
* **tablesHeaderId**: (boolean) [default false] If enabled adds an id property to table headers tags.
* **ghCodeBlocks**: (boolean) [default true] Enable support for GFM code block style.
* **tasklists**: (boolean) [default false] Enable support for GFM tasklists. Example:
```md
- [x] This task is done
- [ ] This is still pending
```
* **smoothLivePreview**: (boolean) [default false] Prevents weird effects in live previews due to incomplete input
* **smartIndentationFix**: (boolean) [default false] Tries to smartly fix indentation problems related to es6 template
strings in the midst of indented code.
* **disableForced4SpacesIndentedSublists**: (boolean) [default false] Disables the requirement of indenting sublists
by 4 spaces for them to be nested, effectively reverting to the old behavior where 2 or 3 spaces were enough.
**(since v1.5.0)**
* **simpleLineBreaks**: (boolean) [default false] Parses line breaks as <br> like GitHub does, without
needing 2 spaces at the end of the line **(since v1.5.1)**
```md
a line
wrapped in two
```
turns into:
```html
<p>a line<br>
wrapped in two</p>
```
* **requireSpaceBeforeHeadingText**: (boolean) [default false] Makes adding a space between `#` and the header text mandatory **(since v1.5.3)**
* **ghMentions**: (boolean) [default false] Enables github @mentions, which link to the username mentioned **(since v1.6.0)**
* **ghMentionsLink**: (string) [default `https://github.com/{u}`] Changes the link generated by @mentions.
Showdown will replace `{u}` with the username. Only applies if ghMentions option is enabled.
Example: `@tivie` with ghMentionsOption set to `//mysite.com/{u}/profile` will result in `<a href="//mysite.com/tivie/profile">@tivie</a>`
* **encodeEmails**: (boolean) [default true] Enable e-mail addresses encoding through the use of Character Entities, transforming ASCII e-mail addresses into its equivalent decimal entities. (since v1.6.1)
NOTE: Prior to version 1.6.1, emails would always be obfuscated through dec and hex encoding.
* **openLinksInNewWindow**: (boolean) [default false] Open all links in new windows
(by adding the attribute `target="_blank"` to `<a>` tags) **(since v1.7.0)**
* **backslashEscapesHTMLTags**: (boolean) [default false] Support for HTML Tag escaping. ex: `\<div>foo\</div>` **(since v1.7.2)**
* **emoji**: (boolean) [default false] Enable emoji support. Ex: `this is a :smile: emoji`
For more info on available emojis, see https://github.com/showdownjs/showdown/wiki/Emojis **(since v.1.8.0)**
* **underline**: (boolean) [default false] ***EXPERIMENTAL FEATURE*** Enable support for underline.
Syntax is **double** or **triple** **underscores** ex: `__underlined word__`. With this option enabled, underscores are no longer parses into `<em>` and `<strong>`.
* **completeHTMLDocument**: (boolean) [default false] Outputs a complete html document,
including `<html>`, `<head>` and `<body>` tags' instead of an HTML fragment. (since v.1.8.5)
* **metadata**: (boolean) [default false] Enable support for document metadata (defined at the top of the document
between `«««` and `»»»` or between `---` and `---`). (since v.1.8.5)
```js
var conv = new showdown.Converter({metadata: true});
var html = conv.makeHtml(someMd);
var metadata = conv.getMetadata(); // returns an object with the document metadata
```
* **splitAdjacentBlockquotes**: (boolean) [default false] Split adjacent blockquote blocks.(since v.1.8.6)
**NOTE**: Please note that until **version 1.6.0**, all of these options are ***DISABLED*** by default in the cli tool.
## Flavors
You can also use flavors or presets to set the correct options automatically, so that showdown behaves like popular markdown flavors.
Currently, the following flavors are available:
* original - original markdown flavor as in [John Gruber's spec](https://daringfireball.net/projects/markdown/)
* vanilla - showdown base flavor (as from v1.3.1)
* github - GFM (GitHub Flavored Markdown)
### Global
```javascript
showdown.setFlavor('github');
```
### Instance
```javascript
converter.setFlavor('github');
```
## CLI Tool
Showdown also comes bundled with a Command Line Interface tool. You can check the [CLI wiki page][cli-wiki] for more info
## Integration with AngularJS
ShowdownJS project also provides seamlessly integration with AngularJS via a "plugin".
Please visit https://github.com/showdownjs/ngShowdown for more information.
## Integration with TypeScript
If you're using TypeScript you maybe want to use the types from [DefinitelyTyped][definitely-typed]
## Integration with SystemJS/JSPM
Integration with SystemJS can be obtained via the third party ["system-md" plugin](https://github.com/guybedford/system-md).
## XSS vulnerability
Showdown doesn't sanitize the input. This is by design since markdown relies on it to allow certain features to be correctly parsed into HTML.
This, however, means XSS injection is quite possible.
Please refer to the wiki article [Markdown's XSS Vulnerability (and how to mitigate it)][xss-wiki]
for more information.
## Extensions
Showdown allows additional functionality to be loaded via extensions. (you can find a list of known showdown extensions [here][ext-wiki])
You can also find a boilerplate, to create your own extensions in [this repository][boilerplate-repo]
### Client-side Extension Usage
```html
<script src="showdown.js"></script>
<script src="twitter-extension.js"></script>
<script>
var converter = new showdown.Converter({ extensions: ['twitter'] });
</script>
```
### Server-side Extension Usage
```js
var showdown = require('showdown'),
myExtension = require('myExtension'),
converter = new showdown.Converter({ extensions: ['myExtension'] });
```
## Tests
A suite of tests is available which require node.js. Once node is installed, run the following command from
the project root to install the dependencies:
npm install
Once installed the tests can be run from the project root using:
npm test
New test cases can easily be added. Create a markdown file (ending in `.md`) which contains the markdown to test.
Create a `.html` file of the exact same name. It will automatically be tested when the tests are executed with `mocha`.
## Contributing
If you wish to contribute please read the following quick guide.
### Want a Feature?
You can request a new feature by submitting an issue. If you would like to implement a new feature feel free to issue a
Pull Request.
### Pull requests (PRs)
PRs are awesome. However, before you submit your pull request consider the following guidelines:
- Search GitHub for an open or closed Pull Request that relates to your submission. You don't want to duplicate effort.
- When issuing PRs that change code, make your changes in a new git branch based on master:
```bash
git checkout -b my-fix-branch master
```
- Documentation (i.e: README.md) changes can be made directly against master.
- Run the full test suite before submitting and make sure all tests pass (obviously =P).
- Try to follow our [**coding style rules**][coding-rules].
Breaking them prevents the PR to pass the tests.
- Refrain from fixing multiple issues in the same pull request. It's preferable to open multiple small PRs instead of one
hard to review big one.
- If the PR introduces a new feature or fixes an issue, please add the appropriate test case.
- We use commit notes to generate the changelog. It's extremely helpful if your commit messages adhere to the
[**AngularJS Git Commit Guidelines**][ng-commit-guide].
- If we suggest changes then:
- Make the required updates.
- Re-run the Angular test suite to ensure tests are still passing.
- Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
```bash
git rebase master -i
git push origin my-fix-branch -f
```
- After your pull request is merged, you can safely delete your branch.
If you have time to contribute to this project, we feel obliged that you get credit for it.
These rules enable us to review your PR faster and will give you appropriate credit in your GitHub profile.
We thank you in advance for your contribution!
### Joining the team
We're looking for members to help maintaining Showdown.
Please see [this issue](https://github.com/showdownjs/showdown/issues/114) to express interest or comment on this note.
## Credits
Full credit list at https://github.com/showdownjs/showdown/blob/master/CREDITS.md
Showdown is powered by:<br/>
[![webstorm](https://www.jetbrains.com/webstorm/documentation/docs/logo_webstorm.png)](https://www.jetbrains.com/webstorm/)
[sd-logo]: https://raw.githubusercontent.com/showdownjs/logo/master/dist/logo.readme.png
[legacy-branch]: https://github.com/showdownjs/showdown/tree/legacy
[releases]: https://github.com/showdownjs/showdown/releases
[changelog]: https://github.com/showdownjs/showdown/blob/master/CHANGELOG.md
[wiki]: https://github.com/showdownjs/showdown/wiki
[cli-wiki]: https://github.com/showdownjs/showdown/wiki/CLI-tool
[definitely-typed]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/showdown
[xss-wiki]: https://github.com/showdownjs/showdown/wiki/Markdown's-XSS-Vulnerability-(and-how-to-mitigate-it)
[ext-wiki]: https://github.com/showdownjs/showdown/wiki/extensions
[coding-rules]: https://github.com/showdownjs/code-style/blob/master/README.md
[ng-commit-guide]: https://github.com/showdownjs/code-style/blob/master/README.md#commit-message-convention
[boilerplate-repo]: https://github.com/showdownjs/extension-boilerplate

View file

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('../src/cli/cli');

View file

@ -1,32 +0,0 @@
{
"name": "showdown",
"description": "A Markdown to HTML converter written in Javascript",
"homepage": "https://github.com/showdownjs/showdown",
"authors": [
"Estevão Santos (https://github.com/tivie)",
"Pascal Deschênes (https://github.com/pdeschen)"
],
"main": ["dist/showdown.js"],
"ignore": [
".editorconfig",
".gitattributes",
".gitignore",
".jscs.json",
".jshintignore",
".jshintrc",
".travis.yml",
"Gruntfile.js",
"package.json",
"test/*"
],
"repository": {
"type": "git",
"url": "https://github.com/showdownjs/showdown.git"
},
"keywords": [
"markdown",
"md",
"mdown"
],
"license": "https://github.com/showdownjs/showdown/blob/master/license.txt"
}

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,34 +0,0 @@
Showdown Copyright (c) 2007, John Fraser
<http://www.attacklab.net/>
All rights reserved.
Original Markdown copyright (c) 2004, John Gruber
<http://daringfireball.net/>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name "Markdown" nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as
is" and any express or implied warranties, including, but not limited
to, the implied warranties of merchantability and fitness for a
particular purpose are disclaimed. In no event shall the copyright owner
or contributors be liable for any direct, indirect, incidental, special,
exemplary, or consequential damages (including, but not limited to,
procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including
negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.

File diff suppressed because it is too large Load diff

View file

@ -1,65 +0,0 @@
{
"name": "showdown",
"version": "1.9.0",
"description": "A Markdown to HTML converter written in Javascript",
"author": "Estevão Santos",
"homepage": "http://showdownjs.com/",
"keywords": [
"markdown",
"converter"
],
"contributors": [
"John Gruber",
"John Fraser",
"Corey Innis",
"Remy Sharp",
"Konstantin Käfer",
"Roger Braun",
"Dominic Tarr",
"Cat Chen",
"Titus Stone",
"Rob Sutherland",
"Pavel Lang",
"Ben Combee",
"Adam Backstrom",
"Pascal Deschênes",
"Estevão Santos"
],
"repository": {
"type": "git",
"url": "https://github.com/showdownjs/showdown.git",
"web": "https://github.com/showdownjs/showdown"
},
"license": "BSD-3-Clause",
"main": "./dist/showdown.js",
"scripts": {
"test": "grunt test"
},
"bin": {
"showdown": "bin/showdown.js"
},
"devDependencies": {
"chai": "^4.0.2",
"grunt": "^1.0.3",
"grunt-contrib-clean": "^1.0.0",
"grunt-contrib-concat": "^1.0.1",
"grunt-contrib-jshint": "^1.1.0",
"grunt-contrib-uglify": "^3.1.0",
"grunt-conventional-changelog": "^6.1.0",
"grunt-conventional-github-releaser": "^1.0.0",
"grunt-endline": "^0.6.1",
"grunt-eslint": "^19.0.0",
"grunt-simple-mocha": "^0.4.0",
"jsdom": "^13.0.0",
"load-grunt-tasks": "^3.2.0",
"performance-now": "^2.0.0",
"quiet-grunt": "^0.2.3",
"semver": "^5.4.1",
"semver-sort": "0.0.4",
"sinon": "^4.0.0",
"source-map-support": "^0.5.0"
},
"dependencies": {
"yargs": "^10.0.3"
}
}

View file

@ -1,45 +0,0 @@
/**
* Created by tivie
*/
'use strict';
var yargs = require('yargs');
yargs
.version()
.alias('v', 'version')
.option('h', {
alias: 'help',
description: 'Show help'
})
.option('q', {
alias: 'quiet',
description: 'Quiet mode. Only print errors',
type: 'boolean',
default: false
})
.option('m', {
alias: 'mute',
description: 'Mute mode. Does not print anything',
type: 'boolean',
default: false
})
.usage('Usage: showdown <command> [options]')
.demand(1, 'You must provide a valid command')
.command('makehtml', 'Converts markdown into html')
.example('showdown makehtml -i foo.md -o bar.html', 'Converts \'foo.md\' to \'bar.html\'')
.wrap(yargs.terminalWidth());
var argv = yargs.argv,
command = argv._[0];
if (command === 'makehtml') {
require('./makehtml.cmd.js').run();
} else {
yargs.showHelp();
}
if (argv.help) {
yargs.showHelp();
}
process.exit(0);

View file

@ -1,195 +0,0 @@
var yargs = require('yargs'),
fs = require('fs'),
Messenger = require('./messenger.js'),
showdown = require('../../dist/showdown'),
showdownOptions = showdown.getDefaultOptions(false);
yargs.reset()
.usage('Usage: showdown makehtml [options]')
.example('showdown makehtml -i', 'Reads from stdin and outputs to stdout')
.example('showdown makehtml -i foo.md -o bar.html', 'Reads \'foo.md\' and writes to \'bar.html\'')
.example('showdown makehtml -i --flavor="github"', 'Parses stdin using GFM style')
.version()
.alias('v', 'version')
.config('c')
.alias('c', 'config')
.help('h')
.alias('h', 'help')
.option('i', {
alias : 'input',
describe: 'Input source. Usually a md file. If omitted or empty, reads from stdin',
type: 'string'
})
.option('o', {
alias : 'output',
describe: 'Output target. Usually a html file. If omitted or empty, writes to stdout',
type: 'string',
default: false
})
.option('u', {
alias : 'encoding',
describe: 'Input encoding',
type: 'string'
})
.option('a', {
alias : 'append',
describe: 'Append data to output instead of overwriting',
type: 'string',
default: false
})
.option('e', {
alias : 'extensions',
describe: 'Load the specified extensions. Should be valid paths to node compatible extensions',
type: 'array'
})
.option('p', {
alias : 'flavor',
describe: 'Run with a predetermined flavor of options. Default is vanilla',
type: 'string'
})
.option('q', {
alias: 'quiet',
description: 'Quiet mode. Only print errors',
type: 'boolean',
default: false
})
.option('m', {
alias: 'mute',
description: 'Mute mode. Does not print anything',
type: 'boolean',
default: false
});
// load showdown default options
for (var opt in showdownOptions) {
if (showdownOptions.hasOwnProperty(opt)) {
if (showdownOptions[opt].defaultValue === false) {
showdownOptions[opt].default = null;
} else {
showdownOptions[opt].default = showdownOptions[opt].defaultValue;
}
yargs.option(opt, showdownOptions[opt]);
}
}
function run () {
'use strict';
var argv = yargs.argv,
readMode = (!argv.i || argv.i === '') ? 'stdin' : 'file',
writeMode = (!argv.o || argv.o === '') ? 'stdout' : 'file',
msgMode = (writeMode === 'file') ? 'stdout' : 'stderr',
/**
* MSG object
* @type {Messenger}
*/
messenger = new Messenger(msgMode, argv.q, argv.m),
read = (readMode === 'stdin') ? readFromStdIn : readFromFile,
write = (writeMode === 'stdout') ? writeToStdOut : writeToFile,
enc = argv.encoding || 'utf8',
flavor = argv.p,
append = argv.a || false,
options = parseOptions(flavor),
converter = new showdown.Converter(options),
md, html;
// Load extensions
if (argv.e) {
messenger.printMsg('Loading extensions');
for (var i = 0; i < argv.e.length; ++i) {
try {
var ext = require(argv.e[i]);
converter.addExtension(ext, argv.e[i]);
} catch (e) {
messenger.printError('Could not load extension ' + argv.e[i] + '. Reason:');
messenger.errorExit(e);
}
}
}
messenger.printMsg('...');
// read the input
messenger.printMsg('Reading data from ' + readMode + '...');
md = read(enc);
// process the input
messenger.printMsg('Parsing markdown...');
html = converter.makeHtml(md);
// write the output
messenger.printMsg('Writing data to ' + writeMode + '...');
write(html, append);
messenger.okExit();
function parseOptions (flavor) {
var options = {},
flavorOpts = showdown.getFlavorOptions(flavor) || {};
// if flavor is not undefined, let's tell the user we're loading that preset
if (flavor) {
messenger.printMsg('Loading ' + flavor + ' flavor.');
}
for (var opt in argv) {
if (argv.hasOwnProperty(opt)) {
// first we load the default options
if (showdownOptions.hasOwnProperty(opt) && showdownOptions[opt].default !== null) {
options[opt] = showdownOptions[opt].default;
}
// we now override defaults with flavor, if a flavor was indeed passed
if (flavorOpts.hasOwnProperty(opt)) {
options[opt] = flavorOpts[opt];
}
// lastly we override with explicit passed options
// being careful not to pass CLI specific options, such as -v, -h or --extensions
if (showdownOptions.hasOwnProperty(opt)) {
if (argv[opt] === true) {
messenger.printMsg('Enabling option ' + opt);
options[opt] = argv[opt];
} else if (argv[opt] === false) {
options[opt] = argv[opt];
}
}
}
}
return options;
}
function readFromStdIn () {
try {
var size = fs.fstatSync(process.stdin.fd).size;
return size > 0 ? fs.readSync(process.stdin.fd, size)[0] : '';
} catch (e) {
var err = new Error('Could not read from stdin, reason: ' + e.message);
messenger.errorExit(err);
}
}
function readFromFile (encoding) {
try {
return fs.readFileSync(argv.i, encoding);
} catch (err) {
messenger.errorExit(err);
}
}
function writeToStdOut (html) {
return process.stdout.write(html);
}
function writeToFile (html, append) {
// If a flag is passed, it means we should append instead of overwriting.
// Only works with files, obviously
var write = (append) ? fs.appendFileSync : fs.writeFileSync;
try {
write(argv.o, html);
} catch (err) {
messenger.errorExit(err);
}
}
}
module.exports = exports = {
run: run
};

View file

@ -1,40 +0,0 @@
function Messenger (writeMode, supress, mute) {
'use strict';
writeMode = writeMode || 'stderr';
supress = (!!supress || !!mute);
mute = !!mute;
this._print = (writeMode === 'stdout') ? console.log : console.error;
this.errorExit = function (e) {
if (!mute) {
console.error('ERROR: ' + e.message);
console.error('Run \'showdown <command> -h\' for help');
}
process.exit(1);
};
this.okExit = function () {
if (!mute) {
this._print('\n');
this._print('DONE!');
}
process.exit(0);
};
this.printMsg = function (msg) {
if (supress || mute || !msg) {
return;
}
this._print(msg);
};
this.printError = function (msg) {
if (mute) {
return;
}
console.error(msg);
};
}
module.exports = Messenger;

View file

@ -1,602 +0,0 @@
/**
* Created by Estevao on 31-05-2015.
*/
/**
* Showdown Converter class
* @class
* @param {object} [converterOptions]
* @returns {Converter}
*/
showdown.Converter = function (converterOptions) {
'use strict';
var
/**
* Options used by this converter
* @private
* @type {{}}
*/
options = {},
/**
* Language extensions used by this converter
* @private
* @type {Array}
*/
langExtensions = [],
/**
* Output modifiers extensions used by this converter
* @private
* @type {Array}
*/
outputModifiers = [],
/**
* Event listeners
* @private
* @type {{}}
*/
listeners = {},
/**
* The flavor set in this converter
*/
setConvFlavor = setFlavor,
/**
* Metadata of the document
* @type {{parsed: {}, raw: string, format: string}}
*/
metadata = {
parsed: {},
raw: '',
format: ''
};
_constructor();
/**
* Converter constructor
* @private
*/
function _constructor () {
converterOptions = converterOptions || {};
for (var gOpt in globalOptions) {
if (globalOptions.hasOwnProperty(gOpt)) {
options[gOpt] = globalOptions[gOpt];
}
}
// Merge options
if (typeof converterOptions === 'object') {
for (var opt in converterOptions) {
if (converterOptions.hasOwnProperty(opt)) {
options[opt] = converterOptions[opt];
}
}
} else {
throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +
' was passed instead.');
}
if (options.extensions) {
showdown.helper.forEach(options.extensions, _parseExtension);
}
}
/**
* Parse extension
* @param {*} ext
* @param {string} [name='']
* @private
*/
function _parseExtension (ext, name) {
name = name || null;
// If it's a string, the extension was previously loaded
if (showdown.helper.isString(ext)) {
ext = showdown.helper.stdExtName(ext);
name = ext;
// LEGACY_SUPPORT CODE
if (showdown.extensions[ext]) {
console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
'Please inform the developer that the extension should be updated!');
legacyExtensionLoading(showdown.extensions[ext], ext);
return;
// END LEGACY SUPPORT CODE
} else if (!showdown.helper.isUndefined(extensions[ext])) {
ext = extensions[ext];
} else {
throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
}
}
if (typeof ext === 'function') {
ext = ext();
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExt = validate(ext, name);
if (!validExt.valid) {
throw Error(validExt.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
}
if (ext[i].hasOwnProperty('listeners')) {
for (var ln in ext[i].listeners) {
if (ext[i].listeners.hasOwnProperty(ln)) {
listen(ln, ext[i].listeners[ln]);
}
}
}
}
}
/**
* LEGACY_SUPPORT
* @param {*} ext
* @param {string} name
*/
function legacyExtensionLoading (ext, name) {
if (typeof ext === 'function') {
ext = ext(new showdown.Converter());
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var valid = validate(ext, name);
if (!valid.valid) {
throw Error(valid.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
default:// should never reach here
throw Error('Extension loader error: Type unrecognized!!!');
}
}
}
/**
* Listen to an event
* @param {string} name
* @param {function} callback
*/
function listen (name, callback) {
if (!showdown.helper.isString(name)) {
throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');
}
if (typeof callback !== 'function') {
throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');
}
if (!listeners.hasOwnProperty(name)) {
listeners[name] = [];
}
listeners[name].push(callback);
}
function rTrimInputText (text) {
var rsp = text.match(/^\s*/)[0].length,
rgx = new RegExp('^\\s{0,' + rsp + '}', 'gm');
return text.replace(rgx, '');
}
/**
* Dispatch an event
* @private
* @param {string} evtName Event name
* @param {string} text Text
* @param {{}} options Converter Options
* @param {{}} globals
* @returns {string}
*/
this._dispatch = function dispatch (evtName, text, options, globals) {
if (listeners.hasOwnProperty(evtName)) {
for (var ei = 0; ei < listeners[evtName].length; ++ei) {
var nText = listeners[evtName][ei](evtName, text, this, options, globals);
if (nText && typeof nText !== 'undefined') {
text = nText;
}
}
}
return text;
};
/**
* Listen to an event
* @param {string} name
* @param {function} callback
* @returns {showdown.Converter}
*/
this.listen = function (name, callback) {
listen(name, callback);
return this;
};
/**
* Converts a markdown string into HTML
* @param {string} text
* @returns {*}
*/
this.makeHtml = function (text) {
//check if text is not falsy
if (!text) {
return text;
}
var globals = {
gHtmlBlocks: [],
gHtmlMdBlocks: [],
gHtmlSpans: [],
gUrls: {},
gTitles: {},
gDimensions: {},
gListLevel: 0,
hashLinkCounts: {},
langExtensions: langExtensions,
outputModifiers: outputModifiers,
converter: this,
ghCodeBlocks: [],
metadata: {
parsed: {},
raw: '',
format: ''
}
};
// This lets us use ¨ trema as an escape char to avoid md5 hashes
// The choice of character is arbitrary; anything that isn't
// magic in Markdown will work.
text = text.replace(/¨/g, '¨T');
// Replace $ with ¨D
// RegExp interprets $ as a special character
// when it's in a replacement string
text = text.replace(/\$/g, '¨D');
// Standardize line endings
text = text.replace(/\r\n/g, '\n'); // DOS to Unix
text = text.replace(/\r/g, '\n'); // Mac to Unix
// Stardardize line spaces
text = text.replace(/\u00A0/g, '&nbsp;');
if (options.smartIndentationFix) {
text = rTrimInputText(text);
}
// Make sure text begins and ends with a couple of newlines:
text = '\n\n' + text + '\n\n';
// detab
text = showdown.subParser('detab')(text, options, globals);
/**
* Strip any lines consisting only of spaces and tabs.
* This makes subsequent regexs easier to write, because we can
* match consecutive blank lines with /\n+/ instead of something
* contorted like /[ \t]*\n+/
*/
text = text.replace(/^[ \t]+$/mg, '');
//run languageExtensions
showdown.helper.forEach(langExtensions, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
// run the sub parsers
text = showdown.subParser('metadata')(text, options, globals);
text = showdown.subParser('hashPreCodeTags')(text, options, globals);
text = showdown.subParser('githubCodeBlocks')(text, options, globals);
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('hashCodeTags')(text, options, globals);
text = showdown.subParser('stripLinkDefinitions')(text, options, globals);
text = showdown.subParser('blockGamut')(text, options, globals);
text = showdown.subParser('unhashHTMLSpans')(text, options, globals);
text = showdown.subParser('unescapeSpecialChars')(text, options, globals);
// attacklab: Restore dollar signs
text = text.replace(/¨D/g, '$$');
// attacklab: Restore tremas
text = text.replace(/¨T/g, '¨');
// render a complete html document instead of a partial if the option is enabled
text = showdown.subParser('completeHTMLDocument')(text, options, globals);
// Run output modifiers
showdown.helper.forEach(outputModifiers, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
// update metadata
metadata = globals.metadata;
return text;
};
/**
* Converts an HTML string into a markdown string
* @param src
* @param [HTMLParser] A WHATWG DOM and HTML parser, such as JSDOM. If none is supplied, window.document will be used.
* @returns {string}
*/
this.makeMarkdown = this.makeMd = function (src, HTMLParser) {
// replace \r\n with \n
src = src.replace(/\r\n/g, '\n');
src = src.replace(/\r/g, '\n'); // old macs
// due to an edge case, we need to find this: > <
// to prevent removing of non silent white spaces
// ex: <em>this is</em> <strong>sparta</strong>
src = src.replace(/>[ \t]+</, '>¨NBSP;<');
if (!HTMLParser) {
if (window && window.document) {
HTMLParser = window.document;
} else {
throw new Error('HTMLParser is undefined. If in a webworker or nodejs environment, you need to provide a WHATWG DOM and HTML such as JSDOM');
}
}
var doc = HTMLParser.createElement('div');
doc.innerHTML = src;
var globals = {
preList: substitutePreCodeTags(doc)
};
// remove all newlines and collapse spaces
clean(doc);
// some stuff, like accidental reference links must now be escaped
// TODO
// doc.innerHTML = doc.innerHTML.replace(/\[[\S\t ]]/);
var nodes = doc.childNodes,
mdDoc = '';
for (var i = 0; i < nodes.length; i++) {
mdDoc += showdown.subParser('makeMarkdown.node')(nodes[i], globals);
}
function clean (node) {
for (var n = 0; n < node.childNodes.length; ++n) {
var child = node.childNodes[n];
if (child.nodeType === 3) {
if (!/\S/.test(child.nodeValue)) {
node.removeChild(child);
--n;
} else {
child.nodeValue = child.nodeValue.split('\n').join(' ');
child.nodeValue = child.nodeValue.replace(/(\s)+/g, '$1');
}
} else if (child.nodeType === 1) {
clean(child);
}
}
}
// find all pre tags and replace contents with placeholder
// we need this so that we can remove all indentation from html
// to ease up parsing
function substitutePreCodeTags (doc) {
var pres = doc.querySelectorAll('pre'),
presPH = [];
for (var i = 0; i < pres.length; ++i) {
if (pres[i].childElementCount === 1 && pres[i].firstChild.tagName.toLowerCase() === 'code') {
var content = pres[i].firstChild.innerHTML.trim(),
language = pres[i].firstChild.getAttribute('data-language') || '';
// if data-language attribute is not defined, then we look for class language-*
if (language === '') {
var classes = pres[i].firstChild.className.split(' ');
for (var c = 0; c < classes.length; ++c) {
var matches = classes[c].match(/^language-(.+)$/);
if (matches !== null) {
language = matches[1];
break;
}
}
}
// unescape html entities in content
content = showdown.helper.unescapeHTMLEntities(content);
presPH.push(content);
pres[i].outerHTML = '<precode language="' + language + '" precodenum="' + i.toString() + '"></precode>';
} else {
presPH.push(pres[i].innerHTML);
pres[i].innerHTML = '';
pres[i].setAttribute('prenum', i.toString());
}
}
return presPH;
}
return mdDoc;
};
/**
* Set an option of this Converter instance
* @param {string} key
* @param {*} value
*/
this.setOption = function (key, value) {
options[key] = value;
};
/**
* Get the option of this Converter instance
* @param {string} key
* @returns {*}
*/
this.getOption = function (key) {
return options[key];
};
/**
* Get the options of this Converter instance
* @returns {{}}
*/
this.getOptions = function () {
return options;
};
/**
* Add extension to THIS converter
* @param {{}} extension
* @param {string} [name=null]
*/
this.addExtension = function (extension, name) {
name = name || null;
_parseExtension(extension, name);
};
/**
* Use a global registered extension with THIS converter
* @param {string} extensionName Name of the previously registered extension
*/
this.useExtension = function (extensionName) {
_parseExtension(extensionName);
};
/**
* Set the flavor THIS converter should use
* @param {string} name
*/
this.setFlavor = function (name) {
if (!flavor.hasOwnProperty(name)) {
throw Error(name + ' flavor was not found');
}
var preset = flavor[name];
setConvFlavor = name;
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
options[option] = preset[option];
}
}
};
/**
* Get the currently set flavor of this converter
* @returns {string}
*/
this.getFlavor = function () {
return setConvFlavor;
};
/**
* Remove an extension from THIS converter.
* Note: This is a costly operation. It's better to initialize a new converter
* and specify the extensions you wish to use
* @param {Array} extension
*/
this.removeExtension = function (extension) {
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var a = 0; a < extension.length; ++a) {
var ext = extension[a];
for (var i = 0; i < langExtensions.length; ++i) {
if (langExtensions[i] === ext) {
langExtensions[i].splice(i, 1);
}
}
for (var ii = 0; ii < outputModifiers.length; ++i) {
if (outputModifiers[ii] === ext) {
outputModifiers[ii].splice(i, 1);
}
}
}
};
/**
* Get all extension of THIS converter
* @returns {{language: Array, output: Array}}
*/
this.getAllExtensions = function () {
return {
language: langExtensions,
output: outputModifiers
};
};
/**
* Get the metadata of the previously parsed document
* @param raw
* @returns {string|{}}
*/
this.getMetadata = function (raw) {
if (raw) {
return metadata.raw;
} else {
return metadata.parsed;
}
};
/**
* Get the metadata format of the previously parsed document
* @returns {string}
*/
this.getMetadataFormat = function () {
return metadata.format;
};
/**
* Private: set a single key, value metadata pair
* @param {string} key
* @param {string} value
*/
this._setMetadataPair = function (key, value) {
metadata.parsed[key] = value;
};
/**
* Private: set metadata format
* @param {string} format
*/
this._setMetadataFormat = function (format) {
metadata.format = format;
};
/**
* Private: set metadata raw text
* @param {string} raw
*/
this._setMetadataRaw = function (raw) {
metadata.raw = raw;
};
};

File diff suppressed because it is too large Load diff

View file

@ -1,17 +0,0 @@
var root = this;
// AMD Loader
if (typeof define === 'function' && define.amd) {
define(function () {
'use strict';
return showdown;
});
// CommonJS/nodeJS Loader
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = showdown;
// Regular Browser loader
} else {
root.showdown = showdown;
}

View file

@ -1,192 +0,0 @@
/**
* Created by Tivie on 13-07-2015.
*/
function getDefaultOpts (simple) {
'use strict';
var defaultOptions = {
omitExtraWLInCodeBlocks: {
defaultValue: false,
describe: 'Omit the default extra whiteline added to code blocks',
type: 'boolean'
},
noHeaderId: {
defaultValue: false,
describe: 'Turn on/off generated header id',
type: 'boolean'
},
prefixHeaderId: {
defaultValue: false,
describe: 'Add a prefix to the generated header ids. Passing a string will prefix that string to the header id. Setting to true will add a generic \'section-\' prefix',
type: 'string'
},
rawPrefixHeaderId: {
defaultValue: false,
describe: 'Setting this option to true will prevent showdown from modifying the prefix. This might result in malformed IDs (if, for instance, the " char is used in the prefix)',
type: 'boolean'
},
ghCompatibleHeaderId: {
defaultValue: false,
describe: 'Generate header ids compatible with github style (spaces are replaced with dashes, a bunch of non alphanumeric chars are removed)',
type: 'boolean'
},
rawHeaderId: {
defaultValue: false,
describe: 'Remove only spaces, \' and " from generated header ids (including prefixes), replacing them with dashes (-). WARNING: This might result in malformed ids',
type: 'boolean'
},
headerLevelStart: {
defaultValue: false,
describe: 'The header blocks level start',
type: 'integer'
},
parseImgDimensions: {
defaultValue: false,
describe: 'Turn on/off image dimension parsing',
type: 'boolean'
},
simplifiedAutoLink: {
defaultValue: false,
describe: 'Turn on/off GFM autolink style',
type: 'boolean'
},
excludeTrailingPunctuationFromURLs: {
defaultValue: false,
describe: 'Excludes trailing punctuation from links generated with autoLinking',
type: 'boolean'
},
literalMidWordUnderscores: {
defaultValue: false,
describe: 'Parse midword underscores as literal underscores',
type: 'boolean'
},
literalMidWordAsterisks: {
defaultValue: false,
describe: 'Parse midword asterisks as literal asterisks',
type: 'boolean'
},
strikethrough: {
defaultValue: false,
describe: 'Turn on/off strikethrough support',
type: 'boolean'
},
tables: {
defaultValue: false,
describe: 'Turn on/off tables support',
type: 'boolean'
},
tablesHeaderId: {
defaultValue: false,
describe: 'Add an id to table headers',
type: 'boolean'
},
ghCodeBlocks: {
defaultValue: true,
describe: 'Turn on/off GFM fenced code blocks support',
type: 'boolean'
},
tasklists: {
defaultValue: false,
describe: 'Turn on/off GFM tasklist support',
type: 'boolean'
},
smoothLivePreview: {
defaultValue: false,
describe: 'Prevents weird effects in live previews due to incomplete input',
type: 'boolean'
},
smartIndentationFix: {
defaultValue: false,
description: 'Tries to smartly fix indentation in es6 strings',
type: 'boolean'
},
disableForced4SpacesIndentedSublists: {
defaultValue: false,
description: 'Disables the requirement of indenting nested sublists by 4 spaces',
type: 'boolean'
},
simpleLineBreaks: {
defaultValue: false,
description: 'Parses simple line breaks as <br> (GFM Style)',
type: 'boolean'
},
requireSpaceBeforeHeadingText: {
defaultValue: false,
description: 'Makes adding a space between `#` and the header text mandatory (GFM Style)',
type: 'boolean'
},
ghMentions: {
defaultValue: false,
description: 'Enables github @mentions',
type: 'boolean'
},
ghMentionsLink: {
defaultValue: 'https://github.com/{u}',
description: 'Changes the link generated by @mentions. Only applies if ghMentions option is enabled.',
type: 'string'
},
encodeEmails: {
defaultValue: true,
description: 'Encode e-mail addresses through the use of Character Entities, transforming ASCII e-mail addresses into its equivalent decimal entities',
type: 'boolean'
},
openLinksInNewWindow: {
defaultValue: false,
description: 'Open all links in new windows',
type: 'boolean'
},
backslashEscapesHTMLTags: {
defaultValue: false,
description: 'Support for HTML Tag escaping. ex: \<div>foo\</div>',
type: 'boolean'
},
emoji: {
defaultValue: false,
description: 'Enable emoji support. Ex: `this is a :smile: emoji`',
type: 'boolean'
},
underline: {
defaultValue: false,
description: 'Enable support for underline. Syntax is double or triple underscores: `__underline word__`. With this option enabled, underscores no longer parses into `<em>` and `<strong>`',
type: 'boolean'
},
completeHTMLDocument: {
defaultValue: false,
description: 'Outputs a complete html document, including `<html>`, `<head>` and `<body>` tags',
type: 'boolean'
},
metadata: {
defaultValue: false,
description: 'Enable support for document metadata (defined at the top of the document between `«««` and `»»»` or between `---` and `---`).',
type: 'boolean'
},
splitAdjacentBlockquotes: {
defaultValue: false,
description: 'Split adjacent blockquote blocks',
type: 'boolean'
}
};
if (simple === false) {
return JSON.parse(JSON.stringify(defaultOptions));
}
var ret = {};
for (var opt in defaultOptions) {
if (defaultOptions.hasOwnProperty(opt)) {
ret[opt] = defaultOptions[opt].defaultValue;
}
}
return ret;
}
function allOptionsOn () {
'use strict';
var options = getDefaultOpts(true),
ret = {};
for (var opt in options) {
if (options.hasOwnProperty(opt)) {
ret[opt] = true;
}
}
return ret;
}

View file

@ -1,380 +0,0 @@
/**
* Created by Tivie on 06-01-2015.
*/
// Private properties
var showdown = {},
parsers = {},
extensions = {},
globalOptions = getDefaultOpts(true),
setFlavor = 'vanilla',
flavor = {
github: {
omitExtraWLInCodeBlocks: true,
simplifiedAutoLink: true,
excludeTrailingPunctuationFromURLs: true,
literalMidWordUnderscores: true,
strikethrough: true,
tables: true,
tablesHeaderId: true,
ghCodeBlocks: true,
tasklists: true,
disableForced4SpacesIndentedSublists: true,
simpleLineBreaks: true,
requireSpaceBeforeHeadingText: true,
ghCompatibleHeaderId: true,
ghMentions: true,
backslashEscapesHTMLTags: true,
emoji: true,
splitAdjacentBlockquotes: true
},
original: {
noHeaderId: true,
ghCodeBlocks: false
},
ghost: {
omitExtraWLInCodeBlocks: true,
parseImgDimensions: true,
simplifiedAutoLink: true,
excludeTrailingPunctuationFromURLs: true,
literalMidWordUnderscores: true,
strikethrough: true,
tables: true,
tablesHeaderId: true,
ghCodeBlocks: true,
tasklists: true,
smoothLivePreview: true,
simpleLineBreaks: true,
requireSpaceBeforeHeadingText: true,
ghMentions: false,
encodeEmails: true
},
vanilla: getDefaultOpts(true),
allOn: allOptionsOn()
};
/**
* helper namespace
* @type {{}}
*/
showdown.helper = {};
/**
* TODO LEGACY SUPPORT CODE
* @type {{}}
*/
showdown.extensions = {};
/**
* Set a global option
* @static
* @param {string} key
* @param {*} value
* @returns {showdown}
*/
showdown.setOption = function (key, value) {
'use strict';
globalOptions[key] = value;
return this;
};
/**
* Get a global option
* @static
* @param {string} key
* @returns {*}
*/
showdown.getOption = function (key) {
'use strict';
return globalOptions[key];
};
/**
* Get the global options
* @static
* @returns {{}}
*/
showdown.getOptions = function () {
'use strict';
return globalOptions;
};
/**
* Reset global options to the default values
* @static
*/
showdown.resetOptions = function () {
'use strict';
globalOptions = getDefaultOpts(true);
};
/**
* Set the flavor showdown should use as default
* @param {string} name
*/
showdown.setFlavor = function (name) {
'use strict';
if (!flavor.hasOwnProperty(name)) {
throw Error(name + ' flavor was not found');
}
showdown.resetOptions();
var preset = flavor[name];
setFlavor = name;
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
globalOptions[option] = preset[option];
}
}
};
/**
* Get the currently set flavor
* @returns {string}
*/
showdown.getFlavor = function () {
'use strict';
return setFlavor;
};
/**
* Get the options of a specified flavor. Returns undefined if the flavor was not found
* @param {string} name Name of the flavor
* @returns {{}|undefined}
*/
showdown.getFlavorOptions = function (name) {
'use strict';
if (flavor.hasOwnProperty(name)) {
return flavor[name];
}
};
/**
* Get the default options
* @static
* @param {boolean} [simple=true]
* @returns {{}}
*/
showdown.getDefaultOptions = function (simple) {
'use strict';
return getDefaultOpts(simple);
};
/**
* Get or set a subParser
*
* subParser(name) - Get a registered subParser
* subParser(name, func) - Register a subParser
* @static
* @param {string} name
* @param {function} [func]
* @returns {*}
*/
showdown.subParser = function (name, func) {
'use strict';
if (showdown.helper.isString(name)) {
if (typeof func !== 'undefined') {
parsers[name] = func;
} else {
if (parsers.hasOwnProperty(name)) {
return parsers[name];
} else {
throw Error('SubParser named ' + name + ' not registered!');
}
}
}
};
/**
* Gets or registers an extension
* @static
* @param {string} name
* @param {object|function=} ext
* @returns {*}
*/
showdown.extension = function (name, ext) {
'use strict';
if (!showdown.helper.isString(name)) {
throw Error('Extension \'name\' must be a string');
}
name = showdown.helper.stdExtName(name);
// Getter
if (showdown.helper.isUndefined(ext)) {
if (!extensions.hasOwnProperty(name)) {
throw Error('Extension named ' + name + ' is not registered!');
}
return extensions[name];
// Setter
} else {
// Expand extension if it's wrapped in a function
if (typeof ext === 'function') {
ext = ext();
}
// Ensure extension is an array
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExtension = validate(ext, name);
if (validExtension.valid) {
extensions[name] = ext;
} else {
throw Error(validExtension.error);
}
}
};
/**
* Gets all extensions registered
* @returns {{}}
*/
showdown.getAllExtensions = function () {
'use strict';
return extensions;
};
/**
* Remove an extension
* @param {string} name
*/
showdown.removeExtension = function (name) {
'use strict';
delete extensions[name];
};
/**
* Removes all extensions
*/
showdown.resetExtensions = function () {
'use strict';
extensions = {};
};
/**
* Validate extension
* @param {array} extension
* @param {string} name
* @returns {{valid: boolean, error: string}}
*/
function validate (extension, name) {
'use strict';
var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',
ret = {
valid: true,
error: ''
};
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var i = 0; i < extension.length; ++i) {
var baseMsg = errMsg + ' sub-extension ' + i + ': ',
ext = extension[i];
if (typeof ext !== 'object') {
ret.valid = false;
ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';
return ret;
}
if (!showdown.helper.isString(ext.type)) {
ret.valid = false;
ret.error = baseMsg + 'property "type" must be a string, but ' + typeof ext.type + ' given';
return ret;
}
var type = ext.type = ext.type.toLowerCase();
// normalize extension type
if (type === 'language') {
type = ext.type = 'lang';
}
if (type === 'html') {
type = ext.type = 'output';
}
if (type !== 'lang' && type !== 'output' && type !== 'listener') {
ret.valid = false;
ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: "lang/language", "output/html" or "listener"';
return ret;
}
if (type === 'listener') {
if (showdown.helper.isUndefined(ext.listeners)) {
ret.valid = false;
ret.error = baseMsg + '. Extensions of type "listener" must have a property called "listeners"';
return ret;
}
} else {
if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {
ret.valid = false;
ret.error = baseMsg + type + ' extensions must define either a "regex" property or a "filter" method';
return ret;
}
}
if (ext.listeners) {
if (typeof ext.listeners !== 'object') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an object but ' + typeof ext.listeners + ' given';
return ret;
}
for (var ln in ext.listeners) {
if (ext.listeners.hasOwnProperty(ln)) {
if (typeof ext.listeners[ln] !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an hash of [event name]: [callback]. listeners.' + ln +
' must be a function but ' + typeof ext.listeners[ln] + ' given';
return ret;
}
}
}
}
if (ext.filter) {
if (typeof ext.filter !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"filter" must be a function, but ' + typeof ext.filter + ' given';
return ret;
}
} else if (ext.regex) {
if (showdown.helper.isString(ext.regex)) {
ext.regex = new RegExp(ext.regex, 'g');
}
if (!(ext.regex instanceof RegExp)) {
ret.valid = false;
ret.error = baseMsg + '"regex" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';
return ret;
}
if (showdown.helper.isUndefined(ext.replace)) {
ret.valid = false;
ret.error = baseMsg + '"regex" extensions must implement a replace string or function';
return ret;
}
}
}
return ret;
}
/**
* Validate extension
* @param {object} ext
* @returns {boolean}
*/
showdown.validateExtension = function (ext) {
'use strict';
var validateExtension = validate(ext, null);
if (!validateExtension.valid) {
console.warn(validateExtension.error);
return false;
}
return true;
};

View file

@ -1,98 +0,0 @@
/**
* Turn Markdown link shortcuts into XHTML <a> tags.
*/
showdown.subParser('anchors', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('anchors.before', text, options, globals);
var writeAnchorTag = function (wholeMatch, linkText, linkId, url, m5, m6, title) {
if (showdown.helper.isUndefined(title)) {
title = '';
}
linkId = linkId.toLowerCase();
// Special case for explicit empty url
if (wholeMatch.search(/\(<?\s*>? ?(['"].*['"])?\)$/m) > -1) {
url = '';
} else if (!url) {
if (!linkId) {
// lower-case and turn embedded newlines into spaces
linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
url = globals.gUrls[linkId];
if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
title = globals.gTitles[linkId];
}
} else {
return wholeMatch;
}
}
//url = showdown.helper.escapeCharacters(url, '*_', false); // replaced line to improve performance
url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var result = '<a href="' + url + '"';
if (title !== '' && title !== null) {
title = title.replace(/"/g, '&quot;');
//title = showdown.helper.escapeCharacters(title, '*_', false); // replaced line to improve performance
title = title.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
result += ' title="' + title + '"';
}
// optionLinksInNewWindow only applies
// to external links. Hash links (#) open in same page
if (options.openLinksInNewWindow && !/^#/.test(url)) {
// escaped _
result += ' target="¨E95Eblank"';
}
result += '>' + linkText + '</a>';
return result;
};
// First, handle reference-style links: [link text] [id]
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)] ?(?:\n *)?\[(.*?)]()()()()/g, writeAnchorTag);
// Next, inline-style links: [link text](url "optional title")
// cases with crazy urls like ./image/cat1).png
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<([^>]*)>(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,
writeAnchorTag);
// normal cases
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<?([\S]+?(?:\([\S]*?\)[\S]*?)?)>?(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,
writeAnchorTag);
// handle reference-style shortcuts: [link text]
// These must come last in case you've also got [link test][1]
// or [link test](/foo)
text = text.replace(/\[([^\[\]]+)]()()()()()/g, writeAnchorTag);
// Lastly handle GithubMentions if option is enabled
if (options.ghMentions) {
text = text.replace(/(^|\s)(\\)?(@([a-z\d]+(?:[a-z\d.-]+?[a-z\d]+)*))/gmi, function (wm, st, escape, mentions, username) {
if (escape === '\\') {
return st + mentions;
}
//check if options.ghMentionsLink is a string
if (!showdown.helper.isString(options.ghMentionsLink)) {
throw new Error('ghMentionsLink option must be a string');
}
var lnk = options.ghMentionsLink.replace(/\{u}/g, username),
target = '';
if (options.openLinksInNewWindow) {
target = ' target="¨E95Eblank"';
}
return st + '<a href="' + lnk + '"' + target + '>' + mentions + '</a>';
});
}
text = globals.converter._dispatch('anchors.after', text, options, globals);
return text;
});

View file

@ -1,79 +0,0 @@
// url allowed chars [a-z\d_.~:/?#[]@!$&'()*+,;=-]
var simpleURLRegex = /([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+?\.[^'">\s]+?)()(\1)?(?=\s|$)(?!["<>])/gi,
simpleURLRegex2 = /([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+?)([.!?,()\[\]])?(\1)?(?=\s|$)(?!["<>])/gi,
delimUrlRegex = /()<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)()>()/gi,
simpleMailRegex = /(^|\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?=$|\s)/gmi,
delimMailRegex = /<()(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
replaceLink = function (options) {
'use strict';
return function (wm, leadingMagicChars, link, m2, m3, trailingPunctuation, trailingMagicChars) {
link = link.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var lnkTxt = link,
append = '',
target = '',
lmc = leadingMagicChars || '',
tmc = trailingMagicChars || '';
if (/^www\./i.test(link)) {
link = link.replace(/^www\./i, 'http://www.');
}
if (options.excludeTrailingPunctuationFromURLs && trailingPunctuation) {
append = trailingPunctuation;
}
if (options.openLinksInNewWindow) {
target = ' target="¨E95Eblank"';
}
return lmc + '<a href="' + link + '"' + target + '>' + lnkTxt + '</a>' + append + tmc;
};
},
replaceMail = function (options, globals) {
'use strict';
return function (wholeMatch, b, mail) {
var href = 'mailto:';
b = b || '';
mail = showdown.subParser('unescapeSpecialChars')(mail, options, globals);
if (options.encodeEmails) {
href = showdown.helper.encodeEmailAddress(href + mail);
mail = showdown.helper.encodeEmailAddress(mail);
} else {
href = href + mail;
}
return b + '<a href="' + href + '">' + mail + '</a>';
};
};
showdown.subParser('autoLinks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('autoLinks.before', text, options, globals);
text = text.replace(delimUrlRegex, replaceLink(options));
text = text.replace(delimMailRegex, replaceMail(options, globals));
text = globals.converter._dispatch('autoLinks.after', text, options, globals);
return text;
});
showdown.subParser('simplifiedAutoLinks', function (text, options, globals) {
'use strict';
if (!options.simplifiedAutoLink) {
return text;
}
text = globals.converter._dispatch('simplifiedAutoLinks.before', text, options, globals);
if (options.excludeTrailingPunctuationFromURLs) {
text = text.replace(simpleURLRegex2, replaceLink(options));
} else {
text = text.replace(simpleURLRegex, replaceLink(options));
}
text = text.replace(simpleMailRegex, replaceMail(options, globals));
text = globals.converter._dispatch('simplifiedAutoLinks.after', text, options, globals);
return text;
});

View file

@ -1,32 +0,0 @@
/**
* These are all the transformations that form block-level
* tags like paragraphs, headers, and list items.
*/
showdown.subParser('blockGamut', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('blockGamut.before', text, options, globals);
// we parse blockquotes first so that we can have headings and hrs
// inside blockquotes
text = showdown.subParser('blockQuotes')(text, options, globals);
text = showdown.subParser('headers')(text, options, globals);
// Do Horizontal Rules:
text = showdown.subParser('horizontalRule')(text, options, globals);
text = showdown.subParser('lists')(text, options, globals);
text = showdown.subParser('codeBlocks')(text, options, globals);
text = showdown.subParser('tables')(text, options, globals);
// We already ran _HashHTMLBlocks() before, in Markdown(), but that
// was to escape raw HTML in the original Markdown source. This time,
// we're escaping the markup we've just created, so that we don't wrap
// <p> tags around block-level tags.
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('paragraphs')(text, options, globals);
text = globals.converter._dispatch('blockGamut.after', text, options, globals);
return text;
});

View file

@ -1,42 +0,0 @@
showdown.subParser('blockQuotes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('blockQuotes.before', text, options, globals);
// add a couple extra lines after the text and endtext mark
text = text + '\n\n';
var rgx = /(^ {0,3}>[ \t]?.+\n(.+\n)*\n*)+/gm;
if (options.splitAdjacentBlockquotes) {
rgx = /^ {0,3}>[\s\S]*?(?:\n\n)/gm;
}
text = text.replace(rgx, function (bq) {
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
bq = bq.replace(/^[ \t]*>[ \t]?/gm, ''); // trim one level of quoting
// attacklab: clean up hack
bq = bq.replace(/¨0/g, '');
bq = bq.replace(/^[ \t]+$/gm, ''); // trim whitespace-only lines
bq = showdown.subParser('githubCodeBlocks')(bq, options, globals);
bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse
bq = bq.replace(/(^|\n)/g, '$1 ');
// These leading spaces screw with <pre> content, so we need to fix that:
bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) {
var pre = m1;
// attacklab: hack around Konqueror 3.5.4 bug:
pre = pre.replace(/^ /mg, '¨0');
pre = pre.replace(/¨0/g, '');
return pre;
});
return showdown.subParser('hashBlock')('<blockquote>\n' + bq + '\n</blockquote>', options, globals);
});
text = globals.converter._dispatch('blockQuotes.after', text, options, globals);
return text;
});

View file

@ -1,38 +0,0 @@
/**
* Process Markdown `<pre><code>` blocks.
*/
showdown.subParser('codeBlocks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('codeBlocks.before', text, options, globals);
// sentinel workarounds for lack of \A and \Z, safari\khtml bug
text += '¨0';
var pattern = /(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=¨0))/g;
text = text.replace(pattern, function (wholeMatch, m1, m2) {
var codeblock = m1,
nextChar = m2,
end = '\n';
codeblock = showdown.subParser('outdent')(codeblock, options, globals);
codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);
codeblock = showdown.subParser('detab')(codeblock, options, globals);
codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing newlines
if (options.omitExtraWLInCodeBlocks) {
end = '';
}
codeblock = '<pre><code>' + codeblock + end + '</code></pre>';
return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;
});
// strip sentinel
text = text.replace(/¨0/, '');
text = globals.converter._dispatch('codeBlocks.after', text, options, globals);
return text;
});

View file

@ -1,48 +0,0 @@
/**
*
* * Backtick quotes are used for <code></code> spans.
*
* * You can use multiple backticks as the delimiters if you want to
* include literal backticks in the code span. So, this input:
*
* Just type ``foo `bar` baz`` at the prompt.
*
* Will translate to:
*
* <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
*
* There's no arbitrary limit to the number of backticks you
* can use as delimters. If you need three consecutive backticks
* in your code, use four for delimiters, etc.
*
* * You can use spaces to get literal backticks at the edges:
*
* ... type `` `bar` `` ...
*
* Turns to:
*
* ... type <code>`bar`</code> ...
*/
showdown.subParser('codeSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('codeSpans.before', text, options, globals);
if (typeof(text) === 'undefined') {
text = '';
}
text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
function (wholeMatch, m1, m2, m3) {
var c = m3;
c = c.replace(/^([ \t]*)/g, ''); // leading whitespace
c = c.replace(/[ \t]*$/g, ''); // trailing whitespace
c = showdown.subParser('encodeCode')(c, options, globals);
c = m1 + '<code>' + c + '</code>';
c = showdown.subParser('hashHTMLSpans')(c, options, globals);
return c;
}
);
text = globals.converter._dispatch('codeSpans.after', text, options, globals);
return text;
});

View file

@ -1,62 +0,0 @@
/**
* Create a full HTML document from the processed markdown
*/
showdown.subParser('completeHTMLDocument', function (text, options, globals) {
'use strict';
if (!options.completeHTMLDocument) {
return text;
}
text = globals.converter._dispatch('completeHTMLDocument.before', text, options, globals);
var doctype = 'html',
doctypeParsed = '<!DOCTYPE HTML>\n',
title = '',
charset = '<meta charset="utf-8">\n',
lang = '',
metadata = '';
if (typeof globals.metadata.parsed.doctype !== 'undefined') {
doctypeParsed = '<!DOCTYPE ' + globals.metadata.parsed.doctype + '>\n';
doctype = globals.metadata.parsed.doctype.toString().toLowerCase();
if (doctype === 'html' || doctype === 'html5') {
charset = '<meta charset="utf-8">';
}
}
for (var meta in globals.metadata.parsed) {
if (globals.metadata.parsed.hasOwnProperty(meta)) {
switch (meta.toLowerCase()) {
case 'doctype':
break;
case 'title':
title = '<title>' + globals.metadata.parsed.title + '</title>\n';
break;
case 'charset':
if (doctype === 'html' || doctype === 'html5') {
charset = '<meta charset="' + globals.metadata.parsed.charset + '">\n';
} else {
charset = '<meta name="charset" content="' + globals.metadata.parsed.charset + '">\n';
}
break;
case 'language':
case 'lang':
lang = ' lang="' + globals.metadata.parsed[meta] + '"';
metadata += '<meta name="' + meta + '" content="' + globals.metadata.parsed[meta] + '">\n';
break;
default:
metadata += '<meta name="' + meta + '" content="' + globals.metadata.parsed[meta] + '">\n';
}
}
}
text = doctypeParsed + '<html' + lang + '>\n<head>\n' + title + charset + metadata + '</head>\n<body>\n' + text.trim() + '\n</body>\n</html>';
text = globals.converter._dispatch('completeHTMLDocument.after', text, options, globals);
return text;
});

View file

@ -1,33 +0,0 @@
/**
* Convert all tabs to spaces
*/
showdown.subParser('detab', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('detab.before', text, options, globals);
// expand first n-1 tabs
text = text.replace(/\t(?=\t)/g, ' '); // g_tab_width
// replace the nth with two sentinels
text = text.replace(/\t/g, '¨A¨B');
// use the sentinel to anchor our regex so it doesn't explode
text = text.replace(/¨B(.+?)¨A/g, function (wholeMatch, m1) {
var leadingText = m1,
numSpaces = 4 - leadingText.length % 4; // g_tab_width
// there *must* be a better way to do this:
for (var i = 0; i < numSpaces; i++) {
leadingText += ' ';
}
return leadingText;
});
// clean up sentinels
text = text.replace(/¨A/g, ' '); // g_tab_width
text = text.replace(/¨B/g, '');
text = globals.converter._dispatch('detab.after', text, options, globals);
return text;
});

View file

@ -1,11 +0,0 @@
showdown.subParser('ellipsis', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('ellipsis.before', text, options, globals);
text = text.replace(/\.\.\./g, '…');
text = globals.converter._dispatch('ellipsis.after', text, options, globals);
return text;
});

View file

@ -1,27 +0,0 @@
/**
* Turn emoji codes into emojis
*
* List of supported emojis: https://github.com/showdownjs/showdown/wiki/Emojis
*/
showdown.subParser('emoji', function (text, options, globals) {
'use strict';
if (!options.emoji) {
return text;
}
text = globals.converter._dispatch('emoji.before', text, options, globals);
var emojiRgx = /:([\S]+?):/g;
text = text.replace(emojiRgx, function (wm, emojiCode) {
if (showdown.helper.emojis.hasOwnProperty(emojiCode)) {
return showdown.helper.emojis[emojiCode];
}
return wm;
});
text = globals.converter._dispatch('emoji.after', text, options, globals);
return text;
});

View file

@ -1,23 +0,0 @@
/**
* Smart processing for ampersands and angle brackets that need to be encoded.
*/
showdown.subParser('encodeAmpsAndAngles', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('encodeAmpsAndAngles.before', text, options, globals);
// Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
// http://bumppo.net/projects/amputator/
text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&amp;');
// Encode naked <'s
text = text.replace(/<(?![a-z\/?$!])/gi, '&lt;');
// Encode <
text = text.replace(/</g, '&lt;');
// Encode >
text = text.replace(/>/g, '&gt;');
text = globals.converter._dispatch('encodeAmpsAndAngles.after', text, options, globals);
return text;
});

View file

@ -1,21 +0,0 @@
/**
* Returns the string, with after processing the following backslash escape sequences.
*
* attacklab: The polite way to do this is with the new escapeCharacters() function:
*
* text = escapeCharacters(text,"\\",true);
* text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
*
* ...but we're sidestepping its use of the (slow) RegExp constructor
* as an optimization for Firefox. This function gets called a LOT.
*/
showdown.subParser('encodeBackslashEscapes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('encodeBackslashEscapes.before', text, options, globals);
text = text.replace(/\\(\\)/g, showdown.helper.escapeCharactersCallback);
text = text.replace(/\\([`*_{}\[\]()>#+.!~=|-])/g, showdown.helper.escapeCharactersCallback);
text = globals.converter._dispatch('encodeBackslashEscapes.after', text, options, globals);
return text;
});

View file

@ -1,23 +0,0 @@
/**
* Encode/escape certain characters inside Markdown code runs.
* The point is that in code, these characters are literals,
* and lose their special Markdown meanings.
*/
showdown.subParser('encodeCode', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('encodeCode.before', text, options, globals);
// Encode all ampersands; HTML entities are not
// entities within a Markdown code span.
text = text
.replace(/&/g, '&amp;')
// Do the angle bracket song and dance:
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
// Now, escape characters that are magic in Markdown:
.replace(/([*_{}\[\]\\=~-])/g, showdown.helper.escapeCharactersCallback);
text = globals.converter._dispatch('encodeCode.after', text, options, globals);
return text;
});

View file

@ -1,26 +0,0 @@
/**
* Within tags -- meaning between < and > -- encode [\ ` * _ ~ =] so they
* don't conflict with their use in Markdown for code, italics and strong.
*/
showdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.before', text, options, globals);
// Build a regex to find HTML tags.
var tags = /<\/?[a-z\d_:-]+(?:[\s]+[\s\S]+?)?>/gi,
comments = /<!(--(?:(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>/gi;
text = text.replace(tags, function (wholeMatch) {
return wholeMatch
.replace(/(.)<\/?code>(?=.)/g, '$1`')
.replace(/([\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);
});
text = text.replace(comments, function (wholeMatch) {
return wholeMatch
.replace(/([\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);
});
text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.after', text, options, globals);
return text;
});

View file

@ -1,46 +0,0 @@
/**
* Handle github codeblocks prior to running HashHTML so that
* HTML contained within the codeblock gets escaped properly
* Example:
* ```ruby
* def hello_world(x)
* puts "Hello, #{x}"
* end
* ```
*/
showdown.subParser('githubCodeBlocks', function (text, options, globals) {
'use strict';
// early exit if option is not enabled
if (!options.ghCodeBlocks) {
return text;
}
text = globals.converter._dispatch('githubCodeBlocks.before', text, options, globals);
text += '¨0';
text = text.replace(/(?:^|\n)(?: {0,3})(```+|~~~+)(?: *)([^\s`~]*)\n([\s\S]*?)\n(?: {0,3})\1/g, function (wholeMatch, delim, language, codeblock) {
var end = (options.omitExtraWLInCodeBlocks) ? '' : '\n';
// First parse the github code block
codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);
codeblock = showdown.subParser('detab')(codeblock, options, globals);
codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
codeblock = showdown.subParser('hashBlock')(codeblock, options, globals);
// Since GHCodeblocks can be false positives, we need to
// store the primitive text and the parsed text in a global var,
// and then return a token
return '\n\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
});
// attacklab: strip sentinel
text = text.replace(/¨0/, '');
return globals.converter._dispatch('githubCodeBlocks.after', text, options, globals);
});

View file

@ -1,8 +0,0 @@
showdown.subParser('hashBlock', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashBlock.before', text, options, globals);
text = text.replace(/(^\n+|\n+$)/g, '');
text = '\n\n¨K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\n\n';
text = globals.converter._dispatch('hashBlock.after', text, options, globals);
return text;
});

View file

@ -1,18 +0,0 @@
/**
* Hash and escape <code> elements that should not be parsed as markdown
*/
showdown.subParser('hashCodeTags', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashCodeTags.before', text, options, globals);
var repFunc = function (wholeMatch, match, left, right) {
var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;
return '¨C' + (globals.gHtmlSpans.push(codeblock) - 1) + 'C';
};
// Hash naked <code>
text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '<code\\b[^>]*>', '</code>', 'gim');
text = globals.converter._dispatch('hashCodeTags.after', text, options, globals);
return text;
});

View file

@ -1,19 +0,0 @@
showdown.subParser('hashElement', function (text, options, globals) {
'use strict';
return function (wholeMatch, m1) {
var blockText = m1;
// Undo double lines
blockText = blockText.replace(/\n\n/g, '\n');
blockText = blockText.replace(/^\n/, '');
// strip trailing blank lines
blockText = blockText.replace(/\n+$/g, '');
// Replace the element text with a marker ("¨KxK" where x is its key)
blockText = '\n\n¨K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\n\n';
return blockText;
};
});

View file

@ -1,98 +0,0 @@
showdown.subParser('hashHTMLBlocks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashHTMLBlocks.before', text, options, globals);
var blockTags = [
'pre',
'div',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'table',
'dl',
'ol',
'ul',
'script',
'noscript',
'form',
'fieldset',
'iframe',
'math',
'style',
'section',
'header',
'footer',
'nav',
'article',
'aside',
'address',
'audio',
'canvas',
'figure',
'hgroup',
'output',
'video',
'p'
],
repFunc = function (wholeMatch, match, left, right) {
var txt = wholeMatch;
// check if this html element is marked as markdown
// if so, it's contents should be parsed as markdown
if (left.search(/\bmarkdown\b/) !== -1) {
txt = left + globals.converter.makeHtml(match) + right;
}
return '\n\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
};
if (options.backslashEscapesHTMLTags) {
// encode backslash escaped HTML tags
text = text.replace(/\\<(\/?[^>]+?)>/g, function (wm, inside) {
return '&lt;' + inside + '&gt;';
});
}
// hash HTML Blocks
for (var i = 0; i < blockTags.length; ++i) {
var opTagPos,
rgx1 = new RegExp('^ {0,3}(<' + blockTags[i] + '\\b[^>]*>)', 'im'),
patLeft = '<' + blockTags[i] + '\\b[^>]*>',
patRight = '</' + blockTags[i] + '>';
// 1. Look for the first position of the first opening HTML tag in the text
while ((opTagPos = showdown.helper.regexIndexOf(text, rgx1)) !== -1) {
// if the HTML tag is \ escaped, we need to escape it and break
//2. Split the text in that position
var subTexts = showdown.helper.splitAtIndex(text, opTagPos),
//3. Match recursively
newSubText1 = showdown.helper.replaceRecursiveRegExp(subTexts[1], repFunc, patLeft, patRight, 'im');
// prevent an infinite loop
if (newSubText1 === subTexts[1]) {
break;
}
text = subTexts[0].concat(newSubText1);
}
}
// HR SPECIAL CASE
text = text.replace(/(\n {0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,
showdown.subParser('hashElement')(text, options, globals));
// Special case for standalone HTML comments
text = showdown.helper.replaceRecursiveRegExp(text, function (txt) {
return '\n\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
}, '^ {0,3}<!--', '-->', 'gm');
// PHP and ASP-style processor instructions (<?...?> and <%...%>)
text = text.replace(/(?:\n\n)( {0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,
showdown.subParser('hashElement')(text, options, globals));
text = globals.converter._dispatch('hashHTMLBlocks.after', text, options, globals);
return text;
});

View file

@ -1,64 +0,0 @@
/**
* Hash span elements that should not be parsed as markdown
*/
showdown.subParser('hashHTMLSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashHTMLSpans.before', text, options, globals);
function hashHTMLSpan (html) {
return '¨C' + (globals.gHtmlSpans.push(html) - 1) + 'C';
}
// Hash Self Closing tags
text = text.replace(/<[^>]+?\/>/gi, function (wm) {
return hashHTMLSpan(wm);
});
// Hash tags without properties
text = text.replace(/<([^>]+?)>[\s\S]*?<\/\1>/g, function (wm) {
return hashHTMLSpan(wm);
});
// Hash tags with properties
text = text.replace(/<([^>]+?)\s[^>]+?>[\s\S]*?<\/\1>/g, function (wm) {
return hashHTMLSpan(wm);
});
// Hash self closing tags without />
text = text.replace(/<[^>]+?>/gi, function (wm) {
return hashHTMLSpan(wm);
});
/*showdown.helper.matchRecursiveRegExp(text, '<code\\b[^>]*>', '</code>', 'gi');*/
text = globals.converter._dispatch('hashHTMLSpans.after', text, options, globals);
return text;
});
/**
* Unhash HTML spans
*/
showdown.subParser('unhashHTMLSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('unhashHTMLSpans.before', text, options, globals);
for (var i = 0; i < globals.gHtmlSpans.length; ++i) {
var repText = globals.gHtmlSpans[i],
// limiter to prevent infinite loop (assume 10 as limit for recurse)
limit = 0;
while (/¨C(\d+)C/.test(repText)) {
var num = RegExp.$1;
repText = repText.replace('¨C' + num + 'C', globals.gHtmlSpans[num]);
if (limit === 10) {
console.error('maximum nesting of 10 spans reached!!!');
break;
}
++limit;
}
text = text.replace('¨C' + i + 'C', repText);
}
text = globals.converter._dispatch('unhashHTMLSpans.after', text, options, globals);
return text;
});

View file

@ -1,19 +0,0 @@
/**
* Hash and escape <pre><code> elements that should not be parsed as markdown
*/
showdown.subParser('hashPreCodeTags', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashPreCodeTags.before', text, options, globals);
var repFunc = function (wholeMatch, match, left, right) {
// encode html entities
var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;
return '\n\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
};
// Hash <pre><code>
text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^ {0,3}<pre\\b[^>]*>\\s*<code\\b[^>]*>', '^ {0,3}</code>\\s*</pre>', 'gim');
text = globals.converter._dispatch('hashPreCodeTags.after', text, options, globals);
return text;
});

View file

@ -1,126 +0,0 @@
showdown.subParser('headers', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('headers.before', text, options, globals);
var headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),
// Set text-style headers:
// Header 1
// ========
//
// Header 2
// --------
//
setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n={2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n=+[ \t]*\n+/gm,
setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n-+[ \t]*\n+/gm;
text = text.replace(setextRegexH1, function (wholeMatch, m1) {
var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
hLevel = headerLevelStart,
hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(hashBlock, options, globals);
});
text = text.replace(setextRegexH2, function (matchFound, m1) {
var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
hLevel = headerLevelStart + 1,
hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(hashBlock, options, globals);
});
// atx-style headers:
// # Header 1
// ## Header 2
// ## Header 2 with closing hashes ##
// ...
// ###### Header 6
//
var atxStyle = (options.requireSpaceBeforeHeadingText) ? /^(#{1,6})[ \t]+(.+?)[ \t]*#*\n+/gm : /^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm;
text = text.replace(atxStyle, function (wholeMatch, m1, m2) {
var hText = m2;
if (options.customizedHeaderId) {
hText = m2.replace(/\s?\{([^{]+?)}\s*$/, '');
}
var span = showdown.subParser('spanGamut')(hText, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m2) + '"',
hLevel = headerLevelStart - 1 + m1.length,
header = '<h' + hLevel + hID + '>' + span + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(header, options, globals);
});
function headerId (m) {
var title,
prefix;
// It is separate from other options to allow combining prefix and customized
if (options.customizedHeaderId) {
var match = m.match(/\{([^{]+?)}\s*$/);
if (match && match[1]) {
m = match[1];
}
}
title = m;
// Prefix id to prevent causing inadvertent pre-existing style matches.
if (showdown.helper.isString(options.prefixHeaderId)) {
prefix = options.prefixHeaderId;
} else if (options.prefixHeaderId === true) {
prefix = 'section-';
} else {
prefix = '';
}
if (!options.rawPrefixHeaderId) {
title = prefix + title;
}
if (options.ghCompatibleHeaderId) {
title = title
.replace(/ /g, '-')
// replace previously escaped chars (&, ¨ and $)
.replace(/&amp;/g, '')
.replace(/¨T/g, '')
.replace(/¨D/g, '')
// replace rest of the chars (&~$ are repeated as they might have been escaped)
// borrowed from github's redcarpet (some they should produce similar results)
.replace(/[&+$,\/:;=?@"#{}|^¨~\[\]`\\*)(%.!'<>]/g, '')
.toLowerCase();
} else if (options.rawHeaderId) {
title = title
.replace(/ /g, '-')
// replace previously escaped chars (&, ¨ and $)
.replace(/&amp;/g, '&')
.replace(/¨T/g, '¨')
.replace(/¨D/g, '$')
// replace " and '
.replace(/["']/g, '-')
.toLowerCase();
} else {
title = title
.replace(/[^\w]/g, '')
.toLowerCase();
}
if (options.rawPrefixHeaderId) {
title = prefix + title;
}
if (globals.hashLinkCounts[title]) {
title = title + '-' + (globals.hashLinkCounts[title]++);
} else {
globals.hashLinkCounts[title] = 1;
}
return title;
}
text = globals.converter._dispatch('headers.after', text, options, globals);
return text;
});

View file

@ -1,15 +0,0 @@
/**
* Turn Markdown link shortcuts into XHTML <a> tags.
*/
showdown.subParser('horizontalRule', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('horizontalRule.before', text, options, globals);
var key = showdown.subParser('hashBlock')('<hr />', options, globals);
text = text.replace(/^ {0,2}( ?-){3,}[ \t]*$/gm, key);
text = text.replace(/^ {0,2}( ?\*){3,}[ \t]*$/gm, key);
text = text.replace(/^ {0,2}( ?_){3,}[ \t]*$/gm, key);
text = globals.converter._dispatch('horizontalRule.after', text, options, globals);
return text;
});

View file

@ -1,104 +0,0 @@
/**
* Turn Markdown image shortcuts into <img> tags.
*/
showdown.subParser('images', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('images.before', text, options, globals);
var inlineRegExp = /!\[([^\]]*?)][ \t]*()\([ \t]?<?([\S]+?(?:\([\S]*?\)[\S]*?)?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,
crazyRegExp = /!\[([^\]]*?)][ \t]*()\([ \t]?<([^>]*)>(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(?:(["'])([^"]*?)\6))?[ \t]?\)/g,
base64RegExp = /!\[([^\]]*?)][ \t]*()\([ \t]?<?(data:.+?\/.+?;base64,[A-Za-z0-9+/=\n]+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,
referenceRegExp = /!\[([^\]]*?)] ?(?:\n *)?\[([\s\S]*?)]()()()()()/g,
refShortcutRegExp = /!\[([^\[\]]+)]()()()()()/g;
function writeImageTagBase64 (wholeMatch, altText, linkId, url, width, height, m5, title) {
url = url.replace(/\s/g, '');
return writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title);
}
function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
var gUrls = globals.gUrls,
gTitles = globals.gTitles,
gDims = globals.gDimensions;
linkId = linkId.toLowerCase();
if (!title) {
title = '';
}
// Special case for explicit empty url
if (wholeMatch.search(/\(<?\s*>? ?(['"].*['"])?\)$/m) > -1) {
url = '';
} else if (url === '' || url === null) {
if (linkId === '' || linkId === null) {
// lower-case and turn embedded newlines into spaces
linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(gUrls[linkId])) {
url = gUrls[linkId];
if (!showdown.helper.isUndefined(gTitles[linkId])) {
title = gTitles[linkId];
}
if (!showdown.helper.isUndefined(gDims[linkId])) {
width = gDims[linkId].width;
height = gDims[linkId].height;
}
} else {
return wholeMatch;
}
}
altText = altText
.replace(/"/g, '&quot;')
//altText = showdown.helper.escapeCharacters(altText, '*_', false);
.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
//url = showdown.helper.escapeCharacters(url, '*_', false);
url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var result = '<img src="' + url + '" alt="' + altText + '"';
if (title && showdown.helper.isString(title)) {
title = title
.replace(/"/g, '&quot;')
//title = showdown.helper.escapeCharacters(title, '*_', false);
.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
result += ' title="' + title + '"';
}
if (width && height) {
width = (width === '*') ? 'auto' : width;
height = (height === '*') ? 'auto' : height;
result += ' width="' + width + '"';
result += ' height="' + height + '"';
}
result += ' />';
return result;
}
// First, handle reference-style labeled images: ![alt text][id]
text = text.replace(referenceRegExp, writeImageTag);
// Next, handle inline images: ![alt text](url =<width>x<height> "optional title")
// base64 encoded images
text = text.replace(base64RegExp, writeImageTagBase64);
// cases with crazy urls like ./image/cat1).png
text = text.replace(crazyRegExp, writeImageTag);
// normal cases
text = text.replace(inlineRegExp, writeImageTag);
// handle reference-style shortcuts: ![img text]
text = text.replace(refShortcutRegExp, writeImageTag);
text = globals.converter._dispatch('images.after', text, options, globals);
return text;
});

View file

@ -1,70 +0,0 @@
showdown.subParser('italicsAndBold', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('italicsAndBold.before', text, options, globals);
// it's faster to have 3 separate regexes for each case than have just one
// because of backtracing, in some cases, it could lead to an exponential effect
// called "catastrophic backtrace". Ominous!
function parseInside (txt, left, right) {
/*
if (options.simplifiedAutoLink) {
txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);
}
*/
return left + txt + right;
}
// Parse underscores
if (options.literalMidWordUnderscores) {
text = text.replace(/\b___(\S[\s\S]*?)___\b/g, function (wm, txt) {
return parseInside (txt, '<strong><em>', '</em></strong>');
});
text = text.replace(/\b__(\S[\s\S]*?)__\b/g, function (wm, txt) {
return parseInside (txt, '<strong>', '</strong>');
});
text = text.replace(/\b_(\S[\s\S]*?)_\b/g, function (wm, txt) {
return parseInside (txt, '<em>', '</em>');
});
} else {
text = text.replace(/___(\S[\s\S]*?)___/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong><em>', '</em></strong>') : wm;
});
text = text.replace(/__(\S[\s\S]*?)__/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong>', '</strong>') : wm;
});
text = text.replace(/_([^\s_][\s\S]*?)_/g, function (wm, m) {
// !/^_[^_]/.test(m) - test if it doesn't start with __ (since it seems redundant, we removed it)
return (/\S$/.test(m)) ? parseInside (m, '<em>', '</em>') : wm;
});
}
// Now parse asterisks
if (options.literalMidWordAsterisks) {
text = text.replace(/([^*]|^)\B\*\*\*(\S[\s\S]*?)\*\*\*\B(?!\*)/g, function (wm, lead, txt) {
return parseInside (txt, lead + '<strong><em>', '</em></strong>');
});
text = text.replace(/([^*]|^)\B\*\*(\S[\s\S]*?)\*\*\B(?!\*)/g, function (wm, lead, txt) {
return parseInside (txt, lead + '<strong>', '</strong>');
});
text = text.replace(/([^*]|^)\B\*(\S[\s\S]*?)\*\B(?!\*)/g, function (wm, lead, txt) {
return parseInside (txt, lead + '<em>', '</em>');
});
} else {
text = text.replace(/\*\*\*(\S[\s\S]*?)\*\*\*/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong><em>', '</em></strong>') : wm;
});
text = text.replace(/\*\*(\S[\s\S]*?)\*\*/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong>', '</strong>') : wm;
});
text = text.replace(/\*([^\s*][\s\S]*?)\*/g, function (wm, m) {
// !/^\*[^*]/.test(m) - test if it doesn't start with ** (since it seems redundant, we removed it)
return (/\S$/.test(m)) ? parseInside (m, '<em>', '</em>') : wm;
});
}
text = globals.converter._dispatch('italicsAndBold.after', text, options, globals);
return text;
});

View file

@ -1,203 +0,0 @@
/**
* Form HTML ordered (numbered) and unordered (bulleted) lists.
*/
showdown.subParser('lists', function (text, options, globals) {
'use strict';
/**
* Process the contents of a single ordered or unordered list, splitting it
* into individual list items.
* @param {string} listStr
* @param {boolean} trimTrailing
* @returns {string}
*/
function processListItems (listStr, trimTrailing) {
// The $g_list_level global keeps track of when we're inside a list.
// Each time we enter a list, we increment it; when we leave a list,
// we decrement. If it's zero, we're not in a list anymore.
//
// We do this because when we're not inside a list, we want to treat
// something like this:
//
// I recommend upgrading to version
// 8. Oops, now this line is treated
// as a sub-list.
//
// As a single paragraph, despite the fact that the second line starts
// with a digit-period-space sequence.
//
// Whereas when we're inside a list (or sub-list), that line will be
// treated as the start of a sub-list. What a kludge, huh? This is
// an aspect of Markdown's syntax that's hard to parse perfectly
// without resorting to mind-reading. Perhaps the solution is to
// change the syntax rules such that sub-lists must start with a
// starting cardinal number; e.g. "1." or "a.".
globals.gListLevel++;
// trim trailing blank lines:
listStr = listStr.replace(/\n{2,}$/, '\n');
// attacklab: add sentinel to emulate \z
listStr += '¨0';
var rgx = /(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0| {0,3}([*+-]|\d+[.])[ \t]+))/gm,
isParagraphed = (/\n[ \t]*\n(?!¨0)/.test(listStr));
// Since version 1.5, nesting sublists requires 4 spaces (or 1 tab) indentation,
// which is a syntax breaking change
// activating this option reverts to old behavior
if (options.disableForced4SpacesIndentedSublists) {
rgx = /(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0|\2([*+-]|\d+[.])[ \t]+))/gm;
}
listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {
checked = (checked && checked.trim() !== '');
var item = showdown.subParser('outdent')(m4, options, globals),
bulletStyle = '';
// Support for github tasklists
if (taskbtn && options.tasklists) {
bulletStyle = ' class="task-list-item" style="list-style-type: none;"';
item = item.replace(/^[ \t]*\[(x|X| )?]/m, function () {
var otp = '<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';
if (checked) {
otp += ' checked';
}
otp += '>';
return otp;
});
}
// ISSUE #312
// This input: - - - a
// causes trouble to the parser, since it interprets it as:
// <ul><li><li><li>a</li></li></li></ul>
// instead of:
// <ul><li>- - a</li></ul>
// So, to prevent it, we will put a marker (¨A)in the beginning of the line
// Kind of hackish/monkey patching, but seems more effective than overcomplicating the list parser
item = item.replace(/^([-*+]|\d\.)[ \t]+[\S\n ]*/g, function (wm2) {
return '¨A' + wm2;
});
// m1 - Leading line or
// Has a double return (multi paragraph) or
// Has sublist
if (m1 || (item.search(/\n{2,}/) > -1)) {
item = showdown.subParser('githubCodeBlocks')(item, options, globals);
item = showdown.subParser('blockGamut')(item, options, globals);
} else {
// Recursion for sub-lists:
item = showdown.subParser('lists')(item, options, globals);
item = item.replace(/\n$/, ''); // chomp(item)
item = showdown.subParser('hashHTMLBlocks')(item, options, globals);
// Colapse double linebreaks
item = item.replace(/\n\n+/g, '\n\n');
if (isParagraphed) {
item = showdown.subParser('paragraphs')(item, options, globals);
} else {
item = showdown.subParser('spanGamut')(item, options, globals);
}
}
// now we need to remove the marker (¨A)
item = item.replace('¨A', '');
// we can finally wrap the line in list item tags
item = '<li' + bulletStyle + '>' + item + '</li>\n';
return item;
});
// attacklab: strip sentinel
listStr = listStr.replace(/¨0/g, '');
globals.gListLevel--;
if (trimTrailing) {
listStr = listStr.replace(/\s+$/, '');
}
return listStr;
}
function styleStartNumber (list, listType) {
// check if ol and starts by a number different than 1
if (listType === 'ol') {
var res = list.match(/^ *(\d+)\./);
if (res && res[1] !== '1') {
return ' start="' + res[1] + '"';
}
}
return '';
}
/**
* Check and parse consecutive lists (better fix for issue #142)
* @param {string} list
* @param {string} listType
* @param {boolean} trimTrailing
* @returns {string}
*/
function parseConsecutiveLists (list, listType, trimTrailing) {
// check if we caught 2 or more consecutive lists by mistake
// we use the counterRgx, meaning if listType is UL we look for OL and vice versa
var olRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?\d+\.[ \t]/gm : /^ {0,3}\d+\.[ \t]/gm,
ulRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?[*+-][ \t]/gm : /^ {0,3}[*+-][ \t]/gm,
counterRxg = (listType === 'ul') ? olRgx : ulRgx,
result = '';
if (list.search(counterRxg) !== -1) {
(function parseCL (txt) {
var pos = txt.search(counterRxg),
style = styleStartNumber(list, listType);
if (pos !== -1) {
// slice
result += '\n\n<' + listType + style + '>\n' + processListItems(txt.slice(0, pos), !!trimTrailing) + '</' + listType + '>\n';
// invert counterType and listType
listType = (listType === 'ul') ? 'ol' : 'ul';
counterRxg = (listType === 'ul') ? olRgx : ulRgx;
//recurse
parseCL(txt.slice(pos));
} else {
result += '\n\n<' + listType + style + '>\n' + processListItems(txt, !!trimTrailing) + '</' + listType + '>\n';
}
})(list);
} else {
var style = styleStartNumber(list, listType);
result = '\n\n<' + listType + style + '>\n' + processListItems(list, !!trimTrailing) + '</' + listType + '>\n';
}
return result;
}
/** Start of list parsing **/
text = globals.converter._dispatch('lists.before', text, options, globals);
// add sentinel to hack around khtml/safari bug:
// http://bugs.webkit.org/show_bug.cgi?id=11231
text += '¨0';
if (globals.gListLevel) {
text = text.replace(/^(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,
function (wholeMatch, list, m2) {
var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
return parseConsecutiveLists(list, listType, true);
}
);
} else {
text = text.replace(/(\n\n|^\n?)(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,
function (wholeMatch, m1, list, m3) {
var listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
return parseConsecutiveLists(list, listType, false);
}
);
}
// strip sentinel
text = text.replace(/¨0/, '');
text = globals.converter._dispatch('lists.after', text, options, globals);
return text;
});

View file

@ -1,22 +0,0 @@
showdown.subParser('makeMarkdown.blockquote', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
var innerTxt = showdown.subParser('makeMarkdown.node')(children[i], globals);
if (innerTxt === '') {
continue;
}
txt += innerTxt;
}
}
// cleanup
txt = txt.trim();
txt = '> ' + txt.split('\n').join('\n> ');
return txt;
});

View file

@ -1,7 +0,0 @@
showdown.subParser('makeMarkdown.codeBlock', function (node, globals) {
'use strict';
var lang = node.getAttribute('language'),
num = node.getAttribute('precodenum');
return '```' + lang + '\n' + globals.preList[num] + '\n```';
});

View file

@ -1,5 +0,0 @@
showdown.subParser('makeMarkdown.codeSpan', function (node) {
'use strict';
return '`' + node.innerHTML + '`';
});

View file

@ -1,15 +0,0 @@
showdown.subParser('makeMarkdown.emphasis', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
txt += '*';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '*';
}
return txt;
});

View file

@ -1,17 +0,0 @@
showdown.subParser('makeMarkdown.header', function (node, globals, headerLevel) {
'use strict';
var headerMark = new Array(headerLevel + 1).join('#'),
txt = '';
if (node.hasChildNodes()) {
txt = headerMark + ' ';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
}
return txt;
});

View file

@ -1,5 +0,0 @@
showdown.subParser('makeMarkdown.hr', function () {
'use strict';
return '---';
});

View file

@ -1,18 +0,0 @@
showdown.subParser('makeMarkdown.image', function (node) {
'use strict';
var txt = '';
if (node.hasAttribute('src')) {
txt += '![' + node.getAttribute('alt') + '](';
txt += '<' + node.getAttribute('src') + '>';
if (node.hasAttribute('width') && node.hasAttribute('height')) {
txt += ' =' + node.getAttribute('width') + 'x' + node.getAttribute('height');
}
if (node.hasAttribute('title')) {
txt += ' "' + node.getAttribute('title') + '"';
}
txt += ')';
}
return txt;
});

View file

@ -1,20 +0,0 @@
showdown.subParser('makeMarkdown.links', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes() && node.hasAttribute('href')) {
var children = node.childNodes,
childrenLength = children.length;
txt = '[';
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '](';
txt += '<' + node.getAttribute('href') + '>';
if (node.hasAttribute('title')) {
txt += ' "' + node.getAttribute('title') + '"';
}
txt += ')';
}
return txt;
});

View file

@ -1,33 +0,0 @@
showdown.subParser('makeMarkdown.list', function (node, globals, type) {
'use strict';
var txt = '';
if (!node.hasChildNodes()) {
return '';
}
var listItems = node.childNodes,
listItemsLenght = listItems.length,
listNum = node.getAttribute('start') || 1;
for (var i = 0; i < listItemsLenght; ++i) {
if (typeof listItems[i].tagName === 'undefined' || listItems[i].tagName.toLowerCase() !== 'li') {
continue;
}
// define the bullet to use in list
var bullet = '';
if (type === 'ol') {
bullet = listNum.toString() + '. ';
} else {
bullet = '- ';
}
// parse list item
txt += bullet + showdown.subParser('makeMarkdown.listItem')(listItems[i], globals);
++listNum;
}
// add comment at the end to prevent consecutive lists to be parsed as one
txt += '\n<!-- -->\n';
return txt.trim();
});

View file

@ -1,25 +0,0 @@
showdown.subParser('makeMarkdown.listItem', function (node, globals) {
'use strict';
var listItemTxt = '';
var children = node.childNodes,
childrenLenght = children.length;
for (var i = 0; i < childrenLenght; ++i) {
listItemTxt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
// if it's only one liner, we need to add a newline at the end
if (!/\n$/.test(listItemTxt)) {
listItemTxt += '\n';
} else {
// it's multiparagraph, so we need to indent
listItemTxt = listItemTxt
.split('\n')
.join('\n ')
.replace(/^ {4}$/gm, '')
.replace(/\n\n+/g, '\n\n');
}
return listItemTxt;
});

View file

@ -1,120 +0,0 @@
showdown.subParser('makeMarkdown.node', function (node, globals, spansOnly) {
'use strict';
spansOnly = spansOnly || false;
var txt = '';
// edge case of text without wrapper paragraph
if (node.nodeType === 3) {
return showdown.subParser('makeMarkdown.txt')(node, globals);
}
// HTML comment
if (node.nodeType === 8) {
return '<!--' + node.data + '-->\n\n';
}
// process only node elements
if (node.nodeType !== 1) {
return '';
}
var tagName = node.tagName.toLowerCase();
switch (tagName) {
//
// BLOCKS
//
case 'h1':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 1) + '\n\n'; }
break;
case 'h2':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 2) + '\n\n'; }
break;
case 'h3':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 3) + '\n\n'; }
break;
case 'h4':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 4) + '\n\n'; }
break;
case 'h5':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 5) + '\n\n'; }
break;
case 'h6':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 6) + '\n\n'; }
break;
case 'p':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.paragraph')(node, globals) + '\n\n'; }
break;
case 'blockquote':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.blockquote')(node, globals) + '\n\n'; }
break;
case 'hr':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.hr')(node, globals) + '\n\n'; }
break;
case 'ol':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ol') + '\n\n'; }
break;
case 'ul':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ul') + '\n\n'; }
break;
case 'precode':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.codeBlock')(node, globals) + '\n\n'; }
break;
case 'pre':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.pre')(node, globals) + '\n\n'; }
break;
case 'table':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.table')(node, globals) + '\n\n'; }
break;
//
// SPANS
//
case 'code':
txt = showdown.subParser('makeMarkdown.codeSpan')(node, globals);
break;
case 'em':
case 'i':
txt = showdown.subParser('makeMarkdown.emphasis')(node, globals);
break;
case 'strong':
case 'b':
txt = showdown.subParser('makeMarkdown.strong')(node, globals);
break;
case 'del':
txt = showdown.subParser('makeMarkdown.strikethrough')(node, globals);
break;
case 'a':
txt = showdown.subParser('makeMarkdown.links')(node, globals);
break;
case 'img':
txt = showdown.subParser('makeMarkdown.image')(node, globals);
break;
default:
txt = node.outerHTML + '\n\n';
}
// common normalization
// TODO eventually
return txt;
});

View file

@ -1,17 +0,0 @@
showdown.subParser('makeMarkdown.paragraph', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
}
// some text normalization
txt = txt.trim();
return txt;
});

View file

@ -1,6 +0,0 @@
showdown.subParser('makeMarkdown.pre', function (node, globals) {
'use strict';
var num = node.getAttribute('prenum');
return '<pre>' + globals.preList[num] + '</pre>';
});

View file

@ -1,15 +0,0 @@
showdown.subParser('makeMarkdown.strikethrough', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
txt += '~~';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '~~';
}
return txt;
});

View file

@ -1,15 +0,0 @@
showdown.subParser('makeMarkdown.strong', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
txt += '**';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '**';
}
return txt;
});

View file

@ -1,70 +0,0 @@
showdown.subParser('makeMarkdown.table', function (node, globals) {
'use strict';
var txt = '',
tableArray = [[], []],
headings = node.querySelectorAll('thead>tr>th'),
rows = node.querySelectorAll('tbody>tr'),
i, ii;
for (i = 0; i < headings.length; ++i) {
var headContent = showdown.subParser('makeMarkdown.tableCell')(headings[i], globals),
allign = '---';
if (headings[i].hasAttribute('style')) {
var style = headings[i].getAttribute('style').toLowerCase().replace(/\s/g, '');
switch (style) {
case 'text-align:left;':
allign = ':---';
break;
case 'text-align:right;':
allign = '---:';
break;
case 'text-align:center;':
allign = ':---:';
break;
}
}
tableArray[0][i] = headContent.trim();
tableArray[1][i] = allign;
}
for (i = 0; i < rows.length; ++i) {
var r = tableArray.push([]) - 1,
cols = rows[i].getElementsByTagName('td');
for (ii = 0; ii < headings.length; ++ii) {
var cellContent = ' ';
if (typeof cols[ii] !== 'undefined') {
cellContent = showdown.subParser('makeMarkdown.tableCell')(cols[ii], globals);
}
tableArray[r].push(cellContent);
}
}
var cellSpacesCount = 3;
for (i = 0; i < tableArray.length; ++i) {
for (ii = 0; ii < tableArray[i].length; ++ii) {
var strLen = tableArray[i][ii].length;
if (strLen > cellSpacesCount) {
cellSpacesCount = strLen;
}
}
}
for (i = 0; i < tableArray.length; ++i) {
for (ii = 0; ii < tableArray[i].length; ++ii) {
if (i === 1) {
if (tableArray[i][ii].slice(-1) === ':') {
tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii].slice(-1), cellSpacesCount - 1, '-') + ':';
} else {
tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount, '-');
}
} else {
tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount);
}
}
txt += '| ' + tableArray[i].join(' | ') + ' |\n';
}
return txt.trim();
});

View file

@ -1,15 +0,0 @@
showdown.subParser('makeMarkdown.tableCell', function (node, globals) {
'use strict';
var txt = '';
if (!node.hasChildNodes()) {
return '';
}
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals, true);
}
return txt.trim();
});

View file

@ -1,43 +0,0 @@
showdown.subParser('makeMarkdown.txt', function (node) {
'use strict';
var txt = node.nodeValue;
// multiple spaces are collapsed
txt = txt.replace(/ +/g, ' ');
// replace the custom ¨NBSP; with a space
txt = txt.replace(/¨NBSP;/g, ' ');
// ", <, > and & should replace escaped html entities
txt = showdown.helper.unescapeHTMLEntities(txt);
// escape markdown magic characters
// emphasis, strong and strikethrough - can appear everywhere
// we also escape pipe (|) because of tables
// and escape ` because of code blocks and spans
txt = txt.replace(/([*_~|`])/g, '\\$1');
// escape > because of blockquotes
txt = txt.replace(/^(\s*)>/g, '\\$1>');
// hash character, only troublesome at the beginning of a line because of headers
txt = txt.replace(/^#/gm, '\\#');
// horizontal rules
txt = txt.replace(/^(\s*)([-=]{3,})(\s*)$/, '$1\\$2$3');
// dot, because of ordered lists, only troublesome at the beginning of a line when preceded by an integer
txt = txt.replace(/^( {0,3}\d+)\./gm, '$1\\.');
// +, * and -, at the beginning of a line becomes a list, so we need to escape them also (asterisk was already escaped)
txt = txt.replace(/^( {0,3})([+-])/gm, '$1\\$2');
// images and links, ] followed by ( is problematic, so we escape it
txt = txt.replace(/]([\s]*)\(/g, '\\]$1\\(');
// reference URIs must also be escaped
txt = txt.replace(/^ {0,3}\[([\S \t]*?)]:/gm, '\\[$1]:');
return txt;
});

View file

@ -1,49 +0,0 @@
/**
* Parse metadata at the top of the document
*/
showdown.subParser('metadata', function (text, options, globals) {
'use strict';
if (!options.metadata) {
return text;
}
text = globals.converter._dispatch('metadata.before', text, options, globals);
function parseMetadataContents (content) {
// raw is raw so it's not changed in any way
globals.metadata.raw = content;
// escape chars forbidden in html attributes
// double quotes
content = content
// ampersand first
.replace(/&/g, '&amp;')
// double quotes
.replace(/"/g, '&quot;');
content = content.replace(/\n {4}/g, ' ');
content.replace(/^([\S ]+): +([\s\S]+?)$/gm, function (wm, key, value) {
globals.metadata.parsed[key] = value;
return '';
});
}
text = text.replace(/^\s*«««+(\S*?)\n([\s\S]+?)\n»»»+\n/, function (wholematch, format, content) {
parseMetadataContents(content);
return '¨M';
});
text = text.replace(/^\s*---+(\S*?)\n([\s\S]+?)\n---+\n/, function (wholematch, format, content) {
if (format) {
globals.metadata.format = format;
}
parseMetadataContents(content);
return '¨M';
});
text = text.replace(/¨M/g, '');
text = globals.converter._dispatch('metadata.after', text, options, globals);
return text;
});

View file

@ -1,17 +0,0 @@
/**
* Remove one level of line-leading tabs or spaces
*/
showdown.subParser('outdent', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('outdent.before', text, options, globals);
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
text = text.replace(/^(\t|[ ]{1,4})/gm, '¨0'); // attacklab: g_tab_width
// attacklab: clean up hack
text = text.replace(/¨0/g, '');
text = globals.converter._dispatch('outdent.after', text, options, globals);
return text;
});

View file

@ -1,70 +0,0 @@
/**
*
*/
showdown.subParser('paragraphs', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('paragraphs.before', text, options, globals);
// Strip leading and trailing lines:
text = text.replace(/^\n+/g, '');
text = text.replace(/\n+$/g, '');
var grafs = text.split(/\n{2,}/g),
grafsOut = [],
end = grafs.length; // Wrap <p> tags
for (var i = 0; i < end; i++) {
var str = grafs[i];
// if this is an HTML marker, copy it
if (str.search(/¨(K|G)(\d+)\1/g) >= 0) {
grafsOut.push(str);
// test for presence of characters to prevent empty lines being parsed
// as paragraphs (resulting in undesired extra empty paragraphs)
} else if (str.search(/\S/) >= 0) {
str = showdown.subParser('spanGamut')(str, options, globals);
str = str.replace(/^([ \t]*)/g, '<p>');
str += '</p>';
grafsOut.push(str);
}
}
/** Unhashify HTML blocks */
end = grafsOut.length;
for (i = 0; i < end; i++) {
var blockText = '',
grafsOutIt = grafsOut[i],
codeFlag = false;
// if this is a marker for an html block...
// use RegExp.test instead of string.search because of QML bug
while (/¨(K|G)(\d+)\1/.test(grafsOutIt)) {
var delim = RegExp.$1,
num = RegExp.$2;
if (delim === 'K') {
blockText = globals.gHtmlBlocks[num];
} else {
// we need to check if ghBlock is a false positive
if (codeFlag) {
// use encoded version of all text
blockText = showdown.subParser('encodeCode')(globals.ghCodeBlocks[num].text, options, globals);
} else {
blockText = globals.ghCodeBlocks[num].codeblock;
}
}
blockText = blockText.replace(/\$/g, '$$$$'); // Escape any dollar signs
grafsOutIt = grafsOutIt.replace(/(\n\n)?¨(K|G)\d+\2(\n\n)?/, blockText);
// Check if grafsOutIt is a pre->code
if (/^<pre\b[^>]*>\s*<code\b[^>]*>/.test(grafsOutIt)) {
codeFlag = true;
}
}
grafsOut[i] = grafsOutIt;
}
text = grafsOut.join('\n');
// Strip leading and trailing lines:
text = text.replace(/^\n+/g, '');
text = text.replace(/\n+$/g, '');
return globals.converter._dispatch('paragraphs.after', text, options, globals);
});

View file

@ -1,20 +0,0 @@
/**
* Run extension
*/
showdown.subParser('runExtension', function (ext, text, options, globals) {
'use strict';
if (ext.filter) {
text = ext.filter(text, globals.converter, options);
} else if (ext.regex) {
// TODO remove this when old extension loading mechanism is deprecated
var re = ext.regex;
if (!(re instanceof RegExp)) {
re = new RegExp(re, 'g');
}
text = text.replace(re, ext.replace);
}
return text;
});

View file

@ -1,49 +0,0 @@
/**
* These are all the transformations that occur *within* block-level
* tags like paragraphs, headers, and list items.
*/
showdown.subParser('spanGamut', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('spanGamut.before', text, options, globals);
text = showdown.subParser('codeSpans')(text, options, globals);
text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);
text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);
// Process anchor and image tags. Images must come first,
// because ![foo][f] looks like an anchor.
text = showdown.subParser('images')(text, options, globals);
text = showdown.subParser('anchors')(text, options, globals);
// Make links out of things like `<http://example.com/>`
// Must come after anchors, because you can use < and >
// delimiters in inline links like [this](<url>).
text = showdown.subParser('autoLinks')(text, options, globals);
text = showdown.subParser('simplifiedAutoLinks')(text, options, globals);
text = showdown.subParser('emoji')(text, options, globals);
text = showdown.subParser('underline')(text, options, globals);
text = showdown.subParser('italicsAndBold')(text, options, globals);
text = showdown.subParser('strikethrough')(text, options, globals);
text = showdown.subParser('ellipsis')(text, options, globals);
// we need to hash HTML tags inside spans
text = showdown.subParser('hashHTMLSpans')(text, options, globals);
// now we encode amps and angles
text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);
// Do hard breaks
if (options.simpleLineBreaks) {
// GFM style hard breaks
// only add line breaks if the text does not contain a block (special case for lists)
if (!/\n\n¨K/.test(text)) {
text = text.replace(/\n+/g, '<br />\n');
}
} else {
// Vanilla hard breaks
text = text.replace(/ +\n/g, '<br />\n');
}
text = globals.converter._dispatch('spanGamut.after', text, options, globals);
return text;
});

View file

@ -1,18 +0,0 @@
showdown.subParser('strikethrough', function (text, options, globals) {
'use strict';
function parseInside (txt) {
if (options.simplifiedAutoLink) {
txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);
}
return '<del>' + txt + '</del>';
}
if (options.strikethrough) {
text = globals.converter._dispatch('strikethrough.before', text, options, globals);
text = text.replace(/(?:~){2}([\s\S]+?)(?:~){2}/g, function (wm, txt) { return parseInside(txt); });
text = globals.converter._dispatch('strikethrough.after', text, options, globals);
}
return text;
});

View file

@ -1,53 +0,0 @@
/**
* Strips link definitions from text, stores the URLs and titles in
* hash references.
* Link defs are in the form: ^[id]: url "optional title"
*/
showdown.subParser('stripLinkDefinitions', function (text, options, globals) {
'use strict';
var regex = /^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*<?([^>\s]+)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n+|(?=¨0))/gm,
base64Regex = /^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*<?(data:.+?\/.+?;base64,[A-Za-z0-9+/=\n]+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n\n|(?=¨0)|(?=\n\[))/gm;
// attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
text += '¨0';
var replaceFunc = function (wholeMatch, linkId, url, width, height, blankLines, title) {
linkId = linkId.toLowerCase();
if (url.match(/^data:.+?\/.+?;base64,/)) {
// remove newlines
globals.gUrls[linkId] = url.replace(/\s/g, '');
} else {
globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url, options, globals); // Link IDs are case-insensitive
}
if (blankLines) {
// Oops, found blank lines, so it's not a title.
// Put back the parenthetical statement we stole.
return blankLines + title;
} else {
if (title) {
globals.gTitles[linkId] = title.replace(/"|'/g, '&quot;');
}
if (options.parseImgDimensions && width && height) {
globals.gDimensions[linkId] = {
width: width,
height: height
};
}
}
// Completely remove the definition from the text
return '';
};
// first we try to find base64 link references
text = text.replace(base64Regex, replaceFunc);
text = text.replace(regex, replaceFunc);
// attacklab: strip sentinel
text = text.replace(/¨0/, '');
return text;
});

View file

@ -1,142 +0,0 @@
showdown.subParser('tables', function (text, options, globals) {
'use strict';
if (!options.tables) {
return text;
}
var tableRgx = /^ {0,3}\|?.+\|.+\n {0,3}\|?[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*:?[ \t]*(?:[-=]){2,}[\s\S]+?(?:\n\n|¨0)/gm,
//singeColTblRgx = /^ {0,3}\|.+\|\n {0,3}\|[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*\n(?: {0,3}\|.+\|\n)+(?:\n\n|¨0)/gm;
singeColTblRgx = /^ {0,3}\|.+\|[ \t]*\n {0,3}\|[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*\n( {0,3}\|.+\|[ \t]*\n)*(?:\n|¨0)/gm;
function parseStyles (sLine) {
if (/^:[ \t]*--*$/.test(sLine)) {
return ' style="text-align:left;"';
} else if (/^--*[ \t]*:[ \t]*$/.test(sLine)) {
return ' style="text-align:right;"';
} else if (/^:[ \t]*--*[ \t]*:$/.test(sLine)) {
return ' style="text-align:center;"';
} else {
return '';
}
}
function parseHeaders (header, style) {
var id = '';
header = header.trim();
// support both tablesHeaderId and tableHeaderId due to error in documentation so we don't break backwards compatibility
if (options.tablesHeaderId || options.tableHeaderId) {
id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"';
}
header = showdown.subParser('spanGamut')(header, options, globals);
return '<th' + id + style + '>' + header + '</th>\n';
}
function parseCells (cell, style) {
var subText = showdown.subParser('spanGamut')(cell, options, globals);
return '<td' + style + '>' + subText + '</td>\n';
}
function buildTable (headers, cells) {
var tb = '<table>\n<thead>\n<tr>\n',
tblLgn = headers.length;
for (var i = 0; i < tblLgn; ++i) {
tb += headers[i];
}
tb += '</tr>\n</thead>\n<tbody>\n';
for (i = 0; i < cells.length; ++i) {
tb += '<tr>\n';
for (var ii = 0; ii < tblLgn; ++ii) {
tb += cells[i][ii];
}
tb += '</tr>\n';
}
tb += '</tbody>\n</table>\n';
return tb;
}
function parseTable (rawTable) {
var i, tableLines = rawTable.split('\n');
for (i = 0; i < tableLines.length; ++i) {
// strip wrong first and last column if wrapped tables are used
if (/^ {0,3}\|/.test(tableLines[i])) {
tableLines[i] = tableLines[i].replace(/^ {0,3}\|/, '');
}
if (/\|[ \t]*$/.test(tableLines[i])) {
tableLines[i] = tableLines[i].replace(/\|[ \t]*$/, '');
}
// parse code spans first, but we only support one line code spans
tableLines[i] = showdown.subParser('codeSpans')(tableLines[i], options, globals);
}
var rawHeaders = tableLines[0].split('|').map(function (s) { return s.trim();}),
rawStyles = tableLines[1].split('|').map(function (s) { return s.trim();}),
rawCells = [],
headers = [],
styles = [],
cells = [];
tableLines.shift();
tableLines.shift();
for (i = 0; i < tableLines.length; ++i) {
if (tableLines[i].trim() === '') {
continue;
}
rawCells.push(
tableLines[i]
.split('|')
.map(function (s) {
return s.trim();
})
);
}
if (rawHeaders.length < rawStyles.length) {
return rawTable;
}
for (i = 0; i < rawStyles.length; ++i) {
styles.push(parseStyles(rawStyles[i]));
}
for (i = 0; i < rawHeaders.length; ++i) {
if (showdown.helper.isUndefined(styles[i])) {
styles[i] = '';
}
headers.push(parseHeaders(rawHeaders[i], styles[i]));
}
for (i = 0; i < rawCells.length; ++i) {
var row = [];
for (var ii = 0; ii < headers.length; ++ii) {
if (showdown.helper.isUndefined(rawCells[i][ii])) {
}
row.push(parseCells(rawCells[i][ii], styles[ii]));
}
cells.push(row);
}
return buildTable(headers, cells);
}
text = globals.converter._dispatch('tables.before', text, options, globals);
// find escaped pipe characters
text = text.replace(/\\(\|)/g, showdown.helper.escapeCharactersCallback);
// parse multi column tables
text = text.replace(tableRgx, parseTable);
// parse one column tables
text = text.replace(singeColTblRgx, parseTable);
text = globals.converter._dispatch('tables.after', text, options, globals);
return text;
});

View file

@ -1,32 +0,0 @@
showdown.subParser('underline', function (text, options, globals) {
'use strict';
if (!options.underline) {
return text;
}
text = globals.converter._dispatch('underline.before', text, options, globals);
if (options.literalMidWordUnderscores) {
text = text.replace(/\b___(\S[\s\S]*?)___\b/g, function (wm, txt) {
return '<u>' + txt + '</u>';
});
text = text.replace(/\b__(\S[\s\S]*?)__\b/g, function (wm, txt) {
return '<u>' + txt + '</u>';
});
} else {
text = text.replace(/___(\S[\s\S]*?)___/g, function (wm, m) {
return (/\S$/.test(m)) ? '<u>' + m + '</u>' : wm;
});
text = text.replace(/__(\S[\s\S]*?)__/g, function (wm, m) {
return (/\S$/.test(m)) ? '<u>' + m + '</u>' : wm;
});
}
// escape remaining underscores to prevent them being parsed by italic and bold
text = text.replace(/(_)/g, showdown.helper.escapeCharactersCallback);
text = globals.converter._dispatch('underline.after', text, options, globals);
return text;
});

View file

@ -1,15 +0,0 @@
/**
* Swap back in all the special characters we've hidden.
*/
showdown.subParser('unescapeSpecialChars', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('unescapeSpecialChars.before', text, options, globals);
text = text.replace(/¨E(\d+)E/g, function (wholeMatch, m1) {
var charCodeToReplace = parseInt(m1);
return String.fromCharCode(charCodeToReplace);
});
text = globals.converter._dispatch('unescapeSpecialChars.after', text, options, globals);
return text;
});

View file

@ -1,4 +1,4 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
Page {

View file

@ -1,22 +1,34 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
import Nemo.Notifications 1.0
Dialog {
id: page
id: editDialog
property int id
property var note
onAccepted: {
api.updateNote(note.id, { 'category': categoryField.text, 'content': contentArea.text, 'favorite': favoriteButton.selected } )
onIdChanged: note = notesModel.getNoteById(id)
onNoteChanged: {
dialogHeader.title = note["title"]
contentArea.text = note["content"]
favoriteButton.selected = note["favorite"]
categoryField.text = note["category"]
modifiedDetail.modified = note["modified"]
//parseContent()
}
onStatusChanged: {
if (status === PageStatus.Active) {
//note = api.getNote(note.id, false)
favoriteButton.selected = note.favorite
categoryRepeater.model = api.categories
}
property int modified
property string title
property string category
property string content
property bool favorite
property string etag
property bool error
property string errorMessage
onAccepted: {
notesModel.updateNote(id, { 'category': categoryField.text, 'content': contentArea.text, 'favorite': favoriteButton.selected, 'modified': new Date().valueOf() / 1000 } )
}
SilicaFlickable {
@ -26,10 +38,7 @@ Dialog {
PullDownMenu {
MenuItem {
text: qsTr("Reset")
onClicked: {
note = api.getNote(note.id, false)
favoriteButton.selected = note.favorite
}
onClicked: reloadContent()
}
MenuItem {
text: qsTr("Markdown syntax")
@ -42,29 +51,30 @@ Dialog {
width: parent.width
DialogHeader {
title: note.title
id: dialogHeader
//title: editDialog.title
}
Column {
width: parent.width
spacing: Theme.paddingLarge
Separator {
/*Separator {
width: parent.width
color: Theme.primaryColor
horizontalAlignment: Qt.AlignHCenter
}
}*/
TextArea {
id: contentArea
width: parent.width
focus: true
text: note.content
text: content
placeholderText: qsTr("No content")
font.family: appSettings.useMonoFont ? "DejaVu Sans Mono" : Theme.fontFamily
property int preTextLength: 0
property var listPrefixes: [/^( *)- /gm, /^( *)\* /gm, /^( *)\+ /gm, /^( *)- \[ \] /gm, /^( *)- \[[xX]\] /gm, /^( *)> /gm, /^( *)\d+. /gm]
onTextChanged: {
if (page.status === PageStatus.Active &&
if (editDialog.status === PageStatus.Active &&
text.length > preTextLength &&
text.charAt(cursorPosition-1) === "\n") {
var clipboard = ""
@ -103,7 +113,7 @@ Dialog {
Repeater {
id: categoryRepeater
model: api.categories
model: notesApi.categories
BackgroundItem {
id: categoryBackground
width: categoryRectangle.width
@ -132,18 +142,18 @@ Dialog {
width: parent.width - x
IconButton {
id: favoriteButton
property bool selected: note.favorite
property bool selected: favorite
width: Theme.iconSizeMedium
icon.source: (selected ? "image://theme/icon-m-favorite-selected?" : "image://theme/icon-m-favorite?") +
(favoriteButton.highlighted ? Theme.secondaryHighlightColor : Theme.secondaryColor)
onClicked: {
api.updateNote(note.id, {'favorite': !note.favorite})
api.updateNote(id, {'favorite': !favorite})
}
}
TextField {
id: categoryField
width: parent.width - favoriteButton.width
text: note.category
text: category
placeholderText: qsTr("No category")
label: qsTr("Category")
EnterKey.iconSource: "image://theme/icon-m-enter-accept"
@ -151,8 +161,8 @@ Dialog {
categoryField.focus = false
}
onFocusChanged: {
if (focus === false && text !== note.category) {
api.updateNote(note.id, {'content': note.content, 'category': text}) // This does not seem to work without adding the content
if (focus === false && text !== category) {
notesModel.updateNote(id, {'content': content, 'category': text}) // This does not seem to work without adding the content
}
}
}
@ -161,7 +171,8 @@ Dialog {
DetailItem {
id: modifiedDetail
label: qsTr("Modified")
value: new Date(note.modified * 1000).toLocaleString(Qt.locale(), Locale.ShortFormat)
property int modified
onModifiedChanged: value = new Date(modified * 1000).toLocaleString(Qt.locale(), Locale.ShortFormat)
}
}

View file

@ -1,4 +1,4 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
Page {

View file

@ -1,154 +0,0 @@
import QtQuick 2.0
import Sailfish.Silica 1.0
import Nemo.Configuration 1.0
Dialog {
id: loginDialog
property string accountId
property bool addingNew: false
ConfigurationGroup {
id: account
path: "/apps/harbour-nextcloudnotes/accounts/" + accountId
Component.onCompleted: {
nameField.text = value("name", "", String)
serverField.text = value("server", "https://", String)
usernameField.text = value("username", "", String)
passwordField.text = value("password", "", String)
//unsecureConnectionTextSwitch.checked = value("unencryptedConnection", false, Boolean)
unencryptedConnectionTextSwitch.checked = value("allowUnencryptedConnection", false, Boolean)
}
}
canAccept: (nameField.text.length > 0 && serverField.acceptableInput && usernameField.text.length > 0 && passwordField.text.length > 0)
onAccepted: {
account.setValue("name", nameField.text)
account.setValue("server", serverField.text)
account.setValue("username", usernameField.text)
account.setValue("password", passwordField.text)
//account.setValue("unsecureConnection", unsecureConnectionTextSwitch.checked)
account.setValue("allowUnencryptedConnection", unencryptedConnectionTextSwitch.checked)
account.sync()
api.uuid = accountId
}
onRejected: {
if (addingNew) appSettings.removeAccount(accountId)
}
SilicaFlickable {
anchors.fill: parent
contentHeight: column.height + Theme.paddingLarge
Column {
id: column
width: parent.width
DialogHeader {
//title: qsTr("Nextcloud Login")
acceptText: addingNew ? qsTr("Login") : qsTr("Save")
}
Image {
anchors.horizontalCenter: parent.horizontalCenter
height: Theme.itemSizeHuge
fillMode: Image.PreserveAspectFit
source: "../img/nextcloud-logo-transparent.png"
}
TextField {
id: nameField
focus: true
width: parent.width
text: account.value("name", "", String)
placeholderText: qsTr("Account name")
label: placeholderText
errorHighlight: text.length === 0// && focus === true
EnterKey.enabled: text.length > 0
EnterKey.iconSource: "image://theme/icon-m-enter-next"
EnterKey.onClicked: serverField.focus = true
}
TextField {
id: serverField
// regExp combined from https://stackoverflow.com/a/3809435 (EDIT: removed ? after https to force SSL) and https://www.regextester.com/22
property var encryptedRegEx: /^https:\/\/(((www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b|((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))))([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/
property var unencryptedRegEx : /^https?:\/\/(((www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b|((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))))([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/
width: parent.width
text: account.value("server", "https://", String)
placeholderText: qsTr("Nextcloud server")
label: placeholderText + " " + qsTr("(starting with \"https://\")")
inputMethodHints: Qt.ImhUrlCharactersOnly
validator: RegExpValidator { regExp: unencryptedConnectionTextSwitch.checked ? serverField.unencryptedRegEx : serverField.encryptedRegEx }
errorHighlight: !acceptableInput// && focus === true
EnterKey.enabled: acceptableInput
EnterKey.iconSource: "image://theme/icon-m-enter-next"
EnterKey.onClicked: usernameField.focus = true
}
TextField {
id: usernameField
width: parent.width
text: account.value("name", "", String)
placeholderText: qsTr("Username")
label: placeholderText
inputMethodHints: Qt.ImhNoPredictiveText | Qt.ImhNoAutoUppercase
errorHighlight: text.length === 0// && focus === true
EnterKey.enabled: text.length > 0
EnterKey.iconSource: "image://theme/icon-m-enter-next"
EnterKey.onClicked: passwordField.focus = true
}
PasswordField {
id: passwordField
width: parent.width
text: account.value("password", "", String)
placeholderText: qsTr("Password")
label: placeholderText
errorHighlight: text.length === 0// && focus === true
EnterKey.enabled: text.length > 0
EnterKey.iconSource: "image://theme/icon-m-enter-accept"
EnterKey.onClicked: loginDialog.accept()
}
SectionHeader {
text: qsTr("Security")
}
Label {
x: Theme.horizontalPageMargin
width: parent.width - 2*x
wrapMode: Text.Wrap
color: Theme.secondaryColor
text: qsTr("<strong>CAUTION: Your password will be saved without any encryption on the device!</strong><br>Please consider creating a dedicated app password! Open your Nextcloud in a browser and go to <i>Settings</i> → <i>Security</i>.")
}
/*TextSwitch {
id: unsecureConnectionTextSwitch
text: qsTr("Do not check certificates")
description: qsTr("Enable this option to allow selfsigned certificates")
}*/
TextSwitch {
id: unencryptedConnectionTextSwitch
automaticCheck: false
text: qsTr("Allow unencrypted connections")
description: qsTr("")
checked: account.value("allowUnencryptedConnection", false, Boolean)
onClicked: {
if (checked) {
checked = false
}
else {
var dialog = pageStack.push(Qt.resolvedUrl("UnencryptedDialog.qml"))
dialog.accepted.connect(function() {
checked = true
})
dialog.rejected.connect(function() {
checked = false
})
}
}
}
}
}
allowedOrientations: defaultAllowedOrientations
}

320
qml/pages/LoginPage.qml Normal file
View file

@ -0,0 +1,320 @@
import QtQuick 2.2
import Sailfish.Silica 1.0
import Nemo.Configuration 1.0
Page {
id: loginPage
property string accountId
property bool legacyLoginPossible: false
property bool flowLoginV2Possible: false
ConfigurationGroup {
id: account
path: "/apps/harbour-nextcloudnotes/accounts/" + accountId
property string name: value("name", qsTr("Nextcloud Login"), String)
property url server: value("server", "", String)
property string version: value("version", "v0.2", String)
property string username: value("username", "", String)
property string password: account.value("password", "", String)
property bool doNotVerifySsl: account.value("doNotVerifySsl", false, Boolean)
property bool allowUnecrypted: account.value("allowUnecrypted", false, Boolean)
Component.onCompleted: {
pageHeader.title = name
serverField.text = server ? server : allowUnecrypted ? "http://" : "https://"
usernameField.text = username
passwordField.text = password
unsecureConnectionTextSwitch.checked = doNotVerifySsl
unencryptedConnectionTextSwitch.checked = allowUnecrypted
if (username !== "" && password !== "") {
notesApi.server = server
notesApi.username = username
notesApi.password = password
notesApi.verifySsl = !doNotVerifySsl
notesApi.verifyLogin()
}
}
}
/*onStatusChanged: {
if (status === PageStatus.Activating)
notesApi.getNcStatus()
if (status === PageStatus.Deactivating)
notesApi.abortFlowV2Login()
}*/
Connections {
target: notesApi
onStatusInstalledChanged: {
if (notesApi.statusInstalled)
serverField.focus = false
else {
pageHeader.title
}
}
onStatusVersionChanged: {
if (notesApi.statusVersion) {
if (notesApi.statusVersion.split('.')[0] >= 16) {
legacyLoginPossible = false
flowLoginV2Possible = true
console.log("Using Flow Login v2")
}
else {
legacyLoginPossible = true
flowLoginV2Possible = false
console.log("Using Legacy Login")
}
}
else {
legacyLoginPossible = false
flowLoginV2Possible = false
}
}
onStatusVersionStringChanged: {
if (notesApi.statusVersionString)
pageHeader.description = "Nextcloud " + notesApi.statusVersionString
}
onStatusProductNameChanged: {
if (notesApi.statusProductName) {
pageHeader.title = notesApi.statusProductName
account.name = notesApi.statusProductName
}
}
onLoginStatusChanged: {
switch(notesApi.loginStatus) {
case notesApi.LoginLegacyReady:
apiProgressBar.label = qsTr("Enter your credentials")
break;
//case notesApi.LoginFlowV2Initiating:
// break;
case notesApi.LoginFlowV2Polling:
apiProgressBar.label = qsTr("Follow the instructions in the browser")
break;
case notesApi.LoginFlowV2Success:
notesApi.verifyLogin()
break;
case notesApi.LoginFlowV2Failed:
apiProgressBar.label = qsTr("Login failed!")
break
case notesApi.LoginSuccess:
apiProgressBar.label = qsTr("Login successfull!")
account.username = notesApi.username
account.password = notesApi.password
appSettings.currentAccount = accountId
break;
case notesApi.LoginFailed:
apiProgressBar.label = qsTr("Login failed!")
break;
default:
apiProgressBar.label = ""
break;
}
}
onLoginUrlChanged: {
if (notesApi.loginUrl) {
Qt.openUrlExternally(notesApi.loginUrl)
}
else {
console.log("Login successfull")
}
}
onServerChanged: {
if (notesApi.server) {
console.log("Login server: " + notesApi.server)
account.server = notesApi.server
serverField.text = notesApi.server
}
}
}
SilicaFlickable {
anchors.fill: parent
contentHeight: column.height + Theme.paddingLarge
Column {
id: column
width: parent.width
spacing: Theme.paddingLarge
PageHeader {
id: pageHeader
}
Image {
id: nextcloudLogoImage
anchors.horizontalCenter: parent.horizontalCenter
height: Theme.itemSizeHuge
fillMode: Image.PreserveAspectFit
source: "../img/nextcloud-logo-transparent.png"
}
ProgressBar {
id: apiProgressBar
anchors.horizontalCenter: parent.horizontalCenter
width: parent.width
indeterminate: notesApi.loginStatus === notesApi.LoginFlowV2Initiating ||
notesApi.loginStatus === notesApi.LoginFlowV2Polling
}
Row {
width: parent.width
TextField {
id: serverField
width: parent.width - statusIcon.width - Theme.horizontalPageMargin
placeholderText: qsTr("Nextcloud server")
label: placeholderText
validator: RegExpValidator { regExp: unencryptedConnectionTextSwitch.checked ? /^https?:\/\/([-a-zA-Z0-9@:%._\+~#=].*)/: /^https:\/\/([-a-zA-Z0-9@:%._\+~#=].*)/ }
inputMethodHints: Qt.ImhUrlCharactersOnly
onClicked: if (text === "") text = "https://"
onTextChanged: {
statusBusyIndicatorTimer.restart()
if (acceptableInput) {
notesApi.server = text
notesApi.getNcStatus()
}
}
//EnterKey.enabled: text.length > 0
EnterKey.iconSource: legacyLoginPossible ? "image://theme/icon-m-enter-next" : flowLoginV2Possible ? "image://theme/icon-m-enter-accept" : "image://theme/icon-m-enter-close"
EnterKey.onClicked: {
if (legacyLoginPossible)
usernameField.focus = true
else if (flowLoginV2Possible && notesApi.loginStatus !== notesApi.LoginFlowV2Polling)
notesApi.initiateFlowV2Login()
focus = false
}
}
Icon {
id: statusIcon
highlighted: serverField.highlighted
source: notesApi.statusInstalled ? "image://theme/icon-m-acknowledge" : "image://theme/icon-m-question"
BusyIndicator {
anchors.centerIn: parent
size: BusyIndicatorSize.Medium
running: notesApi.ncStatusStatus === notesApi.NextcloudBusy || (serverField.focus && statusBusyIndicatorTimer.running && !notesApi.statusInstalled)
Timer {
id: statusBusyIndicatorTimer
interval: 200
}
}
}
}
TextSwitch {
id: forceLegacyButton
visible: debug
text: qsTr("Enforce legacy login")
onCheckedChanged: {
checked != checked
if (!checked) {
notesApi.getNcStatus()
}
}
}
Column {
id: flowv2LoginColumn
width: parent.width
spacing: Theme.paddingLarge
visible: opacity !== 0.0
opacity: flowLoginV2Possible && !forceLegacyButton.checked ? 1.0 : 0.0
Behavior on opacity { FadeAnimator {} }
Button {
anchors.horizontalCenter: parent.horizontalCenter
text: notesApi.loginStatus === notesApi.LoginFlowV2Polling ? qsTr("Abort") : notesApi.loginStatus === notesApi.LoginSuccess ? qsTr("Re-Login") : qsTr("Login")
onClicked: notesApi.loginStatus === notesApi.LoginFlowV2Polling ? notesApi.abortFlowV2Login() : notesApi.initiateFlowV2Login()
}
}
Column {
id: legacyLoginColumn
width: parent.width
visible: opacity !== 0.0
opacity: legacyLoginPossible || forceLegacyButton.checked ? 1.0 : 0.0
Behavior on opacity { FadeAnimator {} }
TextField {
id: usernameField
width: parent.width
placeholderText: qsTr("Username")
label: placeholderText
inputMethodHints: Qt.ImhNoPredictiveText | Qt.ImhNoAutoUppercase
errorHighlight: text.length === 0// && focus === true
EnterKey.enabled: text.length > 0
EnterKey.iconSource: "image://theme/icon-m-enter-next"
EnterKey.onClicked: passwordField.focus = true
}
PasswordField {
id: passwordField
width: parent.width
placeholderText: qsTr("Password")
label: placeholderText
errorHighlight: text.length === 0// && focus === true
EnterKey.enabled: text.length > 0
EnterKey.iconSource: "image://theme/icon-m-enter-accept"
EnterKey.onClicked: notesApi.verifyLogin(usernameField.text, passwordField.text)
}
Button {
anchors.horizontalCenter: parent.horizontalCenter
text: qsTr("Test Login")
onClicked: notesApi.verifyLogin(usernameField.text, passwordField.text)
}
}
SectionHeader {
text: qsTr("Note")
}
Label {
x: Theme.horizontalPageMargin
width: parent.width - 2*x
wrapMode: Text.Wrap
color: Theme.secondaryColor
linkColor: Theme.secondaryHighlightColor
text: qsTr("The <a href=\"https://apps.nextcloud.com/apps/notes\">Notes</a> app needs to be installed on the Nextcloud server for this app to work.")
}
SectionHeader {
text: qsTr("Security")
}
Label {
x: Theme.horizontalPageMargin
width: parent.width - 2*x
wrapMode: Text.Wrap
color: Theme.secondaryColor
text: qsTr("<strong>CAUTION: Your password will be saved without any encryption on the device!</strong><br>Please consider creating a dedicated app password! Open your Nextcloud in a browser and go to <i>Settings</i> → <i>Security</i>.")
}
TextSwitch {
id: unsecureConnectionTextSwitch
text: qsTr("Do not check certificates")
description: qsTr("Enable this option to allow selfsigned certificates")
onCheckedChanged: {
account.doNotVerifySsl = checked
notesApi.verifySsl = !account.doNotVerifySsl
}
}
TextSwitch {
id: unencryptedConnectionTextSwitch
automaticCheck: false
text: qsTr("Allow unencrypted connections")
description: qsTr("")
onClicked: {
if (checked) {
checked = false
}
else {
var dialog = pageStack.push(Qt.resolvedUrl("UnencryptedDialog.qml"))
dialog.accepted.connect(function() {
checked = true
})
dialog.rejected.connect(function() {
checked = false
})
}
}
}
}
}
allowedOrientations: defaultAllowedOrientations
}

View file

@ -1,4 +1,4 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
Page {

View file

@ -1,48 +1,62 @@
import "../js/showdown-1.9.0/dist/showdown.js" as ShowDown
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
import "../js/showdown/dist/showdown.js" as ShowDown
Dialog {
id: noteDialog
property int id
property var note
onIdChanged: note = notesModel.getNoteById(id)
onNoteChanged: {
if (note["content"].split('\n')[0].indexOf(note["title"]) > 0) {
dialogHeader.title = ""
}
else {
dialogHeader.title = note["title"]
}
favoriteButton.selected = note["favorite"]
categoryField.text = note["category"]
modifiedDetail.modified = note["modified"]
parseContent()
}
Connections {
target: notesModel
onNoteUpdated: {
if (id === noteDialog.id) {
noteDialog.note = note
}
}
}
acceptDestination: Qt.resolvedUrl("EditPage.qml")
onAcceptPendingChanged: {
if (acceptPending)
acceptDestinationInstance.id = id
}
onStatusChanged: {
if (status === PageStatus.Activating) {
notesModel.getNote(id)
}
}
property var showdown: ShowDown.showdown
property var converter: new showdown.Converter(
{ simplifiedAutoLink: true,
excludeTrailingPunctuationFromURLs: true,
parseImgDimensions: true,
strikethrough: true,
tables: true,
tasklists: false, // this is handled by the function parseContent() because LinkedLabel HTML support is to basic
parseImgDimensions: true,
smoothLivePreview: true,
simpleLineBreaks: true,
emoji: true } )
acceptDestination: Qt.resolvedUrl("EditPage.qml")
acceptDestinationProperties: { note: note }
Component.onCompleted: {
note = api.getNote(note.id)
reloadContent()
}
Connections {
target: api
onBusyChanged: {
if (api.busy === false) {
note = api.getNote(note.id, false)
reloadContent()
}
}
}
function reloadContent() {
acceptDestinationProperties = { note: note }
categoryRepeater.model = api.categories
parseContent()
}
function parseContent() {
//note = api.getNote(note.id, false)
var convertedText = converter.makeHtml(note.content)
var convertedText = converter.makeHtml(note["content"])
var occurence = -1
convertedText = convertedText.replace(/^<li>(<p>)?\[ \] (.*)(<.*)$/gmi,
function(match, p1, p2, p3, offset) {
@ -55,16 +69,17 @@ Dialog {
occurence++
return '<li class="tasklist"><a class="checkbox" href="tasklist:uncheckbox_' + occurence + '">' + (p1 ? p1 : "") + '☑ ' + p2 + '</a>' + p3
} )
convertedText = convertedText.replace("<table>", "<table border='1' cellpadding='" + Theme.paddingMedium + "'>")
convertedText = convertedText.replace(/<table>/gmi, "<table border='1' cellpadding='" + Theme.paddingMedium + "'>")
convertedText = convertedText.replace(/<del>(.*)<\/del>/gmi, function(match, p1) { return "<s>" + p1 + "</s>" })
convertedText = convertedText.replace(/<hr \/>/gmi, "<p><img width=\"" + contentLabel.width + "\" height=\"1\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAAPSURBVHjaYvr//z9AgAEABgYDACuJdK0AAAAASUVORK5CYII=\" /></p>")
contentLabel.text = "<style>\n" +
"ul,ol,table,img { margin: " + Theme.paddingLarge + "px 0px; }\n" +
"p,ul,ol,table,img { margin: " + Theme.paddingLarge + "px 0px; }\n" +
"a:link { color: " + Theme.primaryColor + "; }\n" +
"a.checkbox { text-decoration: none; padding: " + Theme.paddingSmall + "px; display: inline-block; }\n" +
"li.tasklist { font-size:large; margin: " + Theme.paddingMedium + "px 0px; }\n" +
"del { text-decoration: line-through; }\n" +
"table { border-color: " + Theme.secondaryColor + "; }\n" +
"</style>\n" + convertedText
//console.log(contentLabel.text)
//if (debug) console.log(contentLabel.text)
}
SilicaFlickable {
@ -80,44 +95,48 @@ Dialog {
onTriggered: pageStack.pop()
}
PullDownMenu {
busy: api.busy
busy: notesApi.busy
MenuItem {
text: qsTr("Delete")
onClicked: remorse.execute("Deleting", function() { api.deleteNote(note.id) } )
onClicked: remorse.execute("Deleting", function() { notesModel.deleteNote(note["id"]) } )
}
MenuItem {
text: enabled ? qsTr("Reload") : qsTr("Updating...")
enabled: !api.busy
onClicked: api.getNote(note.id)
enabled: !notesApi.busy
onClicked: notesModel.getNote(note["id"])
}
/*MenuItem {
text: qsTr("Edit")
onClicked: pageStack.push(Qt.resolvedUrl("../pages/NotePage.qml"), { id: id } )
}*/
MenuLabel {
visible: appSettings.currentAccount.length >= 0
text: qsTr("Last update") + ": " + (
new Date(api.update).valueOf() !== 0 ?
new Date(api.update).toLocaleString(Qt.locale(), Locale.ShortFormat) :
new Date(account.update).valueOf() !== 0 ?
new Date(account.update).toLocaleString(Qt.locale(), Locale.ShortFormat) :
qsTr("never"))
}
}
DialogHeader {
id: dialogHeader
dialog: noteDialog
title: note.title
acceptText: qsTr("Edit")
cancelText: qsTr("Notes")
}
BusyIndicator {
parent: dialogHeader.extraContent
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
size: BusyIndicatorSize.Medium
running: notesApi.busy
}
Column {
width: parent.width
spacing: Theme.paddingLarge
Separator {
width: parent.width
color: Theme.primaryColor
horizontalAlignment: Qt.AlignHCenter
}
LinkedLabel {
id: contentLabel
x: Theme.horizontalPageMargin
@ -128,7 +147,7 @@ Dialog {
onLinkActivated: {
//console.log(link)
var occurence = -1
var newContent = note.content
var newContent = note["content"]
if (/^tasklist:checkbox_(\d+)$/m.test(link)) {
newContent = newContent.replace(/- \[ \] (.*)$/gm,
function(match, p1, offset, string) {
@ -137,9 +156,9 @@ Dialog {
return (appSettings.useCapitalX ? '- [X] ' : '- [x] ') + p1 }
else { return match }
} )
note.content = newContent
note["content"] = newContent
parseContent()
api.updateNote(note.id, { 'content': note.content } )
notesModel.updateNote(id, { 'content': note["content"] } )
}
else if (/^tasklist:uncheckbox_(\d+)$/m.test(link)) {
newContent = newContent.replace(/- \[[xX]\] (.*)$/gm,
@ -149,9 +168,9 @@ Dialog {
return '- [ ] ' + p1 }
else { return match }
} )
note.content = newContent
note["content"] = newContent
parseContent()
api.updateNote(note.id, { 'content': note.content } )
notesModel.updateNote(id, { 'content': note["content"] } )
}
else {
Qt.openUrlExternally(link)
@ -175,7 +194,7 @@ Dialog {
Repeater {
id: categoryRepeater
model: api.categories
model: notesApi.categories
BackgroundItem {
id: categoryBackground
width: categoryRectangle.width
@ -206,18 +225,17 @@ Dialog {
width: parent.width - x
IconButton {
id: favoriteButton
property bool selected: note.favorite
property bool selected: false
width: Theme.iconSizeMedium
icon.source: (selected ? "image://theme/icon-m-favorite-selected?" : "image://theme/icon-m-favorite?") +
(favoriteButton.highlighted ? Theme.secondaryHighlightColor : Theme.secondaryColor)
onClicked: {
api.updateNote(note.id, {'favorite': !note.favorite})
notesModel.updateNote(note["id"], {'favorite': selected, 'modified': new Date().valueOf() / 1000 })
}
}
TextField {
id: categoryField
width: parent.width - favoriteButton.width
text: note.category
placeholderText: qsTr("No category")
label: qsTr("Category")
EnterKey.iconSource: "image://theme/icon-m-enter-accept"
@ -225,8 +243,8 @@ Dialog {
categoryField.focus = false
}
onFocusChanged: {
if (focus === false && text !== note.category) {
api.updateNote(note.id, {'content': note.content, 'category': text}) // This does not seem to work without adding the content
if (focus === false && text !== note["category"]) {
notesModel.updateNote(id, {'content': note["content"], 'category': text, 'modified': new Date().valueOf() / 1000}) // This does not seem to work without adding the content
}
}
}
@ -235,7 +253,8 @@ Dialog {
DetailItem {
id: modifiedDetail
label: qsTr("Modified")
value: new Date(note.modified * 1000).toLocaleString(Qt.locale(), Locale.ShortFormat)
property int modified
onModifiedChanged: value = new Date(modified * 1000).toLocaleString(Qt.locale(), Locale.ShortFormat)
}
}

View file

@ -1,324 +0,0 @@
import QtQuick 2.5
import Sailfish.Silica 1.0
import Nemo.Configuration 1.0
Item {
property string uuid
property string name
property url server
property url url
property string version: "v0.2"
property string username
property string password
property date update
property bool unsecureConnection
property bool unencryptedConnection
property var modelData: [ ]
property var model: ListModel { }
property var categories: [ ]
property string file: StandardPaths.data + "/" + uuid + ".json"
property bool saveFile: false
property bool busy: false
property bool searchActive: false
property int status: 204
property string statusText: "No Content"
Component.onCompleted: {
refreshConfig()
}
onStatusChanged: {
console.log("Network status: " + statusText + " (" + status + ")")
}
onUuidChanged: {
account.setValue("uuid", uuid)
onUuidChanged: console.log("Account : " + uuid)
account.path = "/apps/harbour-nextcloudnotes/accounts/" + uuid
refreshConfig()
modelData = []
model.clear()
appSettings.currentAccount = uuid
//getNotes()
}
onNameChanged: account.setValue("name", name)
onServerChanged: account.setValue("server", server)
onUsernameChanged: account.setValue("username", username)
onPasswordChanged: account.setValue("password", password)
onUpdateChanged: account.setValue("update", update)
onUnsecureConnectionChanged: account.setValue("unsecureConnection", unsecureConnection)
onUnencryptedConnectionChanged: account.setValue("unencryptedConnection", unencryptedConnection)
Connections {
target: appSettings
onSortByChanged: _mapDataToModel()
}
ConfigurationGroup {
id: account
path: "/apps/harbour-nextcloudnotes/accounts/" + uuid
onValuesChanged: refreshConfig()
}
function refreshConfig() {
account.sync()
name = account.value("name", "", String)
server = account.value("server", "", String)
url = server + "/index.php/apps/notes/api/" + version + "/notes"
username = account.value("username", "", String)
password = account.value("password", "", String)
update = account.value("update", "", Date)
unsecureConnection = account.value("unsecureConnection", false, Boolean)
unencryptedConnection = account.value("unencryptedConnection", false, Boolean)
}
function clear() {
modelData = []
model.clear()
account.clear()
}
function _APIcall(method, data) {
busy = true
var endpoint = url
if (data && (method === "GET" || method === "PUT" || method === "DELETE")) {
if (data.id) {
endpoint = endpoint + "/" + data.id
}
}
console.log("Calling " + endpoint)
var apiReq = new XMLHttpRequest
apiReq.open(method, endpoint, true)
apiReq.setRequestHeader('User-Agent', 'SailfishOS/harbour-nextcloudnotes')
apiReq.setRequestHeader('OCS-APIRequest', 'true')
apiReq.setRequestHeader("Content-Type", "application/json")
apiReq.setRequestHeader("Authorization", "Basic " + Qt.btoa(username + ":" + password))
apiReq.withCredentials = true
apiReq.onreadystatechange = function() {
if (apiReq.readyState === XMLHttpRequest.DONE) {
if (apiReq.status === 200) {
var json = JSON.parse(apiReq.responseText)
switch(method) {
case "GET":
if (Array.isArray(json)) {
console.log("Received all notes via API: " + endpoint)
modelData = json
_mapDataToModel()
update = new Date()
}
else {
console.log("Received a single note via API: " + endpoint)
_addToModelData(json)
}
break;
case "POST":
console.log("Created a note via API: " + endpoint)
_addToModelData(json)
pageStack.push(Qt.resolvedUrl("NotePage.qml"), { note: json } )
pageStack.completeAnimation()
pageStack.navigateForward()
break;
case "PUT":
console.log("Updated a note via API: " + endpoint)
_addToModelData(json)
break;
case "DELETE":
console.log("Deleted a note via API: " + endpoint)
_removeFromModelData(data.id)
break;
default:
console.log("Unsupported method: " + method)
break;
}
}/*
else if (apiReq.status === 304) {
console.log("ETag does not differ!")
}
else if (apiReq.status === 401) {
console.log("Unauthorized!")
}
else if (apiReq.status === 404) {
console.log("Note does not exist!")
}*/
else {
//console.log("Network error: " + apiReq.statusText + " (" + apiReq.status + ")")
}
statusText = apiReq.statusText
status = apiReq.status
busy = false
}
}
if (method === "GET") {
apiReq.send()
}
else if (method === "POST" || method === "PUT" || method === "DELETE") {
apiReq.send(JSON.stringify(data))
}
else {
console.log("Unsupported method: " + method)
apiReq.abort()
}
}
function getNotes(refresh) {
if (typeof(refresh) === 'undefined')
refresh = true
if (refresh)
_APIcall("GET")
return modelData
}
function getNote(id, refresh) {
if (typeof(refresh) === 'undefined')
refresh = true
if (id) {
if (refresh)
_APIcall("GET", { 'id': id } )
var note
modelData.forEach(function(currentValue) {
if (currentValue.id === id)
note = currentValue
} )
return note
}
}
function createNote(data) {
if (data)
_APIcall("POST", data)
}
function updateNote(id, data) {
if (id && data) {
data.id = id
_APIcall("PUT", data)
}
}
function deleteNote(id) {
if (id)
_APIcall("DELETE", { 'id': id } )
}
function _addToModelData(data) {
var dataUpdated = false
modelData.forEach(function(currentValue, index, array) {
if (currentValue.id === data.id) {
array[index] = data
dataUpdated = true
}
} )
if (!dataUpdated) {
modelData.push(data)
}
_mapDataToModel()
}
function _removeFromModelData(id) {
modelData.forEach(function(currentValue, index, array) {
if (currentValue.id === id) {
modelData.splice(index, 1)
}
} )
_mapDataToModel()
}
function _mapDataToModel() {
modelData.forEach(function(value) { value.date = getPrettyDate(value.modified) } )
switch(appSettings.sortBy) {
case "date":
modelData.sort(function(a, b) { return b.modified-a.modified } )
break
case "category":
modelData.sort(function(a, b) { return b.modified-a.modified } )
modelData.sort(function(a, b) { return ((a.category > b.category) ? 1 : ((b.category > a.category) ? -1 : 0)) } )
break
case "title":
modelData.sort(function(a, b) { return b.modified-a.modified } )
modelData.sort(function(a, b) { return ((a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0)) } )
break
}
if (!searchActive) {
categories = [ ]
for (var element in modelData) {
if (categories.indexOf(modelData[element].category) === -1 && modelData[element].category !== "" && typeof(modelData[element].category) !== 'undefined') {
categories.push(modelData[element].category)
}
model.set(element, modelData[element])
}
element++
while (model.count > element) {
model.remove(element)
}
}
}
function search(query) {
if (query !== "") {
searchActive = true
model.clear()
for (var element in modelData) {
if (modelData[element].title.toLowerCase().indexOf(query) >= 0 |
modelData[element].content.toLowerCase().indexOf(query) >= 0 |
modelData[element].category.toLowerCase().indexOf(query) >= 0) {
model.append(modelData[element])
}
}
}
else {
searchActive = false
_mapDataToModel()
}
}
// source: https://stackoverflow.com/a/14339782
function getPrettyDate(date) {
var today = new Date()
today.setHours(0)
today.setMinutes(0)
today.setSeconds(0)
today.setMilliseconds(0)
var compDate = new Date(date*1000)
compDate.setHours(0)
compDate.setMinutes(0)
compDate.setSeconds(0)
compDate.setMilliseconds(0)
if (compDate.getTime() === today.getTime()) {
return qsTr("Today")
} else if ((today.getTime() - compDate.getTime()) <= (24 * 60 * 60 *1000)) {
return qsTr("Yesterday")
} else {
return compDate.toLocaleDateString(Qt.locale(), Locale.ShortFormat)
}
}
/*Component.onCompleted: {
if (saveFile) {
if (account.name === "") {
saveFile = false
}
else {
busy = true
var fileReq = new XMLHttpRequest
fileReq.open("GET", file)
fileReq.onreadystatechange = function() {
if (fileReq.readyState === XMLHttpRequest.DONE) {
if (fileReq.responseText === "") {
update()
}
else {
console.log("Loaded " + account.name + " from local JSON file")
json = fileReq.responseText
busy = false
}
}
}
fileReq.send()
}
}
}*/
}

View file

@ -1,18 +1,23 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
Page {
id: page
property string searchString
onStatusChanged: {
if (status === PageStatus.Active) {
if (appSettings.accountIDs.length <= 0) {
if (status === PageStatus.Activating) {
if (accounts.value.length <= 0) {
addAccountHint.restart()
}
else {
autoSyncTimer.restart()
}
}
else if (status === PageStatus.Deactivating) {
autoSyncTimer.stop()
}
}
SilicaListView {
@ -21,7 +26,7 @@ Page {
spacing: Theme.paddingLarge
PullDownMenu {
busy: api.busy
busy: notesApi.busy
MenuItem {
text: qsTr("Settings")
@ -29,19 +34,19 @@ Page {
}
MenuItem {
text: qsTr("Add note")
enabled: appSettings.currentAccount.length > 0
onClicked: api.createNote({'content': ""})
enabled: appSettings.currentAccount.length > 0 && notesApi.networkAccessible
onClicked: notesModel.createNote( { 'content': "", 'modified': new Date().valueOf() / 1000 } )
}
MenuItem {
text: enabled ? qsTr("Reload") : qsTr("Updating...")
enabled: appSettings.currentAccount.length > 0 && !api.busy
onClicked: api.getNotes()
text: notesApi.networkAccessible && !notesApi.busy ? qsTr("Reload") : qsTr("Updating...")
enabled: appSettings.currentAccount.length > 0 && notesApi.networkAccessible && !notesApi.busy
onClicked: notesModel.getAllNotes()
}
MenuLabel {
visible: appSettings.currentAccount.length > 0
text: qsTr("Last update") + ": " + (
new Date(api.update).valueOf() !== 0 ?
new Date(api.update).toLocaleString(Qt.locale(), Locale.ShortFormat) :
new Date(account.update).valueOf() !== 0 ?
new Date(account.update).toLocaleString(Qt.locale(), Locale.ShortFormat) :
qsTr("never"))
}
}
@ -51,54 +56,59 @@ Page {
SearchField {
id: searchField
width: parent.width
placeholderText: api.name
enabled: !busyIndicator.running && !noLoginPlaceholder.enabled && !errorPlaceholder.enabled && !noNotesPlaceholder.enabled
placeholderText: notesApi.statusProductName.length > 0 ? notesApi.statusProductName : account.name.length > 0 ? account.name : qsTr("Nextcloud Notes")
EnterKey.iconSource: "image://theme/icon-m-enter-close"
EnterKey.onClicked: focus = false
onTextChanged: api.search(text.toLowerCase())
onTextChanged: {
searchString = text
notesProxyModel.setFilterFixedString(text)
}
}
Label {
id: description
x: Theme.horizontalPageMargin
width: parent.width - 2*x
visible: text.length > 1
anchors.bottom: parent.bottom
anchors.bottomMargin: Theme.paddingMedium
color: Theme.secondaryHighlightColor
font.pixelSize: Theme.fontSizeSmall
text: api.username + "@" + api.server
text: notesApi.username + "@" + notesApi.host
}
BusyIndicator {
anchors.verticalCenter: searchField.verticalCenter
anchors.right: parent.right
anchors.rightMargin: Theme.horizontalPageMargin
size: BusyIndicatorSize.Medium
running: api.busy && !busyIndicator.running
running: notesApi.busy && !busyIndicator.running
}
}
currentIndex: -1
model: api.model
Connections {
target: api
onUuidChanged: notesList.model = api.model
}
model: notesProxyModel
delegate: BackgroundItem {
id: note
contentHeight: titleLabel.height + previewLabel.height + 2*Theme.paddingSmall
height: contentHeight + menu.height
width: parent.width
highlighted: down || menu.active
/*ListView.onAdd: AddAnimation {
target: note
ListView.onAdd: AddAnimation {
target: note //searchText !== "" ? null : note
}
ListView.onRemove: RemoveAnimation {
target: note
}*/
target: note //searchText !== "" ? null : note
}
RemorseItem {
id: remorse
}
onClicked: pageStack.push(Qt.resolvedUrl("NotePage.qml"), { id: id } )
onPressAndHold: menu.open(note)
Separator {
width: parent.width
color: Theme.primaryColor
@ -113,7 +123,8 @@ Page {
icon.source: (favorite ? "image://theme/icon-m-favorite-selected?" : "image://theme/icon-m-favorite?") +
(note.highlighted ? Theme.secondaryHighlightColor : Theme.secondaryColor)
onClicked: {
api.updateNote(id, {'favorite': !favorite} )
var newFavorite = !favorite
notesModel.updateNote(id, {'favorite': newFavorite } )
}
}
@ -143,7 +154,7 @@ Page {
Label {
id: categoryLabel
anchors.centerIn: parent
text: category
text: categoryLabel.text.length > 0 ? category : ""
color: note.highlighted ? Theme.secondaryHighlightColor : Theme.secondaryColor
font.pixelSize: Theme.fontSizeExtraSmall
}
@ -172,10 +183,6 @@ Page {
}
}
onClicked: pageStack.push(Qt.resolvedUrl("NotePage.qml"),
{ note: api.model.get(index)} )
onPressAndHold: menu.open(note)
ContextMenu {
id: menu
MenuLabel {
@ -187,7 +194,7 @@ Page {
text: qsTr("Delete")
onClicked: {
remorse.execute(note, qsTr("Deleting note"), function() {
api.deleteNote(id)
notesModel.deleteNote(id)
})
}
}
@ -196,7 +203,7 @@ Page {
section.property: appSettings.sortBy
section.criteria: appSettings.sortBy === "title" ? ViewSection.FirstCharacter : ViewSection.FullString
section.labelPositioning: appSettings.sortBy === "title" ? ViewSection.FirstCharacter : ViewSection.InlineLabels
section.labelPositioning: appSettings.sortBy === "title" ? ViewSection.CurrentLabelAtStart | ViewSection.NextLabelAtEnd : ViewSection.InlineLabels
section.delegate: SectionHeader {
text: section
}
@ -205,26 +212,37 @@ Page {
id: busyIndicator
anchors.centerIn: parent
size: BusyIndicatorSize.Large
running: notesList.count === 0 && api.busy
running: notesList.count === 0 && notesApi.busy
}
Label {
id: busyLabel
anchors.top: busyIndicator.bottom
anchors.topMargin: Theme.paddingMedium
visible: busyIndicator.running
width: parent.width
color: Theme.highlightColor
font.pixelSize: Theme.fontSizeExtraLarge
horizontalAlignment: Qt.AlignHCenter
text: qsTr("Loading notes...")
}
ViewPlaceholder {
id: noLoginPlaceholder
enabled: appSettings.accountIDs.length <= 0
enabled: accounts.value.length <= 0
text: qsTr("No account yet")
hintText: qsTr("Got to the settings to add an account")
}
ViewPlaceholder {
id: noNotesPlaceholder
enabled: api.status === 204 && !busyIndicator.running && !noLoginPlaceholder.enabled
enabled: notesApi.status === 204 && !busyIndicator.running && !noLoginPlaceholder.enabled
text: qsTr("No notes yet")
hintText: qsTr("Pull down to add a note")
}
ViewPlaceholder {
id: noSearchPlaceholder
enabled: notesList.count === 0 && api.searchActive
enabled: notesList.count === 0 && searchString !== "" //notesProxyModel.filterRegExp !== ""
text: qsTr("No result")
hintText: qsTr("Try another query")
}
@ -233,7 +251,7 @@ Page {
id: errorPlaceholder
enabled: notesList.count === 0 && !busyIndicator.running && !noSearchPlaceholder.enabled && !noNotesPlaceholder.enabled && !noLoginPlaceholder.enabled
text: qsTr("An error occurred")
hintText: api.statusText
//hintText: notesApi.statusText
}
TouchInteractionHint {

View file

@ -1,9 +1,8 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
import Nemo.Configuration 1.0
import Nemo.Notifications 1.0
Page {
id: page
@ -33,7 +32,7 @@ Page {
}
Label {
id: noAccountsLabel
visible: appSettings.accountIDs.length <= 0
visible: accounts.value.length <= 0
text: qsTr("No Nextcloud account yet")
font.pixelSize: Theme.fontSizeLarge
color: Theme.secondaryHighlightColor
@ -41,7 +40,7 @@ Page {
}
Repeater {
id: accountRepeater
model: appSettings.accountIDs
model: accounts.value
delegate: ListItem {
id: accountListItem
@ -52,18 +51,17 @@ Page {
id: account
path: "/apps/harbour-nextcloudnotes/accounts/" + modelData
Component.onCompleted: {
accountTextSwitch.text = value("name", qsTr("Unnamed account"), String)
accountTextSwitch.description = account.value("username", qsTr("unknown"), String) + "@" + account.value("server", qsTr("unknown"), String)
accountTextSwitch.text = account.value("username", qsTr("unknown"), String) + " @ " + value("name", qsTr("Unnamed account"), String)
accountTextSwitch.description =account.value("server", qsTr("unknown"), String)
}
}
TextSwitch {
id: accountTextSwitch
automaticCheck: false
checked: modelData === api.uuid
checked: modelData === appSettings.currentAccount
onClicked: {
api.uuid = modelData
api.getNotes()
appSettings.currentAccount = modelData
}
onPressAndHold: openMenu()
}
@ -71,7 +69,7 @@ Page {
MenuItem {
text: qsTr("Edit")
onClicked: {
var login = pageStack.replace(Qt.resolvedUrl("LoginDialog.qml"), { accountId: modelData })
var login = pageStack.push(Qt.resolvedUrl("LoginPage.qml"), { accountId: modelData })
}
}
MenuItem {
@ -91,7 +89,7 @@ Page {
anchors.horizontalCenter: parent.horizontalCenter
onClicked: {
var newAccountID = appSettings.addAccount()
var login = pageStack.replace(Qt.resolvedUrl("LoginDialog.qml"), { accountId: newAccountID, addingNew: true })
var login = pageStack.push(Qt.resolvedUrl("LoginPage.qml"), { accountId: newAccountID, addingNew: true })
}
}
@ -124,6 +122,7 @@ Page {
onCurrentIndexChanged: {
appSettings.autoSyncInterval = autoSyncIntervalRepeater.model[currentIndex]
if (autoSyncIntervalRepeater.model[currentIndex] === 42 && theAnswer.enabled) {
console.log(theAnswer.body)
theAnswer.publish()
}
}
@ -144,27 +143,38 @@ Page {
}
ComboBox {
id: sortByComboBox
property var names: [qsTr("Last edited"), qsTr("Category"), qsTr("Title alphabetically")]
property var criteria: [
{ role: "modifiedString", text: qsTr("Last edited") },
{ role: "category", text: qsTr("Category") },
{ role: "title", text: qsTr("Title alphabetically") },
{ role: "none", text: qsTr("No sorting") }
]
label: qsTr("Sort notes by")
description: qsTr("This will also change how the notes are grouped")
menu: ContextMenu {
Repeater {
id: sortByRepeater
model: ["date", "category", "title"]
model: sortByComboBox.criteria
MenuItem {
text: sortByComboBox.names[index]
//enabled: modelData !== "title"
text: modelData.text
Component.onCompleted: {
if (modelData === appSettings.sortBy) {
if (modelData.role === appSettings.sortBy) {
sortByComboBox.currentIndex = index
}
}
onClicked: appSettings.sortBy = modelData.role
}
}
}
onCurrentIndexChanged: {
/*onCurrentIndexChanged: {
appSettings.sortBy = sortByRepeater.model[currentIndex]
}
}*/
}
TextSwitch {
text: qsTr("Favorites on top")
description: qsTr("Show notes marked as favorite above the others")
checked: appSettings.favoritesOnTop
onCheckedChanged: appSettings.favoritesOnTop = checked
}
TextSwitch {
text: qsTr("Show separator")

View file

@ -1,4 +1,4 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
Page {

View file

@ -1,4 +1,4 @@
import QtQuick 2.0
import QtQuick 2.2
import Sailfish.Silica 1.0
Dialog {

View file

@ -12,6 +12,46 @@
# * date Author's Name <author's email> version-release
# - Summary of changes
* Tue May 05 2020 Scharel Clemens <harbour-nextcloudnotes@scharel.rocks> 0.9-0
- Working offline mode
* Thu Apr 13 2020 Scharel Clemens <harbour-nextcloudnotes@scharel.rocks> 0.8-1
- Updated Signals and Slots between the modules
* Mon Apr 13 2020 Scharel Clemens <harbour-nextcloudnotes@scharel.rocks> 0.8-0
- New methods for data handling improved
* Fri Apr 10 2020 Scharel Clemens <harbour-nextcloudnotes@scharel.rocks> 0.7-0
- New methods for data handling are now usable
* Sun Apr 05 2020 Scharel Clemens <harbour-nextcloudnotes@scharel.rocks> 0.6-1
- Implementing new methods for data handling (files and API targets)
* Sun Mar 29 2020 Scharel Clemens <harbour-nextcloudnotes@scharel.rocks> 0.6-0
- Improved changes of 0.5
* Sun Jan 19 2020 Scharel Clemens <harbour-nextcloudnotes@scharel.rocks> 0.5-0
- Added offline mode
- Added Nextcloud Flow v2 Login
* Sun Jan 19 2020 Scharel Clemens <harbour-nextcloudnotes@scharel.rocks> 0.4-0
- Implemented API in C++
* Fri Dec 28 2018 Scharel Clemens <harbour-nextcloudnotes@scharel.name> 0.3-0
- Began implementing the data model in C++
* Thu Dec 27 2018 Scharel Clemens <harbour-nextcloudnotes@scharel.name> 0.2-10
- Implemented #24: "Option to show favorite notes on the top of the list"
- Implemented #32: "Allow selfsigned SSL certificates" (not tested!)
* Wed Dec 26 2018 Scharel Clemens <harbour-nextcloudnotes@scharel.name> 0.2-9
- Improved workaround for #40
* Mon Dec 17 2018 Scharel Clemens <harbour-nextcloudnotes@scharel.name> 0.2-8
- Some changes in the backgend
- Fixed #39
- Workaround for #40
* Wed Dec 12 2018 Scharel Clemens <harbour-nextcloudnotes@scharel.name> 0.2-7
- Implementing #18: Page with Markdown syntax
- Added padding to the bottom of the pages

View file

@ -13,8 +13,8 @@ Name: harbour-nextcloudnotes
%{!?qtc_make:%define qtc_make make}
%{?qtc_builddir:%define _builddir %qtc_builddir}
Summary: Nextcloud Notes
Version: 0.2
Release: 7
Version: 0.9
Release: 0
Group: Applications/Editors
License: MIT
URL: https://github.com/scharel/harbour-nextcloudnotes

View file

@ -1,7 +1,7 @@
Name: harbour-nextcloudnotes
Summary: Nextcloud Notes
Version: 0.2
Release: 7
Version: 0.9
Release: 0
# The contents of the Group field should be one of the groups listed here:
# https://github.com/mer-tools/spectacle/blob/master/data/GROUPS
Group: Applications/Editors

View file

@ -1,5 +1,11 @@
#include <QtQuick>
#include <sailfishapp.h>
#include <QtQml>
#include <QObject>
#include "note.h"
#include "notesapi.h"
#include "notesstore.h"
#include "notesmodel.h"
int main(int argc, char *argv[])
{
@ -12,15 +18,39 @@ int main(int argc, char *argv[])
qDebug() << app->applicationDisplayName() << app->applicationVersion();
QQuickView* view = SailfishApp::createView();
qRegisterMetaType<Note>();
NotesModel* notesModel = new NotesModel;
NotesProxyModel* notesProxyModel = new NotesProxyModel;
notesProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
notesProxyModel->setSortLocaleAware(true);
notesProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
notesProxyModel->setFilterRole(NotesModel::ContentRole);
notesProxyModel->setSourceModel(notesModel);
view->setSource(SailfishApp::pathTo("qml/harbour-nextcloudnotes.qml"));
NotesStore* notesStore = new NotesStore;
NotesApi* notesApi = new NotesApi;
notesModel->setNotesApi(notesApi);
notesModel->setNotesStore(notesStore);
QQuickView* view = SailfishApp::createView();
#ifdef QT_DEBUG
view->rootContext()->setContextProperty("debug", QVariant(true));
#else
view->rootContext()->setContextProperty("debug", QVariant(false));
#endif
view->rootContext()->setContextProperty("notesModel", notesModel);
view->rootContext()->setContextProperty("notesProxyModel", notesProxyModel);
view->rootContext()->setContextProperty("notesStore", notesStore);
view->rootContext()->setContextProperty("notesApi", notesApi);
view->setSource(SailfishApp::pathTo("qml/harbour-nextcloudnotes.qml"));
view->show();
return app->exec();
int retval = app->exec();
notesApi->deleteLater();
notesStore->deleteLater();
notesProxyModel->deleteLater();
notesModel->deleteLater();
return retval;
}

390
src/note.cpp Normal file
View file

@ -0,0 +1,390 @@
#include "note.h"
const QMap<Note::NoteField, QString> Note::m_noteFieldNames = QMap<Note::NoteField, QString>( {
{Note::Id, "id"},
{Note::Modified, "modified"},
{Note::Title, "title"},
{Note::Category, "category"},
{Note::Content, "content"},
{Note::Favorite, "favorite"},
{Note::Etag, "etag"},
{Note::Error, "error"},
{Note::ErrorMessage, "errorMessage"} } );
Note::Note(QObject *parent) : QObject(parent) {
connectSignals();
}
Note::~Note() {
//qDebug() << "Note destroyed: " << id();
}
Note::Note(const Note& note, QObject *parent) : QObject(parent) {
setId(note.id());
setModified(note.modified());
setTitle(note.title());
setCategory(note.category());
setContent(note.content());
setFavorite(note.favorite());
setEtag(note.etag());
setError(note.error());
setErrorMessage(note.errorMessage());
connectSignals();
}
Note::Note(const QJsonObject &note, QObject *parent) : QObject(parent) {
setId(id(note));
setModified(modified(note));
setTitle(title(note));
setCategory(category(note));
setContent(content(note));
setFavorite(favorite(note));
setEtag(etag(note));
setError(error(note));
setErrorMessage(errorMessage(note));
connectSignals();
}
Note& Note::operator =(const Note& note) {
setId(note.id());
setModified(note.modified());
setTitle(note.title());
setCategory(note.category());
setContent(note.content());
setFavorite(note.favorite());
setEtag(note.etag());
setError(note.error());
setErrorMessage(note.errorMessage());
return *this;
}
Note& Note::operator =(const QJsonObject& note) {
setId(id(note));
setModified(modified(note));
setTitle(title(note));
setCategory(category(note));
setContent(content(note));
setFavorite(favorite(note));
setEtag(etag(note));
setError(error(note));
setErrorMessage(errorMessage(note));
return *this;
}
Note& Note::operator <<(const QJsonObject& note) {
if (note.contains(Note::noteFieldName(Note::Id)))
setId(id(note));
if (note.contains(Note::noteFieldName(Note::Modified)))
setModified(modified(note));
if (note.contains(Note::noteFieldName(Note::Title)))
setTitle(title(note));
if (note.contains(Note::noteFieldName(Note::Category)))
setCategory(category(note));
if (note.contains(Note::noteFieldName(Note::Content)))
setContent(content(note));
if (note.contains(Note::noteFieldName(Note::Favorite)))
setFavorite(favorite(note));
if (note.contains(Note::noteFieldName(Note::Etag)))
setEtag(etag(note));
if (note.contains(Note::noteFieldName(Note::Error)))
setError(error(note));
if (note.contains(Note::noteFieldName(Note::ErrorMessage)))
setErrorMessage(errorMessage(note));
return *this;
}
bool Note::operator ==(const Note& note) const {
return id() == note.id();
}
bool Note::operator ==(const QJsonObject& note) const {
return id() == id(note);
}
bool Note::equal(const Note &note) const {
return id() == note.id() &&
modified() == note.modified() &&
title() == note.title() &&
category() == note.category() &&
content() == note.content() &&
favorite() == note.favorite() &&
etag() == note.etag() &&
error() == note.error() &&
errorMessage() == note.errorMessage();
}
bool Note::equal(const QJsonObject &note) const {
return id() == id(note) &&
modified() == modified(note) &&
title() == title(note) &&
category() == category(note) &&
content() == content(note) &&
favorite() == favorite(note) &&
etag() == etag(note) &&
error() == error(note) &&
errorMessage() == errorMessage(note);
}
bool Note::operator <(const Note& note) const {
return modified() < note.modified();
}
bool Note::operator <(const QJsonObject& note) const {
return modified() < modified(note);
}
bool Note::operator >(const Note& note) const {
return modified() > note.modified();
}
bool Note::operator >(const QJsonObject& note) const {
return modified() > modified(note);
}
const QJsonObject Note::toJsonObject() const {
return m_json;
}
const QJsonValue Note::toJsonValue() const {
return QJsonValue(m_json);
}
const QJsonDocument Note::toJsonDocument() const {
return QJsonDocument(m_json);
}
Note::NoteField Note::noteFieldsFromStringList(QStringList fields) {
QList<NoteField> list = noteFields();
QFlags<NoteField> flags;
for (int i = 0; i < list.size(); ++i) {
if (fields.contains(noteFieldName(list[i]))) {
flags |= list[i];
}
}
return static_cast<NoteField>((int)flags);
}
QStringList Note::noteFieldsToStringList(NoteField fields) {
QList<NoteField> list = noteFields();
QFlags<NoteField> flags(fields);
QStringList stringList;
for (int i = 0; i < list.size(); ++i) {
if (flags.testFlag(list[i])) {
stringList << noteFieldName(list[i]);
}
}
return stringList;
}
int Note::id() const {
return m_json.value(noteFieldName(Id)).toInt(-1);
}
int Note::id(const QJsonObject &jobj) {
return jobj.value(noteFieldName(Id)).toInt(-1);
}
void Note::setId(int id) {
if (id >= 0) {
if (id != this->id()) {
m_json.insert(noteFieldName(Id), QJsonValue(id));
emit idChanged(this->id());
}
}
else {
m_json.remove(noteFieldName(Id));
emit idChanged(this->id());
}
}
int Note::modified() const {
return m_json.value(noteFieldName(Modified)).toInt();
}
int Note::modified(const QJsonObject &jobj) {
return jobj.value(noteFieldName(Modified)).toInt();
}
void Note::setModified(int modified) {
if (modified > 0) {
if (modified != this->modified()) {
m_json.insert(noteFieldName(Modified), QJsonValue(modified));
emit modifiedChanged(this->modified());
emit modifiedStringChanged(modifiedString());
emit modifiedDateTimeChanged(modifiedDateTime());
}
}
else {
m_json.remove(noteFieldName(Modified));
emit modifiedChanged(this->modified());
emit modifiedStringChanged(modifiedString());
emit modifiedDateTimeChanged(modifiedDateTime());
}
}
QString Note::title() const {
return m_json.value(noteFieldName(Title)).toString();
}
QString Note::title(const QJsonObject &jobj) {
return jobj.value(noteFieldName(Title)).toString();
}
void Note::setTitle(QString title) {
if (!title.isNull()) {
if (title != this->title()) {
m_json.insert(noteFieldName(Title), QJsonValue(title));
emit titleChanged(this->title());
}
}
else {
m_json.remove(noteFieldName(Title));
emit titleChanged(this->title());
}
}
QString Note::category() const {
return m_json.value(noteFieldName(Category)).toString();
}
QString Note::category(const QJsonObject &jobj) {
return jobj.value(noteFieldName(Category)).toString();
}
void Note::setCategory(QString category) {
if (!category.isNull()) {
if (category != this->category()) {
m_json.insert(noteFieldName(Category), QJsonValue(category));
emit categoryChanged(this->category());
}
}
else {
m_json.remove(noteFieldName(Category));
emit categoryChanged(this->category());
}
}
QString Note::content() const {
return m_json.value(noteFieldName(Content)).toString();
}
QString Note::content(const QJsonObject &jobj) {
return jobj.value(noteFieldName(Content)).toString();
}
void Note::setContent(QString content) {
if (!content.isNull()) {
if (content != this->content()) {
m_json.insert(noteFieldName(Content), QJsonValue(content));
emit contentChanged(this->content());
}
}
else {
m_json.remove(noteFieldName(Content));
emit contentChanged(this->content());
}
}
bool Note::favorite() const {
return m_json.value(noteFieldName(Favorite)).toBool();
}
bool Note::favorite(const QJsonObject &jobj) {
return jobj.value(noteFieldName(Favorite)).toBool();
}
void Note::setFavorite(bool favorite) {
if (favorite && favorite != this->favorite()) {
m_json.insert(noteFieldName(Favorite), QJsonValue(favorite));
emit favoriteChanged(this->favorite());
}
else {
m_json.remove(noteFieldName(Favorite));
emit favoriteChanged(this->favorite());
}
}
QString Note::etag() const {
return m_json.value(noteFieldName(Etag)).toString();
}
QString Note::etag(const QJsonObject &jobj) {
return jobj.value(noteFieldName(Etag)).toString();
}
void Note::setEtag(QString etag) {
if (!etag.isNull()) {
if (etag != this->etag()) {
m_json.insert(noteFieldName(Etag), QJsonValue(etag));
emit etagChanged(this->etag());
}
}
else {
m_json.remove(noteFieldName(Etag));
emit etagChanged(this->etag());
}
}
bool Note::error() const {
return m_json.value(noteFieldName(Error)).toBool();
}
bool Note::error(const QJsonObject &jobj) {
return jobj.value(noteFieldName(Error)).toBool();
}
void Note::setError(bool error) {
if (error) {
if (error != this->error()) {
m_json.insert(noteFieldName(Error), QJsonValue(error));
emit errorChanged(this->error());
}
}
else {
m_json.remove(noteFieldName(Error));
emit errorChanged(this->error());
}
}
QString Note::errorMessage() const {
return m_json.value(noteFieldName(ErrorMessage)).toString();
}
QString Note::errorMessage(const QJsonObject &jobj) {
return jobj.value(noteFieldName(ErrorMessage)).toString();
}
void Note::setErrorMessage(QString errorMessage) {
if (!errorMessage.isNull()) {
if (errorMessage != this->errorMessage()) {
m_json.insert(noteFieldName(ErrorMessage), QJsonValue(errorMessage));
emit errorMessageChanged(this->errorMessage());
}
}
else {
m_json.remove(noteFieldName(ErrorMessage));
emit errorMessageChanged(this->errorMessage());
}
}
QString Note::modifiedString() const {
return modifiedString(m_json);
}
QString Note::modifiedString(const QJsonObject &jobj) {
QDateTime date = modifiedDateTime(jobj);
QString dateString;
qint64 diff = date.daysTo(QDateTime::currentDateTime());
if (diff == 0)
dateString = tr("Today");
else if (diff == 1)
dateString = tr("Yesterday");
else if (diff < 7)
dateString = date.toLocalTime().toString("dddd");
else if (date.toLocalTime().toString("yyyy") == QDateTime::currentDateTime().toString("yyyy"))
dateString = date.toLocalTime().toString("MMMM");
else if (!date.isValid())
dateString = date.toLocalTime().toString("MMMM yyyy");
return dateString;
}
QDateTime Note::modifiedDateTime() const {
return modifiedDateTime(m_json);
}
QDateTime Note::modifiedDateTime(const QJsonObject &jobj) {
QDateTime date;
date.setTime_t(modified(jobj));
return date;
}
void Note::connectSignals() {
connect(this, SIGNAL(idChanged(int)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(modifiedChanged(int)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(titleChanged(QString)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(categoryChanged(QString)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(contentChanged(QString)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(favoriteChanged(bool)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(etagChanged(QString)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(errorChanged(bool)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(errorMessageChanged(QString)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(modifiedStringChanged(QString)), this, SIGNAL(noteChanged()));
connect(this, SIGNAL(modifiedDateTimeChanged(QDateTime)), this, SIGNAL(noteChanged()));
}

142
src/note.h Normal file
View file

@ -0,0 +1,142 @@
#ifndef NOTE_H
#define NOTE_H
#include <QObject>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDateTime>
#include <QMap>
#include <QDebug>
// TODO derive from QJsonObject
class Note : public QObject {
Q_OBJECT
public:
Note(QObject *parent = NULL);
Note(const Note& note, QObject *parent = NULL);
Note(const QJsonObject& note, QObject *parent = NULL);
~Note();
Note& operator =(const Note& note);
Note& operator =(const QJsonObject& note);
Note& operator <<(const QJsonObject& note);
bool operator ==(const Note& note) const;
bool operator ==(const QJsonObject& note) const;
bool equal(const Note& note) const;
bool equal(const QJsonObject& note) const;
bool operator <(const Note& note) const;
bool operator <(const QJsonObject& note) const;
bool operator >(const Note& note) const;
bool operator >(const QJsonObject& note) const;
bool isValid() const { return id() >= 0; }
const QJsonObject toJsonObject() const;
const QJsonValue toJsonValue() const;
const QJsonDocument toJsonDocument() const;
enum NoteField {
None = 0x0000,
Id = 0x0001,
Modified = 0x0002,
Title = 0x0004,
Category = 0x0008,
Content = 0x0010,
Favorite = 0x0020,
Etag = 0x0040,
Error = 0x0080,
ErrorMessage = 0x0100
};
Q_DECLARE_FLAGS(NoteFields, NoteField)
Q_FLAG(NoteFields)
Q_INVOKABLE static QList<NoteField> noteFields() {
return m_noteFieldNames.keys();
}
Q_INVOKABLE static QString noteFieldName(NoteField field) {
return m_noteFieldNames[field];
}
Q_INVOKABLE static QStringList noteFieldNames() {
return m_noteFieldNames.values();
}
Q_INVOKABLE static NoteField noteFieldsFromStringList(QStringList fields);
Q_INVOKABLE static QStringList noteFieldsToStringList(Note::NoteField fields);
Q_PROPERTY(int id READ id WRITE setId NOTIFY idChanged)
int id() const;
void setId(int id);
Q_PROPERTY(int modified READ modified WRITE setModified NOTIFY modifiedChanged)
int modified() const;
void setModified(int modified);
Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged)
QString title() const;
void setTitle(QString title);
Q_PROPERTY(QString category READ category WRITE setCategory NOTIFY categoryChanged)
QString category() const;
void setCategory(QString category);
Q_PROPERTY(QString content READ content WRITE setContent NOTIFY contentChanged)
QString content() const;
void setContent(QString content);
Q_PROPERTY(bool favorite READ favorite WRITE setFavorite NOTIFY favoriteChanged)
bool favorite() const;
void setFavorite(bool favorite);
Q_PROPERTY(QString etag READ etag WRITE setEtag NOTIFY etagChanged)
QString etag() const;
void setEtag(QString etag);
Q_PROPERTY(bool error READ error WRITE setError NOTIFY errorChanged)
bool error() const;
void setError(bool error);
Q_PROPERTY(QString errorMessage READ errorMessage WRITE setErrorMessage NOTIFY errorMessageChanged)
QString errorMessage() const;
void setErrorMessage(QString errorMessage);
Q_PROPERTY(QString modifiedString READ modifiedString NOTIFY modifiedStringChanged)
QString modifiedString() const;
Q_PROPERTY(QDateTime modifiedDateTime READ modifiedDateTime NOTIFY modifiedDateTimeChanged)
QDateTime modifiedDateTime() const;
static int id(const QJsonObject& jobj);
static int modified(const QJsonObject& jobj);
static QString title(const QJsonObject& jobj);
static QString category(const QJsonObject& jobj);
static QString content(const QJsonObject& jobj);
static bool favorite(const QJsonObject& jobj);
static QString etag(const QJsonObject& jobj);
static bool error(const QJsonObject& jobj);
static QString errorMessage(const QJsonObject& jobj);
static QString modifiedString(const QJsonObject& jobj);
static QDateTime modifiedDateTime(const QJsonObject& jobj);
signals:
void idChanged(int id);
void modifiedChanged(int modified);
void titleChanged(QString title);
void categoryChanged(QString category);
void contentChanged(QString content);
void favoriteChanged(bool favorite);
void etagChanged(QString etag);
void errorChanged(bool error);
void errorMessageChanged(QString errorMessage);
void modifiedStringChanged(QString date);
void modifiedDateTimeChanged(QDateTime dateTime);
void noteChanged();
private:
QJsonObject m_json;
const static QMap<NoteField, QString> m_noteFieldNames;
void connectSignals();
};
Q_DECLARE_METATYPE(Note)
#endif // NOTE_H

644
src/notesapi.cpp Normal file
View file

@ -0,0 +1,644 @@
#include "notesapi.h"
#include <QGuiApplication>
#include <QAuthenticator>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDir>
NotesApi::NotesApi(const QString statusEndpoint, const QString loginEndpoint, const QString ocsEndpoint, const QString notesEndpoint, QObject *parent)
: m_statusEndpoint(statusEndpoint), m_loginEndpoint(loginEndpoint), m_ocsEndpoint(ocsEndpoint), m_notesEndpoint(notesEndpoint)
{
// TODO verify connections (also in destructor)
m_loginPollTimer.setInterval(POLL_INTERVALL);
connect(&m_loginPollTimer, SIGNAL(timeout()), this, SLOT(pollLoginUrl()));
setNcStatusStatus(NextcloudStatus::NextcloudUnknown);
setLoginStatus(LoginStatus::LoginUnknown);
m_ncStatusStatus = NextcloudStatus::NextcloudUnknown;
m_status_installed = false;
m_status_maintenance = false;
m_status_needsDbUpgrade = false;
m_status_extendedSupport = false;
m_loginStatus = LoginStatus::LoginUnknown;
connect(this, SIGNAL(urlChanged(QUrl)), this, SLOT(verifyUrl(QUrl)));
connect(&m_manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), this, SLOT(requireAuthentication(QNetworkReply*,QAuthenticator*)));
connect(&m_manager, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)), this, SLOT(onNetworkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)));
connect(&m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
connect(&m_manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this, SLOT(sslError(QNetworkReply*,QList<QSslError>)));
m_request.setSslConfiguration(QSslConfiguration::defaultConfiguration());
m_request.setHeader(QNetworkRequest::UserAgentHeader, QGuiApplication::applicationDisplayName() + " " + QGuiApplication::applicationVersion() + " - " + QSysInfo::machineHostName());
m_request.setHeader(QNetworkRequest::ContentTypeHeader, QString("application/x-www-form-urlencoded").toUtf8());
m_request.setRawHeader("OCS-APIREQUEST", "true");
m_authenticatedRequest = m_request;
m_authenticatedRequest.setHeader(QNetworkRequest::ContentTypeHeader, QString("application/json").toUtf8());
}
NotesApi::~NotesApi() {
disconnect(&m_loginPollTimer, SIGNAL(timeout()), this, SLOT(pollLoginUrl()));
disconnect(this, SIGNAL(urlChanged(QUrl)), this, SLOT(verifyUrl(QUrl)));
disconnect(&m_manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), this, SLOT(requireAuthentication(QNetworkReply*,QAuthenticator*)));
disconnect(&m_manager, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)), this, SLOT(onNetworkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)));
disconnect(&m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
disconnect(&m_manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this, SLOT(sslError(QNetworkReply*,QList<QSslError>)));
}
QString NotesApi::account() const {
return m_account;
}
void NotesApi::setAccount(const QString &account) {
if (account != m_account) {
m_account = account;
emit accountChanged(account);
}
}
const QList<int> NotesApi::noteIds() {
return m_syncedNotes.keys();
}
bool NotesApi::noteExists(const int id) {
return m_syncedNotes.contains(id);
}
int NotesApi::noteModified(const int id) {
return m_syncedNotes.value(id, -1);
}
bool NotesApi::getAllNotes(const QStringList& exclude) {
qDebug() << "Getting all notes";
QUrl url = apiEndpointUrl(m_notesEndpoint);
if (!exclude.isEmpty())
url.setQuery(QString(EXCLUDE_QUERY).append(exclude.join(",")));
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
qDebug() << "GET" << url.toDisplayString();
m_authenticatedRequest.setUrl(url);
m_getAllNotesReplies << m_manager.get(m_authenticatedRequest);
emit busyChanged(true);
return true;
}
return false;
}
bool NotesApi::getNote(const int id, const QStringList& exclude) {
qDebug() << "Getting note: " << id;
QUrl url = apiEndpointUrl(m_notesEndpoint + QString("/%1").arg(id));
if (!exclude.isEmpty())
url.setQuery(QString(EXCLUDE_QUERY).append(exclude.join(",")));
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
qDebug() << "GET" << url.toDisplayString();
m_authenticatedRequest.setUrl(url);
m_getNoteReplies << m_manager.get(m_authenticatedRequest);
emit busyChanged(true);
return true;
}
return false;
}
bool NotesApi::createNote(const QJsonObject& note) {
qDebug() << "Creating note";
QUrl url = apiEndpointUrl(m_notesEndpoint);
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
qDebug() << "POST" << url.toDisplayString();
m_authenticatedRequest.setUrl(url);
m_createNoteReplies << m_manager.post(m_authenticatedRequest, QJsonDocument(note).toJson());
emit busyChanged(true);
return true;
}
return false;
}
bool NotesApi::updateNote(const int id, const QJsonObject& note) {
qDebug() << "Updating note: " << id;
QUrl url = apiEndpointUrl(m_notesEndpoint + QString("/%1").arg(id));
if (id >= 0 && url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
qDebug() << "PUT" << url.toDisplayString();
m_authenticatedRequest.setUrl(url);
m_updateNoteReplies << m_manager.put(m_authenticatedRequest, QJsonDocument(note).toJson());
emit busyChanged(true);
return true;
}
return false;
}
bool NotesApi::deleteNote(const int id) {
qDebug() << "Deleting note: " << id;
QUrl url = apiEndpointUrl(m_notesEndpoint + QString("/%1").arg(id));
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
qDebug() << "DELETE" << url.toDisplayString();
m_authenticatedRequest.setUrl(url);
m_deleteNoteReplies << m_manager.deleteResource(m_authenticatedRequest);
emit busyChanged(true);
return true;
}
return false;
}
bool NotesApi::busy() const {
return !(m_getAllNotesReplies.empty() &&
m_getNoteReplies.empty() &&
m_createNoteReplies.empty() &&
m_updateNoteReplies.empty() &&
m_deleteNoteReplies.empty() &&
m_statusReplies.empty() &&
m_loginReplies.empty() &&
m_pollReplies.empty() &&
m_ocsReplies.empty());
}
void NotesApi::setVerifySsl(bool verify) {
if (verify != (m_request.sslConfiguration().peerVerifyMode() == QSslSocket::VerifyPeer)) {
m_request.sslConfiguration().setPeerVerifyMode(verify ? QSslSocket::VerifyPeer : QSslSocket::VerifyNone);
emit verifySslChanged(verify);
}
if (verify != (m_authenticatedRequest.sslConfiguration().peerVerifyMode() == QSslSocket::VerifyPeer)) {
m_authenticatedRequest.sslConfiguration().setPeerVerifyMode(verify ? QSslSocket::VerifyPeer : QSslSocket::VerifyNone);
emit verifySslChanged(verify);
}
}
void NotesApi::setUrl(QUrl url) {
if (url != m_url) {
QString oldServer = server();
setScheme(url.scheme());
setHost(url.host());
setPort(url.port());
setUsername(url.userName());
setPassword(url.password());
setPath(url.path());
emit urlChanged(m_url);
if (server() != oldServer)
emit serverChanged(server());
}
}
QString NotesApi::server() const {
QUrl server;
server.setScheme(m_url.scheme());
server.setHost(m_url.host());
if (m_url.port() > 0)
server.setPort(m_url.port());
server.setPath(m_url.path());
return server.toString();
}
void NotesApi::setServer(QString serverUrl) {
QUrl url(serverUrl.trimmed());
if (url != server()) {
setScheme(url.scheme());
setHost(url.host());
setPort(url.port());
setPath(url.path());
}
}
void NotesApi::setScheme(QString scheme) {
if (scheme != m_url.scheme() && (scheme == "http" || scheme == "https")) {
m_url.setScheme(scheme);
emit schemeChanged(m_url.scheme());
emit serverChanged(server());
emit urlChanged(m_url);
}
}
void NotesApi::setHost(QString host) {
if (host != m_url.host()) {
m_url.setHost(host);
emit hostChanged(m_url.host());
emit serverChanged(server());
emit urlChanged(m_url);
}
}
void NotesApi::setPort(int port) {
if (port != m_url.port() && port >= 1 && port <= 65535) {
m_url.setPort(port);
emit portChanged(m_url.port());
emit serverChanged(server());
emit urlChanged(m_url);
}
}
void NotesApi::setUsername(QString username) {
if (username != m_url.userName()) {
m_url.setUserName(username);
QString concatenated = username + ":" + password();
QByteArray data = concatenated.toLocal8Bit().toBase64();
QString headerData = "Basic " + data;
m_authenticatedRequest.setRawHeader("Authorization", headerData.toLocal8Bit());
emit usernameChanged(m_url.userName());
emit urlChanged(m_url);
}
}
void NotesApi::setPassword(QString password) {
if (password != m_url.password()) {
m_url.setPassword(password);
QString concatenated = username() + ":" + password;
QByteArray data = concatenated.toLocal8Bit().toBase64();
QString headerData = "Basic " + data;
m_authenticatedRequest.setRawHeader("Authorization", headerData.toLocal8Bit());
emit passwordChanged(m_url.password());
emit urlChanged(m_url);
}
}
void NotesApi::setPath(QString path) {
if (path != m_url.path()) {
m_url.setPath(path);
emit pathChanged(m_url.path());
emit serverChanged(server());
emit urlChanged(m_url);
}
}
bool NotesApi::getNcStatus() {
QUrl url = apiEndpointUrl(m_statusEndpoint);
qDebug() << "GET" << url.toDisplayString();
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
setNcStatusStatus(NextcloudStatus::NextcloudBusy);
m_request.setUrl(url);
m_statusReplies << m_manager.get(m_request);
return true;
}
else {
qDebug() << "URL not valid!";
setNcStatusStatus(NextcloudStatus::NextcloudUnknown);
}
return false;
}
bool NotesApi::initiateFlowV2Login() {
if (m_loginStatus == LoginStatus::LoginFlowV2Initiating || m_loginStatus == LoginStatus::LoginFlowV2Polling) {
abortFlowV2Login();
}
QUrl url = apiEndpointUrl(m_loginEndpoint);
qDebug() << "POST" << url.toDisplayString();
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
setLoginStatus(LoginStatus::LoginFlowV2Initiating);
m_request.setUrl(url);
m_loginReplies << m_manager.post(m_request, QByteArray());
return true;
}
else {
qDebug() << "URL not valid!";
setLoginStatus(LoginStatus::LoginFlowV2Failed);
abortFlowV2Login();
}
return false;
}
void NotesApi::abortFlowV2Login() {
m_loginPollTimer.stop();
m_loginUrl.clear();
emit loginUrlChanged(m_loginUrl);
m_pollUrl.clear();
m_pollToken.clear();
setLoginStatus(LoginStatus::LoginUnknown);
}
void NotesApi::pollLoginUrl() {
qDebug() << "POST" << m_pollUrl.toDisplayString();
if (m_pollUrl.isValid() && !m_pollUrl.scheme().isEmpty() && !m_pollUrl.host().isEmpty() && !m_pollToken.isEmpty()) {
m_request.setUrl(m_pollUrl);
m_pollReplies << m_manager.post(m_request, QByteArray("token=").append(m_pollToken));
}
else {
qDebug() << "URL not valid!";
setLoginStatus(LoginStatus::LoginFlowV2Failed);
abortFlowV2Login();
}
}
void NotesApi::verifyLogin(QString username, QString password) {
m_ocsRequest = m_authenticatedRequest;
if (username.isEmpty())
username = this->username();
if (password.isEmpty())
password = this->password();
QUrl url = apiEndpointUrl(m_ocsEndpoint + QString("/users/%1").arg(username));
m_ocsRequest.setRawHeader("Authorization", "Basic " + QString(username + ":" + password).toLocal8Bit().toBase64());
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
qDebug() << "GET" << url.toDisplayString();
m_ocsRequest.setUrl(url);
m_ocsReplies << m_manager.get(m_ocsRequest);
emit busyChanged(true);
}
}
const QString NotesApi::errorMessage(int error) const {
QString message;
switch (error) {
case NoError:
message = tr("No error");
break;
case NoConnectionError:
message = tr("No network connection available");
break;
case CommunicationError:
message = tr("Failed to communicate with the Nextcloud server");
break;
case SslHandshakeError:
message = tr("An error occured while establishing an encrypted connection");
break;
case AuthenticationError:
message = tr("Could not authenticate to the Nextcloud instance");
break;
default:
message = tr("Unknown error");
break;
}
return message;
}
void NotesApi::verifyUrl(QUrl url) {
emit urlValidChanged(url.isValid());
}
void NotesApi::requireAuthentication(QNetworkReply *reply, QAuthenticator *authenticator) {
if (reply && authenticator) {
authenticator->setUser(username());
authenticator->setPassword(password());
}
else
emit noteError(AuthenticationError);
}
void NotesApi::onNetworkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible) {
emit networkAccessibleChanged(accessible == QNetworkAccessManager::Accessible);
}
void NotesApi::replyFinished(QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError)
qDebug() << reply->error() << reply->errorString();
if (reply->error() == QNetworkReply::NoError)
emit noteError(NoError);
else if (reply->error() == QNetworkReply::AuthenticationRequiredError)
emit noteError(AuthenticationError);
else if (reply->error() == QNetworkReply::ContentNotFoundError && m_pollReplies.contains(reply))
emit noteError(NoError);
else
emit noteError(CommunicationError);
QByteArray data = reply->readAll();
QJsonDocument json = QJsonDocument::fromJson(data);
if (m_getAllNotesReplies.contains(reply)) {
qDebug() << "Get all notes reply";
if (reply->error() == QNetworkReply::NoError && json.isArray()) {
updateApiNotes(json.array());
}
m_getAllNotesReplies.removeOne(reply);
}
else if (m_getNoteReplies.contains(reply)) {
qDebug() << "Get note reply";
if (reply->error() == QNetworkReply::NoError && json.isObject())
updateApiNote(json.object());
m_getNoteReplies.removeOne(reply);
}
else if (m_createNoteReplies.contains(reply)) {
qDebug() << "Create note reply";
if (reply->error() == QNetworkReply::NoError && json.isObject())
createApiNote(json.object());
m_createNoteReplies.removeOne(reply);
}
else if (m_updateNoteReplies.contains(reply)) {
qDebug() << "Update note reply";bool ok;
QString idString = reply->url().path().split('/', QString::SkipEmptyParts).last();
int id = idString.toInt(&ok);
if (reply->error() == QNetworkReply::NoError && json.isObject() && id >= 0 && ok) {
QJsonObject obj = json.object();
obj["id"] = id;
updateApiNote(obj);
}
m_updateNoteReplies.removeOne(reply);
}
else if (m_deleteNoteReplies.contains(reply)) {
qDebug() << "Delete note reply";
bool ok;
QString idString = reply->url().path().split('/', QString::SkipEmptyParts).last();
int id = idString.toInt(&ok);
if (reply->error() == QNetworkReply::NoError && id >= 0 && ok) {
m_syncedNotes.remove(id);
emit noteDeleted(id);
}
m_deleteNoteReplies.removeOne(reply);
}
else if (m_loginReplies.contains(reply)) {
qDebug() << "Login reply";
if (reply->error() == QNetworkReply::NoError && json.isObject())
updateLoginFlow(json.object());
else {
m_loginStatus = LoginStatus::LoginFailed;
emit loginStatusChanged(m_loginStatus);
}
m_loginReplies.removeOne(reply);
}
else if (m_pollReplies.contains(reply)) {
qDebug() << "Poll reply, finished";
if (reply->error() == QNetworkReply::NoError && json.isObject())
updateLoginCredentials(json.object());
else if (reply->error() == QNetworkReply::ContentNotFoundError) {
qDebug() << "Polling not finished yet" << reply->url().toDisplayString();
m_loginStatus = LoginStatus::LoginFlowV2Polling;
emit loginStatusChanged(m_loginStatus);
}
else {
m_loginStatus = LoginStatus::LoginFailed;
emit loginStatusChanged(m_loginStatus);
}
m_pollReplies.removeOne(reply);
abortFlowV2Login();
}
else if (m_statusReplies.contains(reply)) {
qDebug() << "Status reply";
if (reply->error() == QNetworkReply::NoError && json.isObject())
updateNcStatus(json.object());
else
updateNcStatus(QJsonObject());
m_statusReplies.removeOne(reply);
}
else if (m_ocsReplies.contains(reply)) {
qDebug() << "OCS reply";
QString xml(data);
if (reply->error() == QNetworkReply::NoError && xml.contains("<status>ok</status>")) {
qDebug() << "Login Success!";
setLoginStatus(LoginSuccess);
}
else {
qDebug() << "Login Failed!";
setLoginStatus(LoginFailed);
}
m_ocsReplies.removeOne(reply);
}
else {
qDebug() << "Unknown reply";
}
//qDebug() << data;
emit busyChanged(busy());
reply->deleteLater();
}
void NotesApi::sslError(QNetworkReply *reply, const QList<QSslError> &errors) {
qDebug() << "SSL errors accured while calling" << reply->url().toDisplayString();
for (int i = 0; i < errors.size(); ++i) {
qDebug() << errors[i].errorString();
}
emit noteError(SslHandshakeError);
}
QUrl NotesApi::apiEndpointUrl(const QString endpoint) const {
QUrl url = server();
url.setPath(url.path() + endpoint);
return url;
}
void NotesApi::updateNcStatus(const QJsonObject &status) {
if (m_status_installed != status.value("installed").toBool()) {
m_status_installed = status.value("installed").toBool();
emit statusInstalledChanged(m_status_installed);
}
if (m_status_maintenance != status.value("maintenance").toBool()) {
m_status_maintenance = status.value("maintenance").toBool();
emit statusMaintenanceChanged(m_status_maintenance);
}
if (m_status_needsDbUpgrade != status.value("needsDbUpgrade").toBool()) {
m_status_needsDbUpgrade = status.value("needsDbUpgrade").toBool();
emit statusNeedsDbUpgradeChanged(m_status_needsDbUpgrade);
}
if (m_status_version != status.value("version").toString()) {
m_status_version = status.value("version").toString();
emit statusVersionChanged(m_status_version);
}
if (m_status_versionstring != status.value("versionstring").toString()) {
m_status_versionstring = status.value("versionstring").toString();
emit statusVersionStringChanged(m_status_versionstring);
}
if (m_status_edition != status.value("edition").toString()) {
m_status_edition = status.value("edition").toString();
emit statusEditionChanged(m_status_edition);
}
if (m_status_productname != status.value("productname").toString()) {
m_status_productname = status.value("productname").toString();
emit statusProductNameChanged(m_status_productname);
}
if (m_status_extendedSupport != status.value("extendedSupport").toBool()) {
m_status_extendedSupport = status.value("extendedSupport").toBool();
emit statusExtendedSupportChanged(m_status_extendedSupport);
}
if (status.isEmpty())
setNcStatusStatus(NextcloudStatus::NextcloudFailed);
else
setNcStatusStatus(NextcloudStatus::NextcloudSuccess);
}
void NotesApi::setNcStatusStatus(NextcloudStatus status, bool *changed) {
if (status != m_ncStatusStatus) {
if (changed)
*changed = true;
m_ncStatusStatus = status;
emit ncStatusStatusChanged(m_ncStatusStatus);
}
}
bool NotesApi::updateLoginFlow(const QJsonObject &login) {
QUrl url;
QString token;
if (!login.isEmpty()) {
QJsonObject poll = login.value("poll").toObject();
url = login.value("login").toString();
if (!poll.isEmpty() && url.isValid()) {
if (url != m_loginUrl) {
m_loginUrl = url;
emit loginUrlChanged(m_loginUrl);
}
url = poll.value("endpoint").toString();
token = poll.value("token").toString();
if (url.isValid() && !token.isEmpty()) {
m_pollUrl = url;
qDebug() << "Poll URL: " << m_pollUrl;
m_pollToken = token;
qDebug() << "Poll Token: " << m_pollToken;
setLoginStatus(LoginStatus::LoginFlowV2Polling);
m_loginPollTimer.start();
return true;
}
}
}
else {
qDebug() << "Invalid Poll Data:" << login;
setLoginStatus(LoginStatus::LoginFlowV2Failed);
abortFlowV2Login();
}
return false;
}
bool NotesApi::updateLoginCredentials(const QJsonObject &credentials) {
QString serverAddr;
QString loginName;
QString appPassword;
if (!credentials.isEmpty()) {
serverAddr = credentials.value("server").toString();
if (!serverAddr.isEmpty() && serverAddr != server())
setServer(serverAddr);
loginName = credentials.value("loginName").toString();
if (!loginName.isEmpty() && loginName != username())
setUsername(loginName);
appPassword = credentials.value("appPassword").toString();
if (!appPassword.isEmpty() && appPassword != password())
setPassword(appPassword);
}
if (!serverAddr.isEmpty() && !loginName.isEmpty() && !appPassword.isEmpty()) {
qDebug() << "Login successfull for user" << loginName << "on" << serverAddr;
setLoginStatus(LoginStatus::LoginFlowV2Success);
return true;
}
qDebug() << "Login failed for user" << loginName << "on" << serverAddr;
return false;
}
void NotesApi::setLoginStatus(LoginStatus status, bool *changed) {
if (status != m_loginStatus) {
if (changed)
*changed = true;
m_loginStatus = status;
emit loginStatusChanged(m_loginStatus);
}
}
void NotesApi::updateApiNotes(const QJsonArray &json) {
QList<int> ids;
for (int i = 0; i < json.size(); ++i) {
if (json[i].isObject()) {
QJsonObject object = json[i].toObject();
if (!object.isEmpty()) {
updateApiNote(json[i].toObject());
ids << object.value("id").toInt(-1);
}
}
}
m_lastSync = QDateTime::currentDateTime();
emit lastSyncChanged(m_lastSync);
emit allNotesChanged(ids);
}
void NotesApi::updateApiNote(const QJsonObject &json) {
int id = json["id"].toInt(-1);
if (id >= 0) {
m_syncedNotes.insert(id, json.value("modified").toInt(-1));
emit noteUpdated(id, json);
}
}
void NotesApi::createApiNote(const QJsonObject &json) {
int id = json["id"].toInt(-1);
if (id >= 0) {
m_syncedNotes.insert(id, json.value("modified").toInt(-1));
emit noteCreated(id, json);
}
}

Some files were not shown because too many files have changed in this diff Show more