GithubHelp home page GithubHelp logo

chrisdhaan / cdmarkdownkit Goto Github PK

View Code? Open in Web Editor NEW
240.0 12.0 63.0 373 KB

An extensive Swift framework providing simple and customizable markdown parsing.

License: MIT License

Ruby 0.58% Swift 99.42%
markdown textview label swift ios macos tvos watchos xcode cocoapods

cdmarkdownkit's Introduction

CDMarkdownKit

Star CDMarkdownKit On Github Stack Overflow

CI Status GitHub Release Swift Versions Platforms CocoaPods Compatible Carthage compatible Swift Package Manager Compatible License


This Swift framework handles standard markdown parsing along with the ability to parse custom elements.

For a demonstration of the capabilities of CDMarkdownKit; run the iOS Example project after cloning the repo.


Features

  • Markdown Parsing
    • Italic
    • Bold
    • Header
    • Quote
    • List
    • Code
    • Syntax
    • Link
    • Image
  • UITextView With Markdown Formatting
  • UILabel With Markdown Formatting
  • Platform Support
    • iOS
    • macOS
    • tvOS
    • watchOS
  • Documentation

Requirements

  • iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
  • Swift 5.3+

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate CDMarkdownKit into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'CDMarkdownKit', '2.5.1'

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate CDMarkdownKit into your Xcode project using Carthage, specify it in your Cartfile:

github "chrisdhaan/CDMarkdownKit" == 2.5.1

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding CDMarkdownKit as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/chrisdhaan/CDMarkdownKit.git", .upToNextMajor(from: "2.5.1"))
]

Git Submodule

If you prefer not to use any of the aforementioned dependency managers, you can integrate CDMarkdownKit into your project manually.

  • Open up Terminal, cd into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:
$ git init
  • Add CDMarkdownKit as a git submodule by running the following command:
git submodule add https://github.com/chrisdhaan/CDMarkdownKit.git
  • Open the new CDMarkdownKit folder, and drag the CDMarkdownKit.xcodeproj into the Project Navigator of your application's Xcode project.

    It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.

  • Select the CDMarkdownKit.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.

  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.

  • In the tab bar at the top of that window, open the "General" panel.

  • Click on the + button under the "Embedded Binaries" section.

  • You will see two different CDMarkdownKit.xcodeproj folders each with two different versions of the CDMarkdownKit.framework nested inside a Products folder.

    It does not matter which Products folder you choose from, but it does matter whether you choose the top or bottom CDMarkdownKit.framework.

  • Select the top CDMarkdownKit.framework for iOS and the bottom one for macOS.

    You can verify which one you selected by inspecting the build log for your project. The build target for CDMarkdownKit will be listed as either CDMarkdownKit iOS, CDMarkdownKit macOS, CDMarkdownKit tvOS or CDMarkdownKit watchOS.

  • And that's it!

    The CDMarkdownKit.framework is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.


Contributing

Before contributing to CDMarkdownKit, please read the instructions detailed in our contribution guide.


Usage

Initialization

// Create parser
let markdownParser = CDMarkdownParser()
// Parse markdown
let markdown = "This *framework* helps **with** parsing `markdown`."
label.attributedText = markdownParser.parse(markdown)

Customization

// Create parser
let markdownParser = CDMarkdownParser(font: UIFont(name: "HelveticaNeue", size: 16),
                                      boldFont: UIFont(name: "HelveticaNeue-Bold", size: 16),
                                      italicFont: UIFont(name: "HelveticaNeue-Thin", size: 16),
                                      fontColor: UIColor.darkGray,
                                      backgroundColor: UIColor.lightGray,
                                      squashNewlines: false)
