• Shame, no more than two months, nuggets domain name from juejin. Im to juejin. Cn;
  • Recent situation, I still write Android basic business wrote some numbness, technology does not advance backward;
  • Take a break, occasionally update a Python crawler tutorial or two, have a persistent problem → article layout.

0x1. Requirement Analysis

Write articles using Markdown syntax and then convert them using Markdown conversion tools. Common tools include:

  • Markdown conversion tool: blog.didispace.com/tools/onlin…
  • Md2All:md.aclickall.com/
  • MPEditor: js8. / MPEditor/in
  • Markdown Nice:www.mdnice.com/

Converted article style (Md2All as an example) :

Not bad, simple enough. However, it is always difficult to be satisfied with the status quo, and three factors made me want to change:

  • After all, the tool is not open source, you use others to use, the style is bad street, are changing colors, replacing pictures, aesthetic fatigue;
  • Brother gave me the amway public number edit plug-in, such as new media butler (cool), one companion assistant, xiu meters, 135, small ants, etc.;

As a firefly in the dark, how blandly ordinary, so spend some time, to customize their own article layout ~

In the participation (Chao) test (XI) after a number of public number, sorted out their own public number typesetting standards, there is a need to refer to a wave ~

# Spacing: (1, 1.5) # line spacing: (1.5, 1.75, 2) # margin: that is, double indentation, both ends of the alignment, the page left and right white, the recommended indentation size is 1.0 # font color: Title #000000; The body of the # 4 c4c4c; Marked with # 888888; Other #B2B2B2 # text can also be tried: #545454; # 3 f3f3f; # 7 f7f7f; In addition to the font color, the public typesetting color should not be more than three, once the color is more, it is difficult to determine the style, 2-3 is better; # Like my three colors: Remblue; Ram powder #FF4081; Emilia: #C65BDA # Symbol system: Create your own symbol system and use it for content segmentation, such as ////////// for large paragraphs of text, - for summaries of paragraphs, and sometimes use emoticons to spice things up: http://cn.piliapp.com/symbol/ # no matter how, want to have their own fixed Settings, such as: The space between paragraphs and pictures should be 2 lines, the size of pictures should be controlled within 1/3 of the area of a screen, no more than 3 lines of words should be used in a paragraph, and when a screen is too full of words, paragraphs should be broken up for segmentation or highlights to create a sense of space, etc. # All in all, try to optimize the reading experience with simple basic Settings, so that the overall layout looks simple but orderly, not dense, not heavy, not depressing. # Use fixed format of official number cover image!! # The fixed format forms a strong personal characteristic. To make a new cover image, you only need to replace the text and picture, which is beautiful and convenient.Copy the code

Specific effects can be seen: mp.weixin.qq.com/s/why-ikTbb…

General style, in fact, the following several:

And every time I finish writing an article and want to publish it to the public account, I need to do this:

For (one line: all content) {when(one line) {is 1 headline → Apply 1 headline style is 2 headline → Apply 1 headline style is body → Apply body style... }}Copy the code

It’s repetitive, it’s a lot of work, especially copying and pasting forms, it’s hopeless, it’s a lot of content, it takes half an hour, it kills enthusiasm… I desperately needed a tool to help me out of this dilemma, not fully automated, but to minimize the time I spent on typography.

0x2. Tool Design

The core of the conversion tool: → Parsing Markdown files → rendering specific types of elements → generating HTML files

The rendering here is actually not that deep, using the Md2All tool as an example, type: # level 1 title

Click Copy, paste it to an IDE, save it as an.html suffix, and format it:

Since the wechat official account does not support CSS and JS(but SVG), it can only write inline styles in HTML tags. So, rendering here is really just replacing the corresponding HTML code with inline styles when parsing to a particular type of element.

So, if you want to write a tool like this, the point is:

  • (1) Parsing Markdown can distinguish different types of elements;
  • ② ALL kinds of HTML code with styles;

First, the problem of Markdown was analyzed. In the spirit of not building your own with wheels, I directly searched the keyword Python Markdown and chose Mistune among many libraries.

To get style HTML, use Elements from Chrome developer tools, for example:

Look at the style, direct steal, advise the kind of young people with rotten street conversion tools mouse feed juice ~

Of course, the style may need to be fine-tuned, and then the tool development process

0X3. I snapped and stood up, soon

Mistune is used to parse Markdown. A brief introduction to this library:

  • One of the fastest pure Python Markdown fast parsers yet, inspired by marked.
  • Official warehouse: github.com/lepture/mis…
  • The official document: mistune. Readthedocs. IO/en/latest /

Install a wave directly with the PIP command:

PIP install mistune = = 2.0.0 a4Copy the code

Usage is also very simple, write a simple Demo experience experience:

The default rendering style obviously can not meet our needs, we need to define a custom renderer, define a renderer mistune.HTMLRenderer subclass, rewrite the corresponding function can be. ## ## ## ## #

The output is as follows:

Then plug it into the article editor to verify that wechat does not support pasting source code, with the help of developer tools, locate the text element, right-click:

Paste a wave:

Go back to the editor and see what it looks like:

Can, consistent with the expectation, the gameplay is probably like this, and then is the refinement and optimization of the specific logic. More in the renderer to rewrite the function can refer to the following links: mistune. Readthedocs. IO/en/latest/a…

0x4. The pine cone flicks the lightning whip

Then record the details of the development of this tool, interested in customizing can be used for reference, not interested in directly skip with finished products can also, the follow-up will slowly update some themes, also welcome to contribute ~

① Whip → style collection example

[bug Mc-10868] – There are some unusable elements when copying elements with the helper plugin:

Some cleanliness, write a regular cleaning:

Clean finish:

