|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# md2txtconv.py - Convert markdown to text file |
| 4 | +# |
| 5 | +# Copyright (c) 2025 Yuichi Nakamura (@yunkya2) |
| 6 | +# |
| 7 | +# The MIT License (MIT) |
| 8 | +# |
| 9 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 10 | +# of this software and associated documentation files (the "Software"), to deal |
| 11 | +# in the Software without restriction, including without limitation the rights |
| 12 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 13 | +# copies of the Software, and to permit persons to whom the Software is |
| 14 | +# furnished to do so, subject to the following conditions: |
| 15 | +# |
| 16 | +# The above copyright notice and this permission notice shall be included in |
| 17 | +# all copies or substantial portions of the Software. |
| 18 | +# |
| 19 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 20 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 21 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 22 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 23 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 24 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 25 | +# THE SOFTWARE. |
| 26 | + |
| 27 | +import sys |
| 28 | +import re |
| 29 | +import codecs |
| 30 | +import os |
| 31 | + |
| 32 | +# 定数の定義 |
| 33 | +WIDTH = 76 |
| 34 | +PRO_HEAD_CHARS = "。、〕〉》」』】〙〗" |
| 35 | + |
| 36 | +def get_display_width(text): |
| 37 | + """ |
| 38 | + テキストの表示幅を計算する関数 |
| 39 | + ASCII文字は1、その他のUnicode文字は2として計算 |
| 40 | + """ |
| 41 | + width = 0 |
| 42 | + for char in text: |
| 43 | + if ord(char) < 128: |
| 44 | + width += 1 |
| 45 | + else: |
| 46 | + width += 2 |
| 47 | + return width |
| 48 | + |
| 49 | +def wrap_text(text, width): |
| 50 | + """ |
| 51 | + テキストを指定された幅で折り返す関数 |
| 52 | + 英数字が連続している単語の途中で改行しないようにする |
| 53 | + """ |
| 54 | + if not text.strip(): |
| 55 | + return text |
| 56 | + text = text.rstrip("\n") |
| 57 | + leading_spaces = len(text) - len(text.lstrip(' ')) |
| 58 | + next_leading_spaces = leading_spaces |
| 59 | + |
| 60 | + # リスト項目のインデントを調整 |
| 61 | + if m := re.match(r'( *)\* ', text): |
| 62 | + text = " " + text |
| 63 | + leading_spaces = len(m.group(1)) + 1 |
| 64 | + next_leading_spaces = len(m.group(0)) + 1 |
| 65 | + if m := re.match(r'( *)\d+\. ', text): |
| 66 | + text = " " + text |
| 67 | + leading_spaces = len(m.group(1)) + 1 |
| 68 | + next_leading_spaces = len(m.group(0)) + 1 |
| 69 | + |
| 70 | + wrapped_lines = [] |
| 71 | + current_line = " " * leading_spaces |
| 72 | + current_width = leading_spaces |
| 73 | + |
| 74 | + word_buffer = "" |
| 75 | + word_width = 0 |
| 76 | + |
| 77 | + for char in text.lstrip(' '): |
| 78 | + char_width = get_display_width(char) |
| 79 | + if char.isspace(): |
| 80 | + # スペースが見つかった場合、現在の単語を行に追加 |
| 81 | + if current_width + word_width > width: |
| 82 | + wrapped_lines.append(current_line) |
| 83 | + leading_spaces = next_leading_spaces |
| 84 | + current_line = " " * leading_spaces + word_buffer |
| 85 | + current_width = leading_spaces + word_width |
| 86 | + else: |
| 87 | + current_line += word_buffer |
| 88 | + current_width += word_width |
| 89 | + current_line += char |
| 90 | + current_width += char_width |
| 91 | + word_buffer = "" |
| 92 | + word_width = 0 |
| 93 | + else: |
| 94 | + if ord(char) < 128: |
| 95 | + # 英数字の場合、単語の途中で改行しないようにする |
| 96 | + if current_width + word_width + char_width > width: |
| 97 | + wrapped_lines.append(current_line) |
| 98 | + leading_spaces = next_leading_spaces |
| 99 | + current_line = " " * leading_spaces + word_buffer + char |
| 100 | + current_width = leading_spaces + word_width + char_width |
| 101 | + word_buffer = "" |
| 102 | + word_width = 0 |
| 103 | + else: |
| 104 | + word_buffer += char |
| 105 | + word_width += char_width |
| 106 | + else: |
| 107 | + # その他のUnicode文字は途中で改行してもよい |
| 108 | + if word_width > 0: |
| 109 | + # まだ出力していない単語がある場合、行に追加 |
| 110 | + current_line += word_buffer |
| 111 | + current_width += word_width |
| 112 | + word_buffer = "" |
| 113 | + word_width = 0 |
| 114 | + |
| 115 | + if current_width + char_width > width: |
| 116 | + if char in PRO_HEAD_CHARS: |
| 117 | + # 禁則処理 |
| 118 | + current_line += char |
| 119 | + char = "" |
| 120 | + char_width = 0 |
| 121 | + wrapped_lines.append(current_line) |
| 122 | + leading_spaces = next_leading_spaces |
| 123 | + current_line = " " * leading_spaces + char |
| 124 | + current_width = leading_spaces + char_width |
| 125 | + else: |
| 126 | + current_line += char |
| 127 | + current_width += char_width |
| 128 | + |
| 129 | + if word_buffer: |
| 130 | + # 最後の単語を行に追加 |
| 131 | + if current_width + word_width > width: |
| 132 | + wrapped_lines.append(current_line) |
| 133 | + current_line = " " * leading_spaces + word_buffer |
| 134 | + else: |
| 135 | + current_line += word_buffer |
| 136 | + |
| 137 | + if current_line.strip(): |
| 138 | + wrapped_lines.append(current_line) |
| 139 | + |
| 140 | + return "\n".join(wrapped_lines) + "\n" |
| 141 | + |
| 142 | +def process_file(filename, remove_original, replacements): |
| 143 | + """ |
| 144 | + ファイルを処理して変換する関数 |
| 145 | + """ |
| 146 | + with codecs.open(filename, 'r', 'utf-8') as f: |
| 147 | + lines = f.readlines() |
| 148 | + |
| 149 | + with codecs.open(filename.replace('.md', '.txt'), 'w', 'cp932') as f: |
| 150 | + nowrap = False |
| 151 | + for line in lines: |
| 152 | + w = get_display_width(line) |
| 153 | + |
| 154 | + if '```' in line: |
| 155 | + # コードブロックの開始・終了を検出 |
| 156 | + nowrap = not nowrap |
| 157 | + pos = line.find('```') |
| 158 | + if pos == 0: |
| 159 | + line = '-' * (WIDTH - 1) + '\n' |
| 160 | + else: |
| 161 | + line = line[:pos] + '-' * (WIDTH - pos - 1) + '\n' |
| 162 | + else: |
| 163 | + # マークダウンの記法をテキストに変換 |
| 164 | + line = re.sub(r'`', '', line) |
| 165 | + line = re.sub(r'\\$', '', line) |
| 166 | + line = re.sub(r'\\<', '<', line) |
| 167 | + line = re.sub(r'\\>', '>', line) |
| 168 | + line = re.sub(r'^# (.*)', r'■■■ \1 ■■■', line) |
| 169 | + line = re.sub(r'^## ', '■ ', line) |
| 170 | + line = re.sub(r'^### ', '● ', line) |
| 171 | + line = re.sub(r'^#### ', '○ ', line) |
| 172 | + line = re.sub(r'\*\*', '', line) |
| 173 | + line = re.sub(r'\[([^]]*)\]\([^)]*\)', r'\1', line) |
| 174 | + line = re.sub(r'(--*):', r'\1-', line) |
| 175 | + |
| 176 | + # 可能であればテキストの折り返しを行う |
| 177 | + if not re.search(r'.*\|.*\|', line) and not nowrap: |
| 178 | + line = wrap_text(line, WIDTH) |
| 179 | + |
| 180 | + # キーワード置換を行う |
| 181 | + for keyword, value in replacements.items(): |
| 182 | + line = line.replace(keyword, value) |
| 183 | + |
| 184 | + # 改行コードを変換してファイルに書き込む |
| 185 | + line = re.sub(r'\n', '\r\n', line) |
| 186 | + f.write(line) |
| 187 | + |
| 188 | + # オプションに応じて元のファイルを削除する |
| 189 | + if remove_original: |
| 190 | + os.remove(filename) |
| 191 | + |
| 192 | +def print_usage(): |
| 193 | + """ |
| 194 | + 使用法のヘルプメッセージを表示する関数 |
| 195 | + """ |
| 196 | + print("Usage: md2txtconv.py [options] <input files>") |
| 197 | + print("Options:") |
| 198 | + print(" -r Remove original .md files after conversion") |
| 199 | + print(" -h Show this help message") |
| 200 | + print(" keyword=value Replace occurrences of 'keyword' with 'value' in the text") |
| 201 | + |
| 202 | +if __name__ == "__main__": |
| 203 | + remove_original = False |
| 204 | + filenames = [] |
| 205 | + replacements = {} |
| 206 | + |
| 207 | + for arg in sys.argv[1:]: |
| 208 | + if arg == '-r': |
| 209 | + remove_original = True |
| 210 | + elif arg == '-h': |
| 211 | + print_usage() |
| 212 | + sys.exit(0) |
| 213 | + elif '=' in arg: |
| 214 | + keyword, value = arg.split('=', 1) |
| 215 | + replacements[keyword] = value |
| 216 | + else: |
| 217 | + filenames.append(arg) |
| 218 | + |
| 219 | + if not filenames: |
| 220 | + print_usage() |
| 221 | + sys.exit(1) |
| 222 | + |
| 223 | + for filename in filenames: |
| 224 | + process_file(filename, remove_original, replacements) |
0 commit comments