Coder Social home page Coder Social logo

markdig.wpf's Introduction

Important

Because of a lack of time and interest, this repo is archived. If my situation changes, I might unarchive it. For the time being, consider forking it or use an alternative. Existing Nuget packages will still be available.

Markdig-WPF NuGet NuGet

A WPF library for lunet-io/markdig

The project is split into two parts:

The WPF renderer allows you to transform markdown text to an equivalent FlowDocument that can then be used in a WPF control. For convenience an implementation of such control is given in MarkdownViewer.

The XAML renderer outputs a string in a similar way as the HTML renderer. This string can then be saved into a file or parsed by an application. It is less complete compared to the WPF renderer.

Markdig.Xaml.SampleApp illustrates a way to utilize the parsed XAML at runtime. It should be fine for small documents but might not be the best way for bigger one.

Features

Supports all standard features from Markdig (i.e. fully CommonMark compliant).

Additionally, the following extensions are supported:

  • Auto-links
  • Task lists (WPF renderer only)
  • Tables (partial support of grid and pipe tables) (WPF renderer only)
  • Extra emphasis

markdig.wpf's People

Contributors

abaniuszewicz avatar davidholsgrove avatar goldie83 avatar grokys avatar jackgriffiths avatar kryptos-fr avatar nbusseneau avatar thoemmi avatar virzak 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

markdig.wpf's Issues

Design question: Why did you split the rendering in two seperated code trees?

Why I ask

  • I need both, Text and Wpf output in the same quality and I am lazy enough to do not take care of two code bases.
  • I have experience with the XamlParser of the .net framework, so I did a quick and dirty test with your library to show the way:
    neolithos@d1d5630

What are the changes
The XamlRenderer emits xaml nodes, now. No text anymore.
I replaced the two methods ToXaml and ToFlowDocument to use only this output. WpfRenderer is not used anymore.

Advantages

  • Only one codebase for the xaml code.

Disadvantags

  • It might consume more time and resources.

What is to do

  • A clean rewrite of the WpfRenderer with the XamlRenderer as backend in a higher code quality.
  • Add a simple enough framework to emit xaml nodes, I am not happy with my current Q&D solution.

I can do this in your/this project, and I also will help you to maintain the library. Will you accept a pull request, when I am done? Or should I start a new project for this task?

Make classes customizable

Hi,

thanks for providing the code. I love his clear and easy structure!

I made some changes on a local branch, which make it possible to customize the WPF Renderer.
So I declared some functions as protected and added also some optional parameter.

I also made the WPF Image clickable. So if you click an image the associated command will be executed. In my case to zoom into it.

I would like to share it with you

Best
FC

Target .Net 4.5.0 instead of .Net 4.5.2

Hello,

Awesome repo it makes using Markdown in a WPF form a breeze. Would you accept a pull request to have markdig.wpf target .net framework 4.5.0 instead of 4.5.2? The Markdig project itself targets 4.5.0 and targeting version 4.5.2 really limits the number of machines this can be used on without first ensuring the framework is installed. Windows 10 was the first release that shipped with support for v4.5.2 and above so for any machine running Windows 8 and lower we can't assume that v4.5.2 will exist.

Focus issues

Hello,

I'm using a MarkdownViewer in a WPF app I'm working on. I've run into some issues with focus:

  1. MarkdownViewer.Focusable is enabled by default which is probably going to be surprising to most users since it's a read-only control (I just disabled it myself).
  2. If NewsViewer.Markdown is empty, tabbing in the app still ends up giving focus to some hidden element within the viewer (not sure which).
  3. If NewsViewer.Markdown contains a hyperlink, tabbing will eventually give focus to that hyperlink, in addition to the previous point.

What I'd like to achieve is not allowing focus on any element within the MarkdownViewer. Is this possible?

Nuget Package

Hi,

I like what you are building. Are you planning on releasing it on Nuget?

Links not work at all