BeautifulSoup: BeautifulSoup: BeautifulSoup: BeautifulSoup: BeautifulSoup: BeautifulSoup

Take a look at the effect:

Yes, comfortable up↑, the subsequent collection of styles, first put in the pool to clean, and then use, can also add new filtering rules.

So once you’ve got the style, then you have to figure out how to store it, you can’t just copy a bunch of strings like you did in the Demo. The concept of template is introduced here, and each style is saved into a single HTML, which is rendered by passing parameters. The Jinja2 template library is used here.

PIP command installs a wave:

pip install Jinja2
Copy the code

Then replace the text part with a variable text:

Then get the template and render it using Jinja2:

The following output is displayed:

Jinja2: Yes, very strong.

  • Liverpoolfc.tv: jinja.palletsprojects.com/en/2.11.x/
  • Or an article I wrote before: “Steal a lazy, public number pull butt morning paper 80% automation — 3.Flask quick method”

This is the process of creating a template and rendering it with a template. Now I’ll show you how to get each style.

② Two whip → title, bold, paragraph

H3 and H2 are similar in that they replace the style text directly with {{text}}

H4 is a bit more troublesome because it has one more order parameter:

Then rewrite the heading function to render it at different levels:

The following mardown string is then passed:

Run and paste the rendered HTML to wechat editor for verification:

Yes, the effect is not stamp, then bold and paragraph style:

After running, paste the generated style to the public number editor kangkang effect:

The reason is that wechat will automatically filter out the \ N line break in the text node. A simple workaround is to replace \n with

when rendering paragraph text

Modify render logic:

Verify the effect:

③ Three whip → form and list

If you want to use the form directly, you can use the form in wechat editor as follows:

The corresponding code is as follows:

Mistune needs to enable plugin_table tool to parse the table, which provides the following functions for overwriting:

Try writing a simple demo:

You can see that in table_head we get the text structure of the table header. Several other functions also get the table structure of different parts.

However, I ended up overriding the table() function because the table rendering is consistent, and it would be a hassle to stuff each function into a

if it were rendered separately.

In addition, the public numbers are mostly read on mobile phones, and the screen width is only a little bit. Generally, a two-column table is recommended. Here I define another Cell class:

Write the template first. The expectation is to pass in the table header list and the table content list and iterate through the render:

Extract the table header and the contents of the table, insert the table into the list, print the text:

LXML extract a wave directly:

Drop a test Markdown in:

Copy the generated style to the editor and verify the effect:

Ok, comfortable, then unordered list, also using the editor’s own style:

Scratch out the template:

Rewrite function render template:

Verification of parameter transfer:

Paste the rendered HTML to the editor and press Enter in the margins to indent the unordered list correctly!

④ Four whip → picture, link

Here is a pit to note, the author stuck here for a long time, hand slide press TAB indent:

Rendered code:

This is treated as a block of code, instead of being indented, or one or two Spaces indented. Also, pull out the style template:

Rewrite function render template:

Mistune will treat each line as a paragraph and then put a new style on top of it, so we need to modify the paragraph rendering function:

Verification of parameter transfer:

The effect is as follows:

⑤ Five whip → code highlighting, reference, in-line code

Code block rendering is also known as code highlighting. Most conversion tools on the web use highlightjs.js with a wide range of styles: highlightjs.org/

The pyacknowledgments code highlight library is used instead. The styles and previews can be picked up at pygments.org/demo/

The PIP command installs a wave of libraries:

pip install Pygaments
Copy the code

It’s easy to use:

Brief description of parameters:

  • Noclasses =True: set not to generate CSS files, i.e. use HTML inline styles;
  • Style =’perldoc’ : set the theme;
  • Wrapcode =True: wrap rendered code with ;

Copy it to the editor to see what it looks like:

Here can be a lot of pits, list:

  • Add overflow-x: auto; add overflow-x: auto;
  • < span style = “font-size: 12px;
  • (3) As shown in the figure below, some strings in the code are not wrapped in span, with different sizes and need to be wrapped in a SPAN.

Here, LXML is used to add and delete node elements and modify their attributes. The specific code is as follows:

Verification of parameter transfer:

The font size and scroll bar are out, which seems to be fine, but if you click on your phone to preview:

Some codes are crowded on one line. The bottom line is the newline character \n, which is eaten by wechat.

Add → white-space:nowrap to specify that the text is not newline until <br> is encountered.

So we need to insert the <br> tag in the right place, just before LXML parsing:

Look at the effect of the phone:

Newline is newline, but the front indentation is missing, look at the other tools to do:

Indent the corresponding amount of  

Therefore, we also need to count the space before each line and fill in the corresponding number of  

Look at the effect of the phone:

Good guy, ok, also kind of the code block of the pit are trample out!

Then add the referenced style as well:

Verification of parameter transfer:

Finally, fill in the style of the inline code

Verification of parameter transfer:

Common node analysis rendering will explain here, and then the full text of rendering fine tuning, line feed, all kinds of parsing conflict processing ah, limited to space, not a explain, can refer to the latest code in the warehouse.

0x5 Traditional Kung Fu ends with a point

In addition, the general public likes to add a specific header and tail to each article. This is simple, directly steal the two styles and save them into AN HTML template. After the body rendering is finished, the stitching can be done, and write a simple example:

Click preview to see the effect on your phone:

The effect is still very good, stepping on N pits + writing, a total of three days, finally made the prototype of the tool; Although it is not complete, not very humanized, there is only one theme at present, there are all kinds of unknown bugs, chicken movement, long-lost sense of achievement; Welcome you to try, put forward suggestions, raise issues, throw the theme public number, slowly improve this small productivity tool, thank you ~

Warehouse address: github.com/coder-pig/h…