Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: kontur-school-2014/01-mark
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: master
Choose a base ref
...
head repository: Anton92nd/01-mark
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
Checking mergeability… Don’t worry, you can still create the pull request.
  • 20 commits
  • 34 files changed
  • 1 contributor

Commits on Nov 4, 2014

  1. initialize project

    Anton92nd committed Nov 4, 2014
    Copy the full SHA
    bec1357 View commit details
  2. two tests added

    Anton92nd committed Nov 4, 2014
    Copy the full SHA
    dd3d3b7 View commit details
  3. test with <p> added

    Anton92nd committed Nov 4, 2014
    Copy the full SHA
    c4346d4 View commit details

Commits on Nov 9, 2014

  1. Copy the full SHA
    a14af4a View commit details
  2. parser class created

    Anton92nd committed Nov 9, 2014
    Copy the full SHA
    afee78e View commit details
  3. Copy the full SHA
    0ebf0ee View commit details
  4. tests project created

    Anton92nd committed Nov 9, 2014
    Copy the full SHA
    f85ad2a View commit details
  5. 3 readers tests added

    Anton92nd committed Nov 9, 2014
    Copy the full SHA
    3418e9d View commit details

Commits on Nov 10, 2014

  1. word reader added

    Anton92nd committed Nov 10, 2014
    Copy the full SHA
    dc9d3bd View commit details
  2. escape reader added

    Anton92nd committed Nov 10, 2014
    Copy the full SHA
    9e7fc66 View commit details
  3. separators reader added

    Anton92nd committed Nov 10, 2014
    Copy the full SHA
    ba12e0e View commit details

Commits on Nov 11, 2014

  1. parser created

    Anton92nd committed Nov 11, 2014
    Copy the full SHA
    eda2c0e View commit details

Commits on Nov 12, 2014

  1. Converter done, tests fixed

    Anton92nd committed Nov 12, 2014
    Copy the full SHA
    79f5a45 View commit details
  2. Converter reworked

    Anton92nd committed Nov 12, 2014
    Copy the full SHA
    383c16d View commit details

Commits on Nov 13, 2014

  1. Copy the full SHA
    9a7c1d4 View commit details
  2. Copy the full SHA
    7eef259 View commit details
  3. test files added

    Anton92nd committed Nov 13, 2014
    Copy the full SHA
    b2127f9 View commit details
  4. Copy the full SHA
    97f954d View commit details
  5. some refactoring

    Anton92nd committed Nov 13, 2014
    Copy the full SHA
    0ee7d19 View commit details
  6. BuildParagraphs reworked

    Anton92nd committed Nov 13, 2014
    Copy the full SHA
    113311a View commit details
63 changes: 63 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto

###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp

###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary

###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary

