Code Monkey home page Code Monkey logo

attributedmarkdown's Introduction

AttributedMarkdown: Native Markdown Parsing on iOS

Markdown is intended to be as easy-to-read and easy-to-write as is feasible.

-- Daring Fireball

This library takes Markdown formatted text and turns it into an NSAttributedString, suitable for rendering in native UIKit components on iOS 6 (UITextView, UILabel, etc).

In short, this allows you to apply styling to Markdown without having to use UIWebView and HTML tags.

This project is based-upon / modifies a Cocoa fork of peg markdown.

Usage:

// start with a raw markdown string
NSString *rawText = @"Hello, world. *This* is native Markdown.";

// create a font attribute for emphasized text
UIFont *emFont = [UIFont fontWithName:@"AvenirNext-MediumItalic" size:15.0];

// create a color attribute for paragraph text
UIColor *color = [UIColor purpleColor];

// create a dictionary to hold your custom attributes for any Markdown types
NSDictionary *attributes = @{
  @(EMPH): @{NSFontAttributeName : emFont,},
  @(PARA): @{NSForegroundColorAttributeName : color,}
};

// parse the markdown
NSAttributedString *prettyText = markdown_to_attr_string(rawText,0,attributes);

// assign it to a view object
myTextView.attributedText = prettyText;

Check out the HelloMarkdown example app to see it in action.

Easy Setup (BETA)

A Cocoapod Podspec file has been added that will allow you to do a pod install to get up and running quickly. Eventually we'll post it to the cocoapods repo. For now, here's what your podfile should look like:

platform :ios
pod 'AttributedMarkdown', :git => 'https://github.com/dreamwieber/AttributedMarkdown.git'

(The HelloMarkdown project hasn't been updated or tested against a cocoapod install. If you find any issues please let us know. This should work fine for your new project though.)

Requirements & Setup

If you don't want to do Cocoapods, you can build the library yourself. There are some dependencies, which have proven tricky for some. Unless you need/want to modify the parser, it's probably easier to go with Cocoapod install.

AttributedMarkdown makes use of a parser-generator called greg. This is included as a submodule, and you'll need to first run this from the command-line (from your project's root directory):

git submodule update --init --recursive

You'll also need to include the CoreText Framework in your project.

To use AttributedMarkdown in one of your projects, follow the standard Apple guidelines for linking against a static library

Finally, create a group in your project called "Headers" and copy these files into it:

markdown_lib.h
markdown_peg.h 

Leave the option to copy the files into your project unselected.

