Giter Site home page Giter Site logo

markdown-js's Introduction

NPM version Build Status Dependency Status

Notice: Unmaintained

This repo is no longer maintained, however there are many alternatives:

markdown-js

Yet another Markdown parser, this time for JavaScript. There's a few options that precede this project but they all treat Markdown to HTML conversion as a single step process. You pass Markdown in and get HTML out, end of story. We had some pretty particular views on how the process should actually look, which include:

  • Producing well-formed HTML. This means that em and strong nesting is important, as is the ability to output as both HTML and XHTML
  • Having an intermediate representation to allow processing of parsed data (we in fact have two, both JsonML: a markdown tree and an HTML tree)
  • Being easily extensible to add new dialects without having to rewrite the entire parsing mechanics
  • Having a good test suite. The only test suites we could find tested massive blocks of input, and passing depended on outputting the HTML with exactly the same whitespace as the original implementation

Installation

Just the markdown library:

npm install markdown

Optionally, install md2html into your path

npm install -g markdown

In the browser

If you want to use from the browser go to the releases page on GitHub and download the version you want (minified or not).

Usage

The basic interface is:

md_content = "Hello.\n\n* This is markdown.\n* It is fun\n* Love it or leave it."
html_content = markdown.toHTML( md_content );

toHTML also accepts a dialect argument:

md_content = "Vessel     | Captain\n-----------|-------------\nNCC-1701   | James T Kirk\nNCC-1701 A | James T Kirk\nNCC-1701 D | Picard";
html_content = markdown.toHTML( md_content, 'Maruku');

Node

The simple way to use it with Node is:

var markdown = require( "markdown" ).markdown;
console.log( markdown.toHTML( "Hello *World*!" ) );

ES6

import {markdown} from 'markdown';
console.log( markdown.toHTML( "Hello *World*!" ) );

Older versions of node

We only officially support node >= 0.10 as the libraries we use for building and testing don't work on older versions of node. That said since this module is so simple and doesn't use any parts of the node API if you use the pre-built version and find a bug let us know and we'll try and fix it.

Browser

It also works in a browser; here is a complete example:

<!DOCTYPE html>
<html>
  <body>
    <textarea id="text-input" oninput="this.editor.update()"
              rows="6" cols="60">Type **Markdown** here.</textarea>
    <div id="preview"> </div>
    <script src="lib/markdown.js"></script>
    <script>
      function Editor(input, preview) {
        this.update = function () {
          preview.innerHTML = markdown.toHTML(input.value);
        };
        input.editor = this;
        this.update();
      }
      var $ = function (id) { return document.getElementById(id); };
      new Editor($("text-input"), $("preview"));
    </script>
  </body>
</html>

Command Line

Assuming you've installed the md2html script (see Installation, above), you can convert Markdown to HTML:

# read from a file
md2html /path/to/doc.md > /path/to/doc.html

# or from stdin
echo 'Hello *World*!' | md2html

More Options

If you want more control check out the documentation in the .js files under src/ which details all the methods and parameters available (including examples!). One day we'll get the docs generated and hosted somewhere for nicer browsing.

Meanwhile, here's an example of using the multi-step processing to make wiki-style linking work by filling in missing link references:

var md = require( "markdown" ).markdown,
    text = "[Markdown] is a simple text-based [markup language]\n" +
           "created by [John Gruber]\n\n" +
           "[John Gruber]: http://daringfireball.net";

// parse the markdown into a tree and grab the link references
var tree = md.parse( text ),
    refs = tree[ 1 ].references;

// iterate through the tree finding link references
( function find_link_refs( jsonml ) {
  if ( jsonml[ 0 ] === "link_ref" ) {
    var ref = jsonml[ 1 ].ref;

    // if there's no reference, define a wiki link
    if ( !refs[ ref ] ) {
      refs[ ref ] = {
        href: "http://en.wikipedia.org/wiki/" + ref.replace(/\s+/, "_" )
      };
    }
  }
  else if ( Array.isArray( jsonml[ 1 ] ) ) {
    jsonml[ 1 ].forEach( find_link_refs );
  }
  else if ( Array.isArray( jsonml[ 2 ] ) ) {
    jsonml[ 2 ].forEach( find_link_refs );
  }
} )( tree );