// Customize elements
/// Bold
markdownParser.bold.color = UIColor.cyan
markdownParser.bold.backgroundColor = UIColor.purple
markdownParser.bold.underlineColor = UIColor.red
markdownParser.bold.underlineStyle = .double
/// Header
markdownParser.header.color = UIColor.black
markdownParser.header.backgroundColor = UIColor.orange
/// List
markdownParser.list.color = UIColor.black
markdownParser.list.backgroundColor = UIColor.red
/// Quote
markdownParser.quote.color = UIColor.gray
markdownParser.quote.backgroundColor = UIColor.clear
/// Link
markdownParser.link.color = UIColor.blue
markdownParser.link.backgroundColor = UIColor.green
let linkParagraphStyle = NSMutableParagraphStyle()
linkParagraphStyle.paragraphSpacing = 20
linkParagraphStyle.paragraphSpacingBefore = 0
linkParagraphStyle.lineSpacing = 20.38
markdownParser.link.paragraphStyle = linkParagraphStyle
markdownParser.automaticLink.color = UIColor.blue
markdownParser.automaticLink.backgroundColor = UIColor.green
/// Italic
markdownParser.italic.color = UIColor.gray
markdownParser.italic.backgroundColor = UIColor.clear
/// Code
markdownParser.code.font = UIFont.systemFont(ofSize: 17)
markdownParser.code.color = UIColor.red
markdownParser.code.backgroundColor = UIColor.black
/// Syntax
markdownParser.syntax.font = UIFont.systemFont(ofSize: 15)
markdownParser.syntax.color = UIColor.lightGray
markdownParser.syntax.backgroundColor = UIColor.black
/// Image
markdownParser.image.size = CGSize(width: 100,
                                   height: 50)
/// Strikethrough
markdownParser.strikethrough.font = UIFont.systemFont(ofSize: 20)
markdownParser.strikethrough.color = UIColor.magenta
markdownParser.strikethrough.strikethroughColor = UIColor.darkGray
markdownParser.strikethrough.strikethroughStyle = .double
// Parse markdown
let markdown = "This *framework* helps **with** parsing `markdown`."
label.attributedText = markdownParser.parse(markdown)

Supported Markdown Elements

*italic* or _italic_
**bold** or __bold__

# Header 1
## Header 2
### Header 3
#### Header 4
##### Header 5
###### Header 6

> Quote

* List
- List
+ List

`code`

```syntax```

[Link](url)
![Image](url)

CDMarkdownTextView

It is recommended that any CDMarkdownTextView objects be initialized programmatically as it uses custom text drawing objects to render attributed strings.

A CDMarkdownTextView object will still render when initialized via a storyboard but the default behavior for the following properties will be overridden:

  • isScrollEnabled = true
  • isSelectable = false
  • isEditable = false

These defaults are set to avoid crashes. There still may be unforeseen crashes that occur when initializing a CDMarkdownTextView object via a storyboard.

Programmatic Example

let rect = CGRect(x: 20,
                  y: 10,
                  width: CGFloat(self.frame.size.width - 40),
                  height: CGFloat(self.frame.size.height - 30))
/// Create custom text container
let textContainer = NSTextContainer(size: rect.size)
/// Create custom layout manager
let layoutManager = CDMarkdownLayoutManager()
layoutManager.addTextContainer(textContainer)
/// Initialization
let textView = CDMarkdownTextView(frame: rect, 
                                  textContainer: textContainer, 
                                  layoutManager: layoutManager)
textView.translatesAutoresizingMaskIntoConstraints = false
/// Standard markdown UI formatting
textView.roundCodeCorners = true
textView.roundSyntaxCorners = true
/// Custom markdown UI formatting
textView.roundAllCorners = true
/// Add constraints so intrinsic content size is set correctly
let topConstraint = NSLayoutConstraint(item: textView,
                                       attribute: NSLayoutAttribute.top,
                                       relatedBy: NSLayoutRelation.equal,
                                       toItem: textView.superview,
                                       attribute: NSLayoutAttribute.bottom,
                                       multiplier: 1,
                                       constant: 10)
let leadingConstraint = NSLayoutConstraint(item: textView,
                                           attribute: NSLayoutAttribute.leading,
                                           relatedBy: NSLayoutRelation.equal,
                                           toItem: textView.superview,
                                           attribute: NSLayoutAttribute.leadingMargin,
                                           multiplier: 1,
                                           constant: 0)
let trailingConstraint = NSLayoutConstraint(item: textView,
                                            attribute: NSLayoutAttribute.trailing,
                                            relatedBy: NSLayoutRelation.equal,
                                            toItem: textView.superview,
                                            attribute: NSLayoutAttribute.trailingMargin,
                                            multiplier: 1,
                                            constant: 0)