(Note that you don't have to call the group "Headers", this is simply a suggestion. The important bit is making sure the header references exist somewhere in your project.)

The import statements in your project, wherever you want to make use of the library (eg., in a View Controller) should look like:

#import "markdown_lib.h"
#import "markdown_peg.h"

Basic Cascading Styles

AttributedMarkdown performs some very basic cascading styles, merging the string attributes of parent elements into child elements by extracting their font traits via CoreText. This allows for things like emphasized words within an h1 tag to be bold as well as italicized.

Performance

Although I have yet to perform any optimizations, parsing and display of markdown in a UITableView filled with many cells of long-form markdown sample text performs rather well.

Limitations

This is a work in progress. Some tags are not yet supported, like img, etc.

Credit

AttributedMarkdown was created by Gregory Wieber and Jim Radford. It is based upon peg-markdown.

License

AttributedMarkdown is released under both the GPL and the MIT license; see LICENSE for details.

Peg-Markdown License

peg-markdown is written and maintained by John MacFarlane (jgm on github), with significant contributions by Ryan Tomayko (rtomayko). It is released under both the GPL and the MIT license; see LICENSE for details. peg-markdown was adapted for Cocoa by David Whetstone.

attributedmarkdown's People

Contributors

anotwell avatar dreamwieber avatar humblehacker avatar jgm avatar jhemingw avatar joelfischerr avatar neonichu avatar obeattie avatar radford avatar rhysforyou avatar rtomayko avatar

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  avatar  avatar

attributedmarkdown's Issues

Crashes when Emails included in markdown

When there are email adresses included in the document, markdown_output.m crashes.

case LINK:;
        NSURL *url = [NSURL URLWithString:elt->contents.link->url];
        if (url) {
            NSDictionary *linkAttibutes = @{@"attributedMarkdownURL": url};
            print_attr_element_list(out, elt->contents.link->label, attributes, merge(current, merge(attributes[elt->key], linkAttibutes)));
        } else {
            NSDictionary *attributesBroken = @{NSForegroundColorAttributeName: [TARGET_PLATFORM_COLOR redColor]}; // Make this attributes[BROKEN]
            print_attr_element_list(out, elt->contents.link->label, attributes, merge(current, attributesBroken));
            print_attr_string(out, [NSString stringWithFormat: @" (%@)", elt->contents.link->url], current);
        }
        break;

How do I use attributes with Swift

let attributes = [H1:[NSFontAttributeName:font],
            H1:[NSForegroundColorAttributeName:color]] 

this doesn't work. "Type NSString does not confrom to protocol 'Hashable' "

Problem with iOS 6

I'm having an issue with iOS 6 and latin encoding:

// create a dictionary to hold your custom attributes for any Markdown types
NSDictionary *attributes = @{
                             @(EMPH): @{NSFontAttributeName : emFont},
                             @(PARA): @{NSForegroundColorAttributeName : color,NSFontAttributeName : pFont},
                             @(STRONG): @{NSFontAttributeName : strongFont,},
                             @(LINK): @{NSForegroundColorAttributeName : linkColor}
                             };

// parse the markdown
NSAttributedString *prettyText = markdown_to_attr_string(description,0,attributes);

Phrase: " Il locale è accogliente e il menù "

iOS 7 is fine: " Il locale è accogliente e il menù "

iOS 6 is not: " Il locale Ë accogliente e il men˘ "

Any suggestion?

Extending to handle ordered lists

All installed in my project perfectly and doing its job. Except that I can't see how to extend it to handle more markdown than that included in the test suite - for example, ordered lists. From what I can see in markdown_parser.leg , markdown_output.m etc etc it should be capable, but even having defined a paragraph style in the Dictionary @forkey:@(ORDEREDLIST) it still comes out as a bulleted list rather than a numbered one.

What am I missing? Does the code need extending or am I missing something in configuration??

Github flavored markdown support

Current markdown_parser.leg working correctly with pure Markdown standart only. But nowadays Github Flavored syntax become very popular so it will be awesome to get support of it.

Issue with live parsing, cursor in wrong position causing 'backwards writing'

FIrst, great library, super useful.

I'm trying to implement a simple rich text editor with markdown being 'live' parsed. It's working with the exception of the cursor always appearing before the last entered character rather than after as in normal writing. Here are the two relevant methods;

#pragma mark - UITextView delegate

-(void)textViewDidChange:(UITextView *)textView {
NSAttributedString *prettyText = markdown_to_attr_string(self.tempMarkdownString,0,self.attributes);
self.textView.attributedText = prettyText;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
self.tempMarkdownString = [self.tempMarkdownString stringByReplacingCharactersInRange:range withString:text];
NSLog(@"'%@' text:%@ , loc:%d , len:%d → %@",textView.text , text , range.location , range.length , self.tempMarkdownString);

return YES;
}

If I don't use the textViewDidChange method parsing works on entering and exiting. When using it parsing does happen live but things are well, backwards. See image below.

iOS Simulator Screen shot 29 Jan 2013 11 19 23

xcode is looking for /Users/username/iPhone

Hi

While compiling the project (10.8.4/xcode 5/ios 7) i am getting this strange error :

make: /Users/username/iPhone: No such file or directory
make: *** No rule to make target `/Users/username/iPhone'. Stop.

Can you please tell me how to fix this?

Is there any mechanism for knowing the links for the corresponding formatted text after the text has been formatted?

If I have a bunch of links that AttributedMarkdown is to parse, such as [Github](http://github.com), is there any mechanism for linking the formatted text that just becomes "GitHub", to the URL it's linked to?

Basically, I'm building a system allowing you to tap on the formatted text to open the corresponding URL, but I'm not sure how to get this URL once the text has been formatted.

Are there any recommendations for doing so?

(Apologies if this isn't actually an "issue", so to speak.)

Sample project script error

I'm getting this error when trying to build the sample project, also getting when trying to integrate the library into my own project

/bin/sh -c "[ -f greg/Makefile ] || { cat <<MESSAGE; exit 1; }

AttributedMarkdown requires the greg parser generator.  Run the following to get it.

git submodule update --init --recursive

MESSAGE
make -C $TEMP_DIR -f $INPUT_FILE_DIR/greg/Makefile VPATH=$INPUT_FILE_DIR/greg || exit $?
$TEMP_DIR/greg -o $DERIVED_FILES_DIR/${INPUT_FILE_BASE}.m $INPUT_FILE_PATH"

make: *** /Volumes/Macintosh: No such file or directory.  Stop.
Command /bin/sh failed with exit code 2

looks like the path for the file isn't escaped out, but i couldn't track down where that path is getting called from and I have in fact run the "git submodule update --init --recursive" command.

not support unicode string

i'm a chinese.
when i use you code.i find that string is error.
so first ,i debug it.and fix it.
@implementation NSMutableString (Sugar)

    - (void)appendCharacter:(unichar)ch {
        if (ch > 127) {
            [self appendFormat:@"%@", [NSString stringWithCharacters:&ch length:1]];
    } else {
        [self appendFormat:@"%c", ch];
    }
}

@end

but still show error string...
the last i find the problem at line 6013 in markdown_parser.m

  yyok= yystart(G);

can you fix it ? thanks

Latest cocoapods compiles AttributedMarkdown using ARC

The latest update to cocoapods changed the default of requires_arc from false to true. The AttributedMarkdown podspec doesn't specify a value for requires_arc and so it ends up being compiled with -fobjc-arc, and subsequently dying.

not support unicode string

i'm a chinese.
when i use you code.i find that string is error.
so first ,i debug it.and fix it.
@implementation NSMutableString (Sugar)

    - (void)appendCharacter:(unichar)ch {
        if (ch > 127) {
            [self appendFormat:@"%@", [NSString stringWithCharacters:&ch length:1]];
    } else {
        [self appendFormat:@"%c", ch];
    }
}

@end

but still show error string...
the last i find the problem at line 6013 in markdown_parser.m

  yyok= yystart(G);

can you fix it ? thanks

The program is stuck

when I use this string "Fkrew[pfokw[eorfk[wekrf[ewrkf[werkf[pewrkf[perwokf[werkf[ewrfk[ewrkf[werfkwe[fk[wefkwerfewrfewrfew" in attributemarkdown cpu excess load and the program is stuck . I find that the higher the frequency used "[", the more severe the CPU load. please fix it, thaks a lot .

About install greg

After link static library, attr-markdown-iOS.
It shows this error message,

Intermediates/markdown.build/Debug-iphonesimulator/attr-markdown-iOS.build/greg: No such file or directory

I think this error relate to configure greg.

I git clone the project and run git submodule update --init --recursive at root directory

I just drag "greg" folder into "markdown" project, and go to "markdown" project add greg as Target dependencies, however it is not working, it show same error message.

I am new to this, can you please help with adding "greg" project? Thanks.

Pod install broken

platform.h is not included properly with the latest cocoapods install.

Distribute as CocoaPod

It would be awesome if this project could be distributed as CocoaPod from cocoapods.org. The pods system would especially be useful to automatically install dependencies as well. (It would probably mean that greg should also be distributed Cocoa Pod)

Parsing error

When I attempt to parse a NSString that contains a '<' or '>' then I end up getting a crash in memory (BAD_EXEC_ACCESS).

Is this a known issue?

Thanks

Example (edit to view raw text, GH formats it as markdown):

On Apr 16, 2013, at 7:56 PM, Matthew Strickland [email protected] wrote:

Test


Reply to this email directly or view it on GitHub.

Issue with font cascading

I have some simple markdown that just uses paragraph and strong styles. When your library generates the attributed string, the color of the strong style is correct, but instead of using the font I specified for STRONG, I get the standard paragraph font. Below are some logs to help clarify what I'm seeing. Any thoughts are appreciated, and thanks for the library.

(lldb) po paragraphAttributes
{
NSColor = "UIDeviceRGBColorSpace 0 0.294118 0.529412 1";
NSFont = "<UICTFont: 0x7b65e4e0> font-family: "Effra-Light"; font-weight: normal; font-style: normal; font-size: 21.00pt";
}

(lldb) po strongAttributes
{
NSColor = "UIDeviceRGBColorSpace 1 1 1 1";
NSFont = "<UICTFont: 0x7b6402e0> font-family: "Effra-Medium"; font-weight: normal; font-style: normal; font-size: 21.00pt";
}

        attributes[@(PARA)] = paragraphAttributes;
        attributes[@(STRONG)] = strongAttributes;
        NSString *rawText = @"This is regular paragraph text **and this is strong.**";

(lldb) po attributedString
This is regular paragraph text {
NSColor = "UIDeviceRGBColorSpace 0 0.294118 0.529412 1";
NSFont = "<UICTFont: 0x7b65e4e0> font-family: "Effra-Light"; font-weight: normal; font-style: normal; font-size: 21.00pt";
}and this is strong. {
NSColor = "UIDeviceRGBColorSpace 1 1 1 1";
NSFont = "<UICTFont: 0x7b65e4e0> font-family: "Effra-Light"; font-weight: normal; font-style: normal; font-size: 21.00pt";
}

Mach-O linker error on build

I am receiving the following error when building. This is using the latest and greatest xcode dev environment. Any thoughts?

screen shot 2014-11-30 at 10 22 35 pm

Thank you for the attributer markdown library. Also, does it support italics?

Paul

UPDATE - Figured it out. The lib had not been linked in. I guess I thought cocoapods would do that, but apparently not. Cheers

Bullet list and ordered list have different formatting

The issue is that the bullet list has an extra newline at the start of items list. Ordered list is missing a newline at the end of list items.

Link to current code:
https://github.com/dreamwieber/AttributedMarkdown/blob/master/markdown_output.m#L237

Proposed code change:

case BULLETLIST:
            //pad(out, 2);
            padded = 0;
            indentation+=1;
            print_attr_element_list(out, elt->children, attributes, merge(current, attributes[elt->key]));
            //pad(out, 1);
            indentation-=1;
            print_attr_string(out, @"\n",current);
            padded = 0;
            break;
case ORDEREDLIST:
            //pad(out, 2);
            padded = 0;
            print_attr_element_list(out, elt->children, attributes, merge(current, attributes[elt->key]));
            //pad(out, 1);
            print_attr_string(out, @"\n",current);
            padded = 0;
            break;

When using Cocoapods to install there are two warnings

I instalIed AttributeMarkdown via the Cocoapods installation, and I get two warnings from markdown_parser.m:

Unused function 'yy_NonAlphanumeric'
Function 'yy_HtmlBlockOl' is not needed and will not be emitted

I know the Cocoapods installation is in beta, but I was curious if there was any way to eliminate this issue before I install via the lengthier method.

Can't include as a dependency in a podspec - please post to cocoapods repo!

s.dependency 'AttributedMarkdown' #fails

#also fails
pod search AttributedMarkdown
[!] Unable to find a pod with name matching `AttributedMarkdown'

This is a pretty big drag. If I have a pod that I'm developing and I want to use AttributedMarkdown in it, I essentially can't. I can only access AttributedMarkdown from classes in my app, not classes in my pod that my app uses. (See here if you are incredulous...). I could do this if I were willing to not use_frameworks, but that locks me out of the new world of swift.

Things have changed with swift and cocoapods and those changes mean that AttributedMarkdown (now more than ever!) needs to be available via pod 'AttributedMarkdown' and without having to point to this git repo!

Issues linking library

Firstly, thanks for such a useful class - it's exactly what I was after!

However, I'm running into some problems trying to use it inside a project. I've tried following the instructions with a brand new project in case it was just my project that was causing problems but I still can't correctly load markdown_lib.h

The steps I've tried so far have been:

  1. Create a new Xcode project
  2. Drag the markdown.xcode file into the file window (this was taken directly from a clone of the git repository with the greg submodule initialised)
  3. Add the libattr-markdown-iOS.a within the "Link Binary with Libraries" pane of the target
  4. Add the flag "-ObjC" to the "Other Linker Flags" within the target
  5. At this point, the app won't compile but generate 6 errors. To fix these, include the CoreText framework

Once these 5 steps are complete, everything compiles but trying to do #import "markdown_lib.h" leads to a file not found error. I've tried variations (i.e. #import "attr-markdown-iOS/markdown_lib.h") to no avail.

If you could let me know where I'm going wrong I'd be very very grateful!

Thanks

Are newlines handled correctly?

I am not sure if newlines are handled correctly... Would like to know if it really is an issue with the library or if it's just me not knowing enough about markdown.

I have the following input

*italics*
**bold**
***bold italic***

And what I get is

italics bold _bold italic_

instead of:

italics
bold
_bold italic_

What would be the correct behaviour? And could I get my expected behaviour new lines using this library?

Thanks,
Georg

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.