周报@2023-03-09 @ Fri, Mar 10, 2023 5:07 PM
周报@2023-03-09 @ Tue, Mar 14, 2023 4:48 PM
Expand 108 lines ...
109
109
110
export default Micro;
110
export default Micro;
111
```
111
```
112
+
113
+
## remark-stringify escape/encode [
114
+
115
+
How to disable remark-stringify escape/encode [?  
116
+
We don't want to escape '[' as it's wildly used in checkbox and backlink. It is task-list-item mark in react-gfm.
117
+
118
+
> https://github.com/syntax-tree/mdast-util-to-markdown/issues/31
119
+
120
+
```ts
121
+
import { unified } from 'unified';
122
+
import rehypeParse from 'rehype-parse';
123
+
import rehypeRemark from 'rehype-remark';
124
+
import remarkStringify from 'remark-stringify';
125
+
import remarkGfm from 'remark-gfm';
126
+
import stringWidth from 'string-width';
127
+
import rehypeRemoveComments from 'rehype-remove-comments';
128
+
import type { Unsafe } from 'mdast-util-to-markdown';
129
+
import { defaultHandlers } from 'mdast-util-to-markdown';
130
+
131
+
const { text } = defaultHandlers;
132
+
133
+
/**
134
+
 * @description By default, mdast-util-to-markdown will escape some characters in some
135
+
 * conditions.
136
+
 * @description See `unsafe.js` for all rules:
137
+
 * https://github.com/syntax-tree/mdast-util-to-markdown/blob/main/lib/unsafe.js#L24
138
+
 * @description In our case, we don't want to apply some of them.
139
+
 */
140
+
function unsafeFilter(rule: Unsafe): boolean {
141
+
  // We don't want to escape '[' as it's wildly used in checkbox and backlink.
142
+
  return rule.character !== '[';
143
+
}
144
+
145
+
export async function html2md(html: string): Promise<string> {
146
+
  const file = await unified()
147
+
    .use(rehypeParse, {
148
+
      fragment: true,
149
+
    })
150
+
    .use(rehypeRemoveComments)
151
+
    .use(rehypeRemark, {
152
+
      unchecked: '[ ] ',
153
+
      checked: '[x] ',
154
+
    })
155
+
    .use(remarkGfm, {
156
+
      stringLength: stringWidth,
157
+
    })
158
+
    .use(remarkStringify, {
159
+
      bullet: '+',
160
+
      bulletOrdered: '.',
161
+
      listItemIndent: 'one',
162
+
      resourceLink: true,
163
+
      fences: true,
164
+
      emphasis: '_',
165
+
      rule: '-',
166
+
      tightDefinitions: true,
167
+
      bulletOther: '-',
168
+
      bulletOrderedOther: ')',
169
+
      handlers: {
170
+
        text: (node, parent, context, safeOptions) => {
171
+
          return text(
172
+
            node,
173
+
            parent,
174
+
            { ...context, unsafe: context.unsafe.filter(unsafeFilter) },
175
+
            safeOptions,
176
+
          );
177
+
        },
178
+
      },
179
+
    })
180
+
    .process(html);
181
+
182
+
  return file.toString().trim();
183
+
}
184
+
```