let bottomConstraint = NSLayoutConstraint(item: self.bottomLayoutGuide,
                                          attribute: NSLayoutAttribute.top,
                                          relatedBy: NSLayoutRelation.equal,
                                          toItem: textView,
                                          attribute: NSLayoutAttribute.bottom,
                                          multiplier: 1,
                                          constant: 20)
self.view.addConstraints([topConstraint,
                          leadingConstraint,
                          trailingConstraint,
                          bottomConstraint])
/// Add to view hierarchy
self.view.addSubview(textView)

Storyboard Example

/// Initialization
@IBOutlet fileprivate weak var textView: CDMarkdownTextView!
/// Standard markdown UI formatting
self.textView.roundCodeCorners = true
self.textView.roundSyntaxCorners = true
/// Custom markdown UI formatting
self.textView.roundAllCorners = true

CDMarkdownLabel

Programmatic Example

let size = self.frame.size
let rect = CGRect(x: 10, 
                  y: 10,
                  width: CGFloat(size.width - 20),
                  height: CGFloat(size.height - 20))
/// Initialization
let label = CDMarkdownLabel(frame: rect)
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
/// Standard markdown UI formatting
label.roundCodeCorners = true
label.roundSyntaxCorners = true
/// Custom markdown UI formatting
label.roundAllCorners = true

self.view.addSubview(label)

Storyboard Example

/// Initialization
@IBOutlet fileprivate weak var label: CDMarkdownLabel!
/// Standard markdown UI formatting
self.label.roundCodeCorners = true
self.label.roundSyntaxCorners = true
/// Custom markdown UI formatting
self.label.roundAllCorners = true

Author

Christopher de Haan, [email protected]


Credits

CDMarkdownKit was influenced by MarkdownKit, a markdown parsing library developed by Ivan Bruel.

CDMarkdownKit adds the following functionalities:

  • Fixed header element parsing
  • Image element parsing
  • Strikethrough element parsing
  • Ability to customize font for all elements
  • Ability to customize color for all elements
  • Ability to customize background color for all elements
  • Ability to customize paragraph style for all elements
  • Ability to customize underline color style for all elements
  • Ability to customize underline style style for all elements
  • UITextView with the ability to round background text color corners for code, syntax, or all elements
  • UILabel with the ability to round background text color corners for code, syntax, or all elements
  • macOS, tvOS, and watchOS support

License

CDMarkdownKit is available under the MIT license. See the LICENSE file for more info.


cdmarkdownkit's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cdmarkdownkit's Issues

Mention pattern bug

ℹ I want to open a link

ℹ Is it possible?

ℹ Do you have a plan for handling click action?

CDMarkdownKit Environment

CDMarkdownKit version: 2.1.0
Xcode version: 11.6
Swift version: 5
Platform(s) running CDMarkdownKit: iOS
macOS version running Xcode: 10.15.3

Crash with automatic link

What did you do?

ℹ Please replace this with what you did.
This is unclear as I have CDMarkdownKit in a deployed application.

What did you expect to happen?

For it not to crash?

What happened instead?

It crashes with CDMarkdownAutomaticLink.regularExpression()

CDMarkdownKit Environment

CDMarkdownKit version:
Xcode version: 9.3
Swift version: 4.1
Platform(s) running CDMarkdownKit: watchOS
macOS version running Xcode: Latest

Here is the report: https://pastebin.com/umuVpw8c

[Privacy Manifest] Implementation

Hello,

As we approach the upcoming spring and the anticipated implementation of the Privacy Manifest by Apple, it's crucial to ensure that your SDK fully complies with Apple's requirements.

Does your SDK need to include it?
If so, do you have a release date planned?

Thank you in advance for your attention to this matter.

Best regards

Add custom attribute

for example

            let detailLocation = gesture.location(in: contentLabel)
            let storage = NSTextStorage(attributedString: contentLabel.attributedText)
            let manager = NSLayoutManager()
            storage.addLayoutManager(manager)
            let container = NSTextContainer(size: CGSize(width: contentLabel.bounds.size.width, height: CGFloat.greatestFiniteMagnitude))
            container.lineFragmentPadding = 0
            container.maximumNumberOfLines = contentLabel.numberOfLines
            container.lineBreakMode = contentLabel.lineBreakMode
            manager.addTextContainer(container)
            let index = manager.characterIndex(for: detailLocation, in: container, fractionOfDistanceBetweenInsertionPoints: nil)
            let attributes = attributedText.attributes(at: index, effectiveRange: nil)
            if let attrbuteValue = attributes[CustomAttributedKey] as? String {
                 print("url is ", attrbuteValue)
            }