###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
6 changes: 6 additions & 0 deletions App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
122 changes: 122 additions & 0 deletions HtmlConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Mark
{
public class HtmlConverter
{
private static readonly Dictionary<TokenType, string> TypeToTag = new Dictionary<TokenType, string>
{
{TokenType.Code, "code"}, {TokenType.Underscore, "em"}, {TokenType.DoubleUnderscore, "strong"}
};

private static string ConstructHtmlParagraph(List<Token> tokens)
{
var newTokens = (new List<Token> { { new Token("", TokenType.Unknown) } }
.Concat(tokens)).ToList();
var treeEdges = BuildTree(newTokens);
return ConcatTree(treeEdges, newTokens, 0);
}

private static string ConcatTree(Tuple<List<int>,bool>[] edges, List<Token> tokens, int node, bool code = false)
{
var subTree = edges[node].Item1.Aggregate("", (str, i) =>
str + ConcatTree(edges, tokens, i, code || tokens[node].Type == TokenType.Code));
if (!TypeToTag.ContainsKey(tokens[node].Type) || edges[node].Item2)
return tokens[node].Value + subTree;
var tag = TypeToTag[tokens[node].Type];
if (tokens[node].Type == TokenType.Code)
subTree = tokens[node].Value + subTree;
var oldTag = tokens[node].Source;
return code ? oldTag + subTree + oldTag : "<" + tag + ">" + subTree + "</" + tag + ">";
}

private static Tuple<List<int>, bool>[] BuildTree(List<Token> tokens)
{
var treeEdges = new Tuple<List<int>, bool>[tokens.Count()];
for (var i = 0; i < treeEdges.Length; i++)
treeEdges[i] = new Tuple<List<int>, bool>(new List<int>(), false);
var stack = new Stack<Tuple<TokenType, int>>();
var counter = new Dictionary<TokenType, int>
{
{TokenType.Underscore, 0}, {TokenType.DoubleUnderscore, 0}
};
stack.Push(new Tuple<TokenType, int>(TokenType.Unknown, 0));
for (var i = 1; i < tokens.Count(); i++)
{
var token = tokens[i];
if (counter.ContainsKey(token.Type))
{
if (counter[token.Type] == 0)
{
counter[token.Type]++;
treeEdges[stack.Peek().Item2].Item1.Add(i);
stack.Push(new Tuple<TokenType, int>(token.Type, i));
continue;
}
while (stack.Peek().Item1 != token.Type)
{
treeEdges[stack.Peek().Item2] = new Tuple<List<int>, bool>
(treeEdges[stack.Peek().Item2].Item1, true);
if (counter.ContainsKey(stack.Peek().Item1))
counter[stack.Peek().Item1]--;
stack.Pop();
}
counter[stack.Peek().Item1]--;
stack.Pop();
}
else
treeEdges[stack.Peek().Item2].Item1.Add(i);
}
while (stack.Count() > 1)
{
treeEdges[stack.Peek().Item2] = new Tuple<List<int>, bool>
(treeEdges[stack.Peek().Item2].Item1, true);
stack.Pop();
}
return treeEdges;
}

private static IEnumerable<string> BuildParagraphs(IEnumerable<string> lines)
{
var result = new List<string>();
while (lines.Any())
{
lines = lines.SkipWhile(line => line.Trim().Length == 0);
if (!lines.Any())
break;
var paragraph = lines.TakeWhile(line => line.Trim().Length > 0);
result.Add(paragraph.Aggregate((sentence, line) => sentence + "\r\n" + line));
lines = lines.SkipWhile(line => line.Trim().Length > 0);
}
return result;
}

private static readonly string[] LineEndings = { "\r\n", "\r", "\n" };

public static string ConvertString(string content)
{
var lines = content.Split(LineEndings, StringSplitOptions.None);
var paragraphs = BuildParagraphs(lines);
var parsedParagraphs = paragraphs.Select(x => ConstructHtmlParagraph(Parser.Parse(x)));
return "<html><head><meta charset=\"UTF-8\"></head>\r\n<body>\r\n" +
parsedParagraphs.Aggregate("", (result, str) => result + "<p>\r\n" + str + "\r\n</p>\r\n") + "</body>\r\n</html>";
}

public static void ConvertFile(string fileNameWithExtension)
{
var text = File.ReadAllText(fileNameWithExtension);
var fileName = fileNameWithExtension.Substring(0, fileNameWithExtension.LastIndexOf('.'));
var result = ConvertString(text);
File.WriteAllText(fileName + ".html", result);
}

public static void Main(string[] args)
{
string fileName = Console.ReadLine();
ConvertFile(fileName);
}
}
}
76 changes: 76 additions & 0 deletions Mark.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A1ABAD85-C3BA-4B78-97C1-B16033E5863F}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Mark</RootNamespace>
<AssemblyName>Mark</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject>Mark.HtmlConverter</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="MoreLinq">
<HintPath>packages\morelinq.1.1.0\lib\net35\MoreLinq.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="HtmlConverter.cs" />
<Compile Include="Readers\CodeReader.cs" />
<Compile Include="Readers\EscapeReader.cs" />
<Compile Include="Readers\LineEndReader.cs" />
<Compile Include="Parser.cs" />
<Compile Include="Readers\SeparatorReader.cs" />
<Compile Include="Token.cs" />
<Compile Include="Readers\ITokenReader.cs" />
<Compile Include="Readers\UnderscoreReader.cs" />
<Compile Include="Readers\WhitespaceReader.cs" />
<Compile Include="Readers\WordReader.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
28 changes: 28 additions & 0 deletions Mark.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30723.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mark", "Mark.csproj", "{A1ABAD85-C3BA-4B78-97C1-B16033E5863F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{018BFEE2-F95A-4190-9D35-3CC83D73BF96}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A1ABAD85-C3BA-4B78-97C1-B16033E5863F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A1ABAD85-C3BA-4B78-97C1-B16033E5863F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A1ABAD85-C3BA-4B78-97C1-B16033E5863F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A1ABAD85-C3BA-4B78-97C1-B16033E5863F}.Release|Any CPU.Build.0 = Release|Any CPU
{018BFEE2-F95A-4190-9D35-3CC83D73BF96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{018BFEE2-F95A-4190-9D35-3CC83D73BF96}.Debug|Any CPU.Build.0 = Debug|Any CPU
{018BFEE2-F95A-4190-9D35-3CC83D73BF96}.Release|Any CPU.ActiveCfg = Release|Any CPU
{018BFEE2-F95A-4190-9D35-3CC83D73BF96}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
36 changes: 36 additions & 0 deletions Parser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mark.Readers;
using MoreLinq;

namespace Mark
{
public static class Parser
{
private static readonly List<ITokenReader> Readers = new List<ITokenReader>
{
new LineEndReader(),
new WhitespaceReader(),
new WordReader(),
new UnderscoreReader(),
new EscapeReader(),
new CodeReader(),
new SeparatorReader()
};

public static List<Token> Parse(string text)
{
var result = new List<Token>();
while (text.Length > 0)
{
var best = Readers.Select(x => x.ReadToken(text)).Where(token => token != null)
.Concat(new Token(text.Substring(0, 1), HttpUtility.HtmlEncode(text.Substring(0, 1)), TokenType.Unknown))
.MaxBy(token => token.Source.Length);
result.Add(best);
text = text.Substring(best.Source.Length);
}
return result;
}
}
}
36 changes: 36 additions & 0 deletions Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Mark")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mark")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1aa1ad33-80da-4736-a7f4-d5788e7f4e73")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
17 changes: 17 additions & 0 deletions Readers/CodeReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace Mark.Readers
{
public class CodeReader : ITokenReader
{
public Token ReadToken(string from)
{
if (!from.StartsWith("`"))
return null;
var i = 1;
while (i < from.Length && from[i] != '`')
{
i += from[i] == '\\' ? 2 : 1;
}
return i >= from.Length ? null : new Token(from.Substring(0, i + 1), from.Substring(1, i - 1), TokenType.Code);
}
}
}
Loading