// convert the tree into html
var html = md.renderJsonML( md.toHTMLTree( tree ) );
console.log( html );

Intermediate Representation

Internally the process to convert a chunk of Markdown into a chunk of HTML has three steps:

  1. Parse the Markdown into a JsonML tree. Any references found in the parsing are stored in the attribute hash of the root node under the key references.
  2. Convert the Markdown tree into an HTML tree. Rename any nodes that need it (bulletlist to ul for example) and lookup any references used by links or images. Remove the references attribute once done.
  3. Stringify the HTML tree being careful not to wreck whitespace where whitespace is important (surrounding inline elements for example).

Each step of this process can be called individually if you need to do some processing or modification of the data at an intermediate stage. For example, you may want to grab a list of all URLs linked to in the document before rendering it to HTML which you could do by recursing through the HTML tree looking for a nodes.

Building and Testing markdown-js

We use Grunt to build and run markdown-js's tests. Make sure you run npm install to install the developer dependencies for the project, then you can:

$ npm test

To run our test suite. If you'd like to build markdown-js, you can run:

$ ./node_modules/.bin/grunt all

This command will run all the tests, then output a concatenated markdown.js and markdown.min.js in the dist/ directory for use in a browser application.

Building a custom markdown-js

By default, you will get the Gruber and Maruku dialects included when you run grunt all. However, you can create a custom build using the following syntax if you don't want to include Maruku support.

$ ./node_modules/.bin/grunt "custom:-dialects/maruku"

Running Tests