and other type, at(@xxx) image preview etc.

custome attrbutes interface is needed

Crash in CDFont+CDMarkdownKit.swift, line 57. Unexpectedly found nil when unwrapping optional value.

What did you do?

                        if let m = chat.message
                           , let font = UIFont(name: "Lato-Regular", size: 20.0)
                        {   
                            let markdownParser = CDMarkdownParser(font: font)
                        }

What did you expect to happen?

No crash

What happened instead?

Crash in CDFont+CDMarkdownKit.swift, line 57. Unexpectedly found nil when unwrapping optional value.

CDMarkdownKit Environment

CDMarkdownKit v2.1.1
xcode 12.5.1
swift v5.0
iOS Simulator
macOS 11.4

This is the CDMarkdownKit code that crashed, it crashed on the force unwrap of "descriptor" variable.

private func withTraits(_ traits: CDFontDescriptorSymbolicTraits...) -> CDFont {
    let descriptor = fontDescriptor.withSymbolicTraits(CDFontDescriptorSymbolicTraits(traits))
    return CDFont(descriptor: descriptor!,
                  size: self.pointSize)
}

UITextViewDelegate not called textView(_ textView: UITextView, shouldInteractWith....

What did you do?

final class MarkDownItemView: StackItemView<MarkDownItemView.Style> {
   override var arrangedViews: [UIView] {
       [markdownView]
   }

   private lazy var markdownView: CDMarkdownTextView = { [unowned self] in
       let textContainer = NSTextContainer(size: .zero)
       let layoutManager = CDMarkdownLayoutManager()
       layoutManager.addTextContainer(textContainer)
       let codeTextView = CDMarkdownTextView(frame: .zero,
                                             textContainer: textContainer,
                                             layoutManager: layoutManager)
       codeTextView.backgroundColor = .clear
       codeTextView.isScrollEnabled = false
       codeTextView.isEditable = false
       codeTextView.isSelectable = true
       codeTextView.delegate = self
       return codeTextView
   }()

   private var model: MarkdownTitleCellModelType?

   override func applyStyle(_ style: Style) {
       setContentInsets(style.contentInsets)
   }
}

extension MarkDownItemView {
   struct Style {
       let headerFont: UIFont
       let font: UIFont
       let boldFont: UIFont
       let italicFont: UIFont
       let linkColor: UIColor
       let fontColor: UIColor
       var contentInsets: UIEdgeInsets = .single(inset: 16)

       static let `default`: Style = .init(
           headerFont: Asset.Font.withStyle(.medium, size: .caption),
           font: Asset.Font.withStyle(.regular, size: .caption),
           boldFont: Asset.Font.withStyle(.medium, size: .caption),
           italicFont: Asset.Font.withStyle(.light, size: .body),
           linkColor: ColorPalette.Purple.darkPrimary.color,
           fontColor: ColorPalette.Black.primary.color
       )
   }

   func setup(model: MarkdownTitleCellModelType) {
       guard let style = styles[model.itemViewState] else {
           return
       }

       self.model = model
       let paragraphStyle = NSMutableParagraphStyle()
       paragraphStyle.paragraphSpacing = 3
       paragraphStyle.paragraphSpacingBefore = 12
       paragraphStyle.lineSpacing = 1.38

       let markdownParser = CDMarkdownParser(
           font: style.font,
           boldFont: style.boldFont,
           italicFont: style.italicFont,
           fontColor: style.fontColor,
           paragraphStyle: paragraphStyle
       )
       markdownParser.header.font = style.headerFont
       markdownParser.header.fontIncrease = 1

       let paragraphStyleList = NSMutableParagraphStyle()
       paragraphStyleList.paragraphSpacing = 3
       paragraphStyleList.paragraphSpacingBefore = 0
       paragraphStyleList.lineSpacing = 1.38
       markdownParser.list.paragraphStyle = paragraphStyleList

       markdownView.linkTextAttributes = [.foregroundColor: style.linkColor]
       markdownView.attributedText = markdownParser.parse(model.title)
       restyle(state: model.itemViewState)
   }
}

extension MarkDownItemView: UITextViewDelegate {
   func textView(_ textView: UITextView, shouldInteractWith markdownURL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
       if ValidationRule(ruleType: .email).validate(against: markdownURL.absoluteString) {
           model?.emailHandler(markdownURL.absoluteString)
       } else if UIApplication.shared.canOpenURL(markdownURL) {
           UIApplication.shared.open(markdownURL, options: [:])
       }
       return false
   }
}


What did you expect to happen?

call delegate method
func textView(_ textView: UITextView, shouldInteractWith markdownURL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

What happened instead?

nothing

CDMarkdownKit Environment

CDMarkdownKit version: 2.2.0 or 2.3.0 same behaviour
Xcode version: 14.1 (14B47b)
Swift version: 5.0
Platform(s) running CDMarkdownKit: ios 16
macOS version running Xcode: 13.0 (22A380)

CDMarkdownKit build failed on XCode 11.4

What did you do?

I've upgraded XCode from 11.3.1 to 11.4

What did you expect to happen?

CDMarkdownKit built with successful results.

What happened instead?

Build failed.
"Switch must be exhaustive on line 301 of CDMarkdownLabel.swift file."
Captura de pantalla 2020-03-25 a las 11 05 31

CDMarkdownKit Environment

CDMarkdownKit version: 1.2.1
Xcode version: 11.4
Swift version: 5
Platform(s) running CDMarkdownKit: iOS 13.3.1
macOS version running Xcode: Catalina 10.15.3 (19D76)

Best regards.

Paragraph Styling in CDMarkdownKit

What did you do?

Proposal for controlling the paragraph styling in CDMarkdownKit

I looked into paragraph styling that was in the old pull request and really liked his solution for paragraph styling. The only changes I made were the math to do number of lines before and after and exposing several variable for configuration. I think there might need to be some work done to pass the paragraph style along to certain classes like CDMarkdownQuote.swift as the default styling may look weird after you add the Quote style.

open var linesBeforeParagraph: CGFloat = 0
open var linesAfterParagraph:  CGFloat = 1
open var lineSpacing:          CGFloat = 1.38
let paraStyle = NSMutableParagraphStyle()
paraStyle.paragraphSpacingBefore = font.pointSize * linesBeforeParagraph
paraStyle.paragraphSpacing = font.pointSize * linesAfterParagraph
paraStyle.lineSpacing = lineSpacing
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paraStyle, range: range)

CDMarkdownKit Environment

CDMarkdownKit version: 1.0.0
Xcode version: Current
Swift version: 4.0
Platform(s) running CDMarkdownKit: Tested with iOS
macOS version running Xcode: Have not tested for macOS

Demo Project

Demo Example

Remove language hint of syntax blocks

What did you do?

Consider the following block

```js
var t = 5;
```

What did you expect to happen?

I would expect it to render as

var t = 5;

What happened instead?

It renders as

js
var t = 5;

CDMarkdownKit Environment

CDMarkdownKit version: 2.5.1
Xcode version: 14.3.1
Swift version: 5.8.1
Platform(s) running CDMarkdownKit: iOS 15/16
macOS version running Xcode: Ventura 13.4.1

I tried to solve this myself and changed the regex inside of CDMarkdownSyntax from

fileprivate static let regex = "(\\s+|^)(`{3})(\\s*[^`]*?\\s*)(\\2)(?!`)"

to

fileprivate static let regex = "(\\s+|^)(`{3}[^\\n]*?\\n)(\\s*[^`]*?\\s*)(`{3})(?!`)"

but this is now rendered as
image

Would be nice if the behaviour could be influenced.

Document WatchKit support

Thanks for creating this project

I experimented with this on WatchKit, and I found that the only API that works is setting attributed text on a WKInterfaceLabel, and that there seems to be no support for links, images, quote or code. Can you confirm this?

For this subset though, it works very well :-)