I made MD hyperlink with []() syntax and see that link is rendered properly in a FlowDocument. BUT... when I click link, nothing happens! Why? I expect link will open browser with given URL.

When I investigated this bug, people also had the same problem, but with normally created FlowDocument. They simply assign to link RequestNavigate handler and in a handler they call Process.Start(). I tried the same with your FlowDocument, but no luck - this handler never ever called. In WPF logs I saw no error, so code is OK. When I manually created Hyperlink and assigned RequestNavigate, code works. That means your WPF renderer creates "invalid" Hyperlink that it cannot even call own handler.

Solution: make please link behave as a link! Not a huge job, but annoying when link doesn't behave as it must.

Update to allow rendering into an exciting FlowDocument with content and styling

Hi there -- I'm looking for a component that I can use to render (commonmark) markdown into a flow document. markdig.wpf looks awesome -- except the flow document I'll be rendering into already has content and styles and such. I want to append the rendered markdown into the document without any assumptions about what might already be in the flow document or how it might be styled. A quick skim of your code seems to show that you'll probably work OK if appending, but you do seem to make some assumptions about being able to set the style of the document overall which may collide with any styling already on the flow document. Any thoughts about this scenario?

Update to markdig 0.17.1

Markdig was updated to version 0.17.1 on 2019-07-04.

  • Go through the changelog and see what can/should be enhanced on WPF side.
  • Package normal and signed versions

See also #27.

How to styel Markdown Code

I have an issue theming for code
Markdig version : 0.5.0.1
VS version: 2022 preview 3.0;
image

It seems that markdig has style for codes
image.

However, what target framework controls the style that should be applied? should it be applied to Textblock or something else?

Nuget package doesn't apply to .Net 4.5 project

Hi,

Thanks for providing this awesome code to make Markdown in WPF much easier!
I am from VisualStudio setup team and we are considering using this package in a .Net 4.5 project for Markdown support. I do saw the change to retargeting the project to .net 4.0, but it seems the nuget package on market still only targeting .Net 452. I am wondering could you please take a look?
Really appreciate your help!

Best,
Menglu

[Assistance Request] AutoLinks and Images Not Working

Issue

First off, let me start by saying that from what I can see in the sample app, this control is amazing - literally exactly what I need.

I am having some issues with getting my markdown to render correctly - I am using databindings to display the information, so I don't know if that is the culprit or not. The markdown itself displays, and some of the extensions work (e.g. pipe tables), but not all of them. Specifically:

  • AutoLinks: the text is underlined, but is not rendered as a clickable link
  • Images: I am getting an error: Exception = Invalid URI: the format of the URI could not be determined. I have a feeling that this may be related to #9
  • Super/Sub Script: Text is rendered at normal height

For posterity, my code snippets are below:

View

The Markdown property is bound to the Contents value (typeof string) of the SelectedItem of a list in another control; Pipeline is bound to a MarkdownPipeline that is created in the ViewModel. As stated above, the Contents renders in the MarkdownViewer, just without some extensions working properly.

<wpf:MarkdownViewer 
      Markdown="{Binding ElementName=userGuidePagesListView, Path=SelectedItem.Contents}"
      Pipeline="{Binding MarkdownPipeline}" />

ViewModel

The Contents property is set by extracting the data from embedded resources files to a string

public class UserGuideViewModel : ViewModelBase
{
  public MarkdownPipeline MarkdownPipeline = new MarkdownPipelineBuilder()
      .UseAdvancedExtensions()
      .UseEmphasisExtras()
      .UseAutoLinks()
      .UseEmojiAndSmiley()
      .Build();

  private List<UserGuidePage> _userGuidePages = new List<UserGuidePage>();
  public List<UserGuidePage> UserGuidePages
  {
    get { return _userGuidePages; }
    set
    {
      if (_userGuidePages != value)
      {
        _userGuidePages = value;
        RaisePropertyChanged("UserGuidePages");
      }
    }
  }

