ladybird/Userland/Utilities/md.cpp

63 lines
1.9 KiB
C++
Raw Normal View History

/*
* Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/DeprecatedString.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/File.h>
2022-01-23 17:10:52 +00:00
#include <LibCore/System.h>
#include <LibMain/Main.h>
#include <LibMarkdown/Document.h>
#include <sys/ioctl.h>
#include <unistd.h>
2022-01-23 17:10:52 +00:00
ErrorOr<int> serenity_main(Main::Arguments arguments)
{
2022-01-23 17:10:52 +00:00
TRY(Core::System::pledge("stdio rpath tty"));
2020-01-13 00:12:18 +00:00
2022-09-14 15:26:53 +00:00
StringView filename;
bool html = false;
int view_width = 0;
Core::ArgsParser args_parser;
args_parser.set_general_help("Render Markdown to some other format.");
args_parser.add_option(html, "Render to HTML rather than for the terminal", "html", 'H');
args_parser.add_option(view_width, "Viewport width for the terminal (defaults to current terminal width)", "view-width", 0, "width");
2021-04-29 19:46:15 +00:00
args_parser.add_positional_argument(filename, "Path to Markdown file", "path", Core::ArgsParser::Required::No);
2022-01-23 17:10:52 +00:00
args_parser.parse(arguments);
if (!html && view_width == 0) {
if (isatty(STDOUT_FILENO)) {
struct winsize ws;
if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0)
view_width = 80;
else
view_width = ws.ws_col;
} else {
view_width = 80;
}
}
2022-09-14 15:26:53 +00:00
auto file = TRY(Core::File::open_file_or_standard_stream(filename, Core::File::OpenMode::Read));
2022-01-23 17:10:52 +00:00
TRY(Core::System::pledge("stdio"));
2020-01-13 00:12:18 +00:00
auto buffer = TRY(file->read_until_eof());
dbgln("Read size {}", buffer.size());
auto input = DeprecatedString::copy(buffer);
auto document = Markdown::Document::parse(input);
if (!document) {
warnln("Error parsing Markdown document");
return 1;
}
DeprecatedString res = html ? document->render_to_html() : document->render_for_terminal(view_width);
out("{}", res);
2022-01-23 17:10:52 +00:00
return 0;
}