Swift 4 Support?

ℹ Please fill out this template when filing an issue.
All lines beginning with an ℹ symbol instruct you with what info we expect. You can delete those lines once you've filled in the info.

Per our *CONTRIBUTING guidelines, we use GitHub for
bugs and feature requests, not general support. Other issues should be opened on Stack Overflow with the tag cdmarkdownkit.

Please remove this line and everything above it before submitting.

What did you do?

ℹ Please replace this with what you did.

I expected Swift 4 to work

ℹ Please replace this with what you expected to happen.

It crashed with numerous errors, some fixable, others not.

ℹ Please replace this with of what happened instead.

CDMarkdownKit Environment

CDMarkdownKit version:
Xcode version:
Swift version:
Platform(s) running CDMarkdownKit:
macOS version running Xcode:

Demo Project

ℹ Please link to or upload a project we can download that reproduces the issue.

marking down a file doesn't format tables

What did you do?

I followed the documentation and marked down a text file

What did you expect to happen?

I expected the entire file to be marked down including tables

What happened instead?

The entire file was marked down except for the tables in the file

CDMarkdownKit Environment

**CDMarkdownKit version:2.1.0
**Xcode version:12.5
**Swift version:5
**Platform(s) running CDMarkdownKit:14.5
**macOS version running Xcode:11.3.1