  public UserGuideViewModel()
  { RenderUserGuidePages(); }

  private void RenderUserGuidePages()
  {
    UserGuidePages = new List<UserGuidePage>();
    string[] delimiter = new string[] { "UserGuide." };
    string[] markdownFiles = assembly.GetManifestResourceNames();
    foreach (string resource in markdownFiles)
      {
        if (resource.Contains("UserGuide") && resource.Contains(".md"))
        {
          UserGuidePage userGuidePage = new UserGuidePage();
          userGuidePage.Title = resource.Split(delimiter, StringSplitOptions.None)[1].Split('.')[0].Replace("-", " ");
          userGuidePage.Contents = GetPageContent(resource);
          UserGuidePages.Add(userGuidePage);
        }
      }
    }
  }

  private string GetPageContent(string resource)
  {
    using (Stream stream = assembly.GetManifestResourceStream(resource))
    {
      using (StreamReader streamReader = new StreamReader(stream))
      { return streamReader.ReadToEnd(); }
    }
  }

Screenshots (Annotated)

Screenshots below; I am also using the same markdown files for the Wiki on GitHub, and have included the links to those pages so that proper rendering can be viewed

Home

Using the Software

Change Log

Thank you in advance for the help!

Port to .net core 3.0

WPF is coming to .net core now. Is there any plan to port markdig.wpf to .net core 3.0?

Intra-document links not created correctly

Given this markdown:

- [`cryptography` functions](#cryptography-functions)

LinkInlineRenderer.Write receives a LinkInline object, with a Url property of "#cryptography-functions".

Line 30 calls Uri.IsWellFormedUriString and since that returns false, the URI that is written is #.

Update to Markdig 0.21.1

Currently, I am unable to update to the latest version of Markdig (0.21.1), as it is deemed to be incompatible with the latest release of Markdig.Wpf (0.3.1)

Style difference with nested list and normal list

Hi,

Thanks for providing this awesome code to make Markdown in WPF much easier!
I am from VisualStudio setup team and we using this package for Markdown support. We are having some rendering issues about nested list that hope can get your help. As you can see from the below image, the space/new line rendering of nested list is different from normal list, looks like the extra "\r\n" we added are ignored. We tried different way to workaround this issue, one way is to add "&nbsp;\r\n" as a new line. But it is slightly different. So I am wondering do you have some other suggestions here?

image
image

The render of github markdown: it keeps the new line

  1. Save your work before continuing. We need to close the following process:

    • Microsoft Visual Studio master (devenv)

    Select Continue to save its current state, close it, and restart it if it is a non-elevated process when the installation is done.

  2. Your machine is busy installing a program other than Visual Studio.

    Select Continue to install Visual Studio while the other install is running. This might cause problems with other parts of the installation.

    Select Retry to continue with the Visual Studio install once the other install has completed.

    Select Cancel to cancel the Visual Studio install.

ToXaml doesn't work for me

Following the same code as given in the sample

    var markdown = File.ReadAllText("Documents/Markdig-readme.md");
    var xaml = Markdig.Xaml.Markdown.ToXaml(markdown);
    FlowDocumentScrollViewer Viewer = new FlowDocumentScrollViewer();
    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xaml)))
    {
        var reader = new XamlXmlReader(stream, new MyXamlSchemaContext());
        var document = System.Windows.Markup.XamlReader.Load(reader) as FlowDocument;
        if(document != null)
        {
            Viewer.Document = document;
        }
    }

I get an exception on System.Windows.Markup.XamlReader.Load(reader) as FlowDocument;
Here's the exception's message.
Provide value on 'Systems.Windows.StaticResourceExtension' threw an exception. Line number '1' and line position '178'.
EDIT:
Here's what the innerexception's message says "Cannot find resource named 'TargetType=Markdig.Wpf.Styles ID=DocumentStyleKey'. Resource names are case sensitive.".

help!