To run the tests under Node you will need tap installed (it's listed as a devDependencies so npm install from the checkout should be enough), then do

$ npm test

Contributing

Do the usual GitHub fork and pull request dance. Add yourself to the contributors section of package.json too if you want to.

License

Released under the MIT license.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

markdown-js's People

Contributors

akzhan avatar ashb avatar ben-turner avatar briankung avatar cadorn avatar cannona avatar clement avatar elberet avatar ethanhann avatar evilstreak avatar eviltrout avatar geraintluff avatar harrysarson avatar imgss avatar isaacs avatar jiggak avatar kasperpeulen avatar kizu avatar matthewkastor avatar mishoo avatar mustmodify avatar novemberborn avatar pallaskatze avatar pgilad avatar richardharrington avatar rlidwka avatar sneakertack avatar somebox avatar xavi- avatar xhmikosr 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  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

markdown-js's Issues

Inline HTML not possible

Currently
console.log( require( "markdown" ).parse( 'heelo' ) );
will produce this:

<b>heelo</b>

Is this normal?

img_ref not converted to img

The Gruber dialect "![" handler can output an img_ref which is intended to be converted when forming the HTML tree, but there is no code in place to do so.

.

.

Open to documentation change to yuidoc?

This is a meta-issue, just wondering if you'd be willing to use the yuidoc format. I've wrapped this module in a YUI wrapper, but I'd like to also be able to generate standard documentation.

The format is quite easy and very clean, plus it has really great output.

You can read up on it here: http://yui.github.com/yuidoc/

The change is pretty minimal, and is just in formatting. Here is an example:

/** 
Take markdown (either as a string or as a JsonML tree) and run it through
[[toHTMLTree]] then turn it into a well-formated HTML fragment.

@method toHTML
@static
@param source {String} markdown string to parse
@param dialect {String} dialect to use

**/

If open, please let me know and I'll submit a pull request with the documentation updated and an example YUIDoc page generated (which will be on my gallery module, which you can see at http://j.shirley.im/tech/yui/gallery-markdown/)

Thanks,
-Jay

Keep original text

I was wondering what it would take for the generated HTML to keep the original formatting text

aka, # This Text
would produce

# This text

Thanks!

Maruku/meta/list tests fail

edit: Ash renamed the bug to talk about the failure, not the error in the runner which is now fixed.

Checked out trunk (8b3cc2f) and with patr v0.2.6 and promised-io v0.2.3, I get the above. Modified the test to be more verbose, and in more detail:

AssertionError: Failed with error on /home/kragen/devel/markdown-js/test/features/meta/list.text: AssertionError: list; expected:
["html",
  ["ul",
    { "id" : "list" },
    ["li",
      "here's a\nloose list"
    ],
    ["li",
      "it might confuse the\nblock_meta routine"
    ]
  ]
]
got:
[
  "html",
  [
    "ul",
    [
      "li",
      [
        "p",
        "here's a\nloose list"
      ]
    ],
    [
      "li",
      [
        "p",
        "it might confuse the\nblock_meta routine\n{: #list}"
      ]
    ]
  ]
]

Despite the suggestion in the paragraph itself, the problem does not seem to be in Markdown.dialects.Maruku.block.block_meta; somehow, mysteriously, processBlock is not getting called for the last block, and so neither is block_meta.

Undeclared variables

js: warning: "markdown.js", line 925: Assignment to undeclared variable i
js: warning: "markdown.js", line 936: Assignment to undeclared variable i

Using evilstreak to output html.

i use this, it works quite nice.

        // get markdown content  
        var body_location = 'markdown/README.markdown';

        function getText(myUrl){
            var result = null;
            $.ajax( { url: myUrl, 
                      type: 'get', 
                      dataType: 'html',
                      async: false,
                      success: function(data) { result = data; } 
                    }
            );
            FileReady = true;
            return result;
        }

        var markdown_source = getText(body_location);

        // convert markdown to html
        var output = markdown.toHTML( markdown_source );
        document.write(output);

Errorneous link_ref

This text: foo [bar] baz parses as:

[ 'markdown',
  [ 'para',
    'foo ',
    [ 'link_ref', { ref: 'bar', original: '[bar]' }, 'bar' ],
    ' baz' ] ]

The original markdown outputs <p>foo [bar] baz</p> which is more like what I'd expect—it's not really a link. I can't find the single [foo] as valid syntax in the Markdown spec, so I assume this is a bug...

Links in parens break

I have something like this:

Lorem ipsum (lorem ipsum) dolar sit amut.

However, the last closing paren is removed. I am getting something like this instead:

Lorem ipsum (lorem ipsum dolar sit amut.

Github does this correctly, as does dingus.

I tracked it down to markdown.js:823,

/^\[([\s\S]*?)\][ \t]*\([ \t]*(\S+)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/

This regex is greedily matching up to the last ).

Doesn't work in the browser

It complains about line 152 in markdown.js.

if ( ( m = (/^(\s*\n)/)(input) ) != null ) {

It doesn't like that calling of an expression as it were a function.

Ideas? Is this meant to work in the browser? Thanks

Ability to generate an anchor on a header, or insert an anchor in the markdown.

Love this tool! I've got a parser that scans my markdown and generates a Table of Contents based on headers. However, markdown.js doesn't have the ability (that I can find) to output an html anchor.

I've hacked it to work for me by modifying the render_tree function, but it's suboptimal. I'd like to either a) simply place a token in my code that would get turned into an html anchor or b) figure out how to escape literal html in my markdown.

It'd be great if an owner could suggest the proper way to implement this, and if a feature is needed I'll happily fork and fix.

.

.

Code blocks in lists

Code blocks in lists do not work. Example:

This is a paragraph:

  * **Heading 1**

    Paragraph.

        JavaScript();

  * **Heading 2**

    Paragraph.

        JavaScript();

        JavaScript();

    Paragraph.

I took a look at the code but that part is pretty involved. Hoping someone more familiar with it can fix it.

why code fencing not work

i run the first example(with a textarea) on the latest chrome。 Blockquotes, code , code fencing don't wok out complete style. TX

link regexp correction

THe regexp in function link() :
/^\[([\s\S]*?)\][ \t]*\([ \t]*(\S+)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/
is triggered by :
[to put it another way][SECTION 1] or even [link this](#SECTION-1)
outputs :
["[to put it another way][SECTION 1] or even [link this](#SECTION-1)", "to put it another way][SECTION 1]or even [link this", "#SECTION-1", undefined, undefined]

Instead, using :
/^\[([^\[\]]*?)\][ \t]*\([ \t]*(\S+)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/
fixes the issue.

Paragraph tag added to last items in lists

The following markdown results in the last items of the lists having a stray <p> tag created:

1. **Mode**

 The following modes are available:
 * 0 = Port Off
 * 232 = RS232 (handshaking determined via the <FlowControl> setting)
 * 485H = Half-duplex RS485
 * 4XXF = Full-duplex RS485 or RS422

1. **BaudRate**

 The following baud rates are available:
 * 100 
 * 300  
 * 600 
 * 1200
 * 2400
 * 4800
 * 9600
 * 14400
 * 19200
 * 38400
 * 57600
 * 115200
 * 128000
 * 256000

1. **DataBits**

 The following data bits are available:
 * 8 = 8 Data Bits

1. **Parity**

 The following parity types are available:
 * N = No Parity
 * O = Odd
 * E = Even
 * S = Space
 * M = Mark

Resulting HTML:

<ol><li><p><strong>Mode</strong></p><p>The following modes are available:</p><ul><li>0 = Port Off</li><li>232 = RS232 (handshaking determined via the &lt;FlowControl&gt; setting)</li><li>485H = Half-duplex RS485</li><li><p>4XXF = Full-duplex RS485 or RS422</p></li></ul></li><li><p><strong>BaudRate</strong></p><p>The following baud rates are available:</p><ul><li>100 </li><li>300   </li><li>600 </li><li>1200</li><li>2400</li><li>4800</li><li>9600</li><li>14400</li><li>19200</li><li>38400</li><li>57600</li><li>115200</li><li>128000</li><li><p>256000</p></li></ul></li><li><p><strong>DataBits</strong></p><p>The following data bits are available:</p><ul><li><p>8 = 8 Data Bits</p></li></ul></li><li><p><strong>Parity</strong></p><p>The following parity types are available:</p><ul><li>N = No Parity</li><li>O = Odd</li><li>E = Even</li><li>S = Space</li><li>M = Mark</li></ul></li></ol>

Notice how each last item of a list is the only one that has the <p>.

jsonML/markdownTree docs in Wiki/README

Hi, Dominic

I hope there would be a reference to guibe me dealing with markdownTree result. So I can write my renderers targetting at other format, instead of HTML.

Thanks.

Allow whitespaces in links between [Alt text] and [id]

Hi,
i just figured other markdown tools assume one can put whitespaces there.
Here's a simple patch :

From c195026631d0c2a735776b2d2f6cc474fd167d9e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Lal?= <[email protected]>
Date: Mon, 24 May 2010 16:58:42 +0200
Subject: [PATCH] Allow whitespace in links [] []

---
 lib/markdown.js |    2 +-
 1 files changed, 1 insertions(+), 1 deletions(-)

diff --git a/lib/markdown.js b/lib/markdown.js
index 58c6b79..899a724 100644
--- a/lib/markdown.js
+++ b/lib/markdown.js
@@ -831,7 +831,7 @@ Markdown.dialects.Gruber.inline = {

       // [Alt text][id]
       // [id]
-      m = text.match( /^\[([\s\S]*?)\](?:\[(.*?)\])?/ );
+      m = text.match( /^\[([\s\S]*?)\][ \t]*(?:\[(.*?)\])?/ );

       if ( m ) {
         // [id] case, text == id
-- 
1.7.1

Image tags not well formed (HTML5 spec)

markdown.toHTML('![image](/path/to/image.jpg)'); renders <p><img alt="image" src="/path/to/image.jpg"></img></p> which is invalid html5. Empty image tags should be self closing.

code block mis-escaped

For example:
\t\techo "x" > /tmp/file

will be translated to:

echo "x" > /tmp/file

Then in chromium, the > is not show as ">".

hr abutting a spaced list crashes

The following is interpreted as an hr abutting a list, and then throws. (I was hoping for a heading not an hr, obviously.)

1. First
2. Second

1. First
--------

Backtrace, from 4816d73:

markdown.js:370
        jsonml.unshift.apply( jsonml, this.processBlock( m[ 1 ], [] ) );
                                           ^
TypeError: Object #<an Object> has no method 'processBlock'
    at Object.horizRule (markdown.js:370:44)
    at Markdown.<anonymous> (markdown.js:620:41)
    at Markdown.processBlock (markdown.js:197:29)
    at Markdown.toTree (markdown.js:234:20)
    at Object.parse (markdown.js:66:13)
    at Object.toHTMLTree (markdown.js:97:48)
    at Object.toHTML (markdown.js:79:22)

Support for in-page links?

There are several specs and recommendations for doing in-page links in markdown.
None of them seem to work in this library, for either the Gruber or Maruku dialect.

### title ###    {#anch}
### title ###    {: #anch}
{#anch}
-----------
{: #anch}
-----------
<a id="anch"></a>
### title ### (expect an auto-created id from the title)

What do you suggest?

Windows linebreak issues

I found that markdown.js is having trouble parsing through windows linebreaks.
For example, with code blocks:

    This is code
    Is this also code?

Which produces this output:

<pre><code>This is code</code></pre>

<p>
    Is this code?</p>

Is this something the library should handle or do I have to keep normalizing the linebreaks before I parse?

link parse not correct

use markdonw.parse the following md string:

JavaScrip((as[nodeJS](http://nodejs.org))and[webdriverNode](https://github.com/neekey/webdriverNode).

which will out put:

<p>JavaScript( as<a href="http://nodejs.org))and[webdriverNode](https://github.com/neekey/webdriverNode">nodeJS</a>.</p>

hope to fix!

Keep code format

Hi, I want to know how show it works for a code block and keep the codes format.
I use it like this
function flipbook_theme() { return array( 'flipbook' => array( 'template' => 'flipbook', 'variables' => array('node' => NULL), ), ); }
but he shows these code in one line, pls help.

HTML support

would be really nice, and bring it closer to the discount implementation

Simple strong/em case fails to be parsed (***foo bar***)

The the sample case of ***foo bar*** fails to parse correctly.

It should be parsed as ["em", ["strong", "foo bar"]] but is instead parsed as [["strong", "*foo bar"], "*"].

However if spaces are added (* **foo** *), it produces the correct HTML.

Links not parsed in headers

Having a header such as: ### Install [foo](http://github.com/bar) ### won't parse the inline link between the tags.

Problem with npm install

Hi,

NPM can not install markdown-js:

Error: Not found: markdown-js@'>=0.1.0'

Did you added your module to npm?

Adding a minified version

I know, you can do it yourself, but I think it'd be good to add a minified version of the code to this repo.

"overlay" no longer supported in npm 0.3

Sorry, the "overlay" functionality had to go for various reasons.

Any chance that you could move the "main" field to the top-level, and rename the package "markdown" instead of "markdown-js"?

test with npm test

It would be easier to get acquainted with this package if package.json was set up to support running the test suite with npm test. I'm interested in coding this up myself but I haven't started yet.

Please add a license

Hi there. It would be very helpful from a distribution packaging point of view if you could include a copy of the MIT license with your software, usually in a file called LICENSE.

Thanks!

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.