Is support for tables going to be included in future?

Swift 4.2 compatibillity

What did you do?

Used CDMarkdownKit in a Swift 4.2/Xcode 10 project

What did you expect to happen?

It should not yield any errors or warnings

What happened instead?

It yields numerous compile errors, primarily related to NSAttributedStringKey & UIFontDescriptorSymbolicTraits.

CDMarkdownKit/Source/CDFont.swift:33:55: 'UIFontDescriptorSymbolicTraits' has been renamed to 'UIFontDescriptor.SymbolicTraits'
CDMarkdownKit/Source/CDMarkdownStyle.swift:50:24: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownStyle.swift:53:24: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownStyle.swift:56:24: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownStyle.swift:59:24: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownSyntax.swift:88:50: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownSyntax.swift:112:47: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownLink.swift:71:39: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownList.swift:108:39: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownParser.swift:193:39: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownParser.swift:196:39: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownParser.swift:199:39: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownParser.swift:202:39: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownHeader.swift:118:24: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownImage.swift:76:39: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownLabel.swift:333:39: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2
CDMarkdownKit/Source/CDMarkdownLabel.swift:390:60: 'NSAttributedStringKey' has been renamed to 'NSAttributedString.Key'
/Foundation.NSAttributedStringKey:2:18: 'NSAttributedStringKey' was obsoleted in Swift 4.2

I can submit a PR for this, but I'd like to hear from @chrisdhaan what approach he wants to follow.
Possible approaches:

  1. Drop pre-Swift 4.2 support completely
  2. Make Swift 4.2 support available through a new branch
  3. Use conditional compile directives to include different code based on used Swift version.

The last option is probably the right one judging on past use of this approach. But I'd like to know for certain before I submit a PR to avoid unnecessary work.

CDMarkdownKit Environment

CDMarkdownKit version: 1.2.0
Xcode version: 10.0
Swift version: 4.2
Platform(s) running CDMarkdownKit: iOS 12
macOS version running Xcode: 10.13.6

Links not rendering

ℹ Please fill out this template when filing an issue.
All lines beginning with an ℹ symbol instruct you with what info we expect. You can delete those lines once you've filled in the info.

Per our *CONTRIBUTING guidelines, we use GitHub for
bugs and feature requests, not general support. Other issues should be opened on Stack Overflow with the tag cdmarkdownkit.

Please remove this line and everything above it before submitting.

What did you do?

Tried to parse links

What did you expect to happen?

I expect [Link](somelink.com) to render as Link with whatever styling i set

What happened instead?

The styling is not applied. Also if the link is the only thing being parsed it is not recognised as a link as the regex expects it to be prefixed with some character.

CDMarkdownKit Environment

CDMarkdownKit version: 1.2.1
Xcode version: 10.2
Swift version: 4.2
Platform(s) running CDMarkdownKit: iOS 12.1 iPhone XS
macOS version running Xcode: 10.14.3, macOS Mojave