Hello
How to set text alignment in xaml files?
The width is always stretched by default. How to cancel the always stretch in the xaml file? I want to stretch the width based on the size of the content.
I tried using styles to solve the text alignment problem, but the width is always stretched by default, so the effect is not ideal.

The type initializer for 'Markdig.Wpf.MarkdownViewer' threw an exception

The code below doesn't compile with new version of markdig (0.15.5)

open FsXaml

type TestWindowBase = XAML<"TestWindow.xaml">

type TestWindow(md) as self =
     inherit TestWindowBase ()

     do self.mdviewer.Markdown <- md

let sampleMD = """
| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |
"""

let window = sampleMD |> TestWindow 

[<EntryPoint>]
[<System.STAThread>]
let main argv =
    System.Windows.Application().Run window

where TestWindow.xaml is:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:markdig="clr-namespace:Markdig.Wpf;assembly=Markdig.Wpf">
    <Grid>
        <markdig:MarkdownViewer Name="mdviewer" />
    </Grid>
</Window>

It works fine with 0.15.4 although.

Incorrect space between EmphasisInlineElements

In markdown like a**b**c or H~2~O, there is a space inserted between the emphasized element and the next element. This is caused by the function WpfRenderer.EndsWithSpace, which returns (IMHO correctly) that there is no space at the end of the emphasized element, and then the function AddInline inserts a space.

What is the best way to avoid the incorrect insertion of the space?

Heading color does not change.

image

<UserControl ...
             Loaded="LicenseDialog_OnLoaded">
  <FlowDocumentScrollViewer x:Name="FlowDocumentScrollViewer" />
</UserControl>
private void LicenseDialog_OnLoaded(object sender, RoutedEventArgs e)
{
    var licenseContent = File.ReadAllText("License.md");
    var flowDocument = Markdown.ToFlowDocument(licenseContent);
    flowDocument.Foreground = Brushes.White;
    FlowDocumentScrollViewer.Document = flowDocument;
}

License.md

### License

Test license.
**Test license.**
Test license.
Test license.
...

Theme Customization

Hi, thanks for your library, it's really handy!

Is there a way to customize the theme? I am not sure how I can replace default generic.xaml with a new set of style definitions. Thanks.

I mean, except creating a file under "Themes/generic.xaml" and in application resource add merge resource dictionary as mentioned here:

<ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Themes/generic.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

That is, is there a way to procedurally configure styles?

Also I do not see in Style.cs a definition for Bold, italic and normal text styles, can you provide some instruction on where those are defined or how can I change it? For instance I would like to change bold text to foreground of "White" in my application's dark theme.

Link on image causes issues when linking to other site than the image itself

Hi!

The feature with clickable/linking images causes issues when you want to link to another site than the image itself.

Example:
![Alt text for image](https://img.youtube.com/vi/C0DPdy98e4c/0.jpg)]
This will link to the videos thumbnail.
Alt text for image

If you implement the command binding like this:
private void HyperlinkCommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e) { Process.Start(e.Parameter.ToString()); }

I have tried to wrap the image with a link, like this:
[![Alt text for image](https://img.youtube.com/vi/C0DPdy98e4c/0.jpg)](https://www.youtube.com/watch?v=C0DPdy98e4c)
Alt text for image
But this will still direct you to the image link.

I have tried not to implement the command binding for images, this results in the image not being clickable at all.

Is the feature with linking images necessary when you can achieve the same result when wrapping an image in a link?

Use of markdig.signed?

Hi,

Do you intend on releasing a version that uses markdig.signed instead of markdig?

Rework extensions setup and dependency

When an extension to the pipeline is not selected, the corresponding renderers should not be included. Additional styles should also live separately from the common styles.

So for example TaskList is an extension (see PR #3 ). It declares a new style key TaskListStyleKey that it uses for CheckBox. And it also has its own renderer TaskListRenderer.

When setting up the pipeline and the WpfRenderer we should query which extensions are available and only include the corresponding renderers.

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.