Add possibility to use multiple \n in a row

Thank you a lot for this library, i want to suggest small improvement that will be very helpful
Right now i can't use multiple \n in a row, because library replacing all consecutive \n into one \n
It can be solved adding bool flag in constructor which says if parser should replace \n or not

Link not clickable

What did you do?

I've tried the sample project, then I create and render a simple markdown, like "This framework helps with parsing markdown with Link."

What did you expect to happen?

the Link is clickable

What happened instead?

it is not clickable because displayActionController is not triggered <- selectedURLRange = nil <- boundingReact is not contains the correctLocation

image

image

CDMarkdownKit Environment

CDMarkdownKit version: 2.3.0
Xcode version: 14.0.1
Swift version: swift-driver version: 1.62.8 Apple Swift version 5.7 (swiftlang-5.7.0.127.4 clang-1400.0.29.50)
Platform(s) running CDMarkdownKit: iOS
macOS version running Xcode: 12.6

CDMarkdownTextView: Load local images

What did you do?

Tried to use a local image (added to main bundle) referencing it via:

![my image](my-image.png)
![my image](./my-image.png)
![my image](file://my-image.png)
![my image](file://./my-image.png)

What did you expect to happen?

The image should at least once be loaded like an external image e.g.

![my external image](http://www.christopherdehaan.me/public/img/circle-hover.png)

which works fine.

What happened instead?

No image loaded.

Instead, console told about a NSURLConnection finished with error - code -1002 error. IIUC this is a not supported protocol.

CDMarkdownKit Environment

CDMarkdownKit version: 0.9.7
Xcode version: 9.2 (9C40b)
Swift version: 4.0.3
Platform(s) running CDMarkdownKit: iOS Simulator w/ iOS 11.2 (15C107)
macOS version running Xcode:: 10.13.2 (17C205)

I used CDMarkdownTextView and could successfully load a local image with:

let myImage = UIImage(named: "my-image.png")
let attachment: NSTextAttachment = NSTextAttachment()
attachment.image = thumbnailImage
let attributedImageString: NSAttributedString = NSAttributedString(attachment: attachment)
cdMarkdownTextView.textStorage.append(attributedImageString)

Rough guess it's related to CDMarkdownImage's url handling.

Demo Project

TBD, matter of time...

Asynchronous images

What did you do?

I have images that are between some paragraphs in my markdown code

What did you expect to happen?

I want to load asynchronously my images. I've tried to change the match function with a DispatchQueue.main.async in the CDMarkdownImage.swift but it doesn't display the images at all.

What happened instead?

The images are loading well but they are synchronized with the rest of the rendering. The view takes a while to load.

CDMarkdownKit Environment

CDMarkdownKit version: 1.0
Xcode version: 10.1
Swift version: 3
Platform(s) running CDMarkdownKit: IOS
**macOS version running Xcode:**10.14.3

Image scaling

What did you do?

Parsed an image link with a large image.

What did you expect to happen?

The image to fit in the textView.

What happened instead?

The image was too large and didn't scale.

CDMarkdownKit Environment

CDMarkdownKit version: 0.9.7
Xcode version: 9.2 (9C40b)
Swift version: 3.2
Platform(s) running CDMarkdownKit: iOS
macOS version running Xcode: MacOS Sierra 10.12.6


Possible solution to this is to pass a desired frame to CDMarkdownParser and initialize CDMarkdownImage with it. Then, scale the attachment size to fit the passed frame.

    private func adjustAttachmentSize(_ attachment: NSTextAttachment, image: UIImage) {
        guard let frame = frame else {
            return
        }

        // about 10 point padding so the image will fit
        let preferredWidth = frame.width - 10
        let widthScalingFactor = image.size.width / preferredWidth

        attachment.bounds = CGRect(x: 0.0,
                                   y: 0.0,
                                   width: image.size.width / widthScalingFactor,
                                   height: image.size.height / widthScalingFactor)
    }

Another possible solution is to parse customElements before defaultElements in CDMarkdownParser. Then developers have an option to create a custom class for scaled images and pass that as a custom element.

Feature Request

Would it be possible to add Strikethrough and underline?

I use this with Swift 5

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.