summaryrefslogtreecommitdiff
path: root/support/texlab/crates/texlab/src/main.rs
blob: ceca02b7f7c3f1bfb33b503a8bc60f8765602d15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
use std::{fs::OpenOptions, io, path::PathBuf};

use anyhow::Result;
use clap::{ArgAction, Parser, Subcommand};
use log::LevelFilter;
use lsp_server::Connection;
use lsp_types::Url;
use texlab::Server;

/// An implementation of the Language Server Protocol for LaTeX
#[derive(Debug, Parser)]
#[clap(version)]
struct Opts {
    /// Increase message verbosity (-vvvv for max verbosity)
    #[clap(short, long, action = ArgAction::Count)]
    verbosity: u8,

    /// No output printed to stderr
    #[clap(short, long)]
    quiet: bool,

    /// Write the logging output to FILE
    #[clap(long, name = "FILE", value_parser)]
    log_file: Option<PathBuf>,

    #[clap(subcommand)]
    command: Option<Command>,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Runs the language server in a editor context using STDIN and STDOUT.
    Run,

    /// Opens a document at a specific line.
    ///
    /// This command can be used to implement inverse search in an editor-agnostic way.
    InverseSearch(InverseSearchOpts),
}

/// Options for the inverse search subcommand.
#[derive(Debug, Parser)]
struct InverseSearchOpts {
    /// The path to the document to open.
    #[clap(short, long, name = "FILE", value_parser)]
    input: PathBuf,

    /// The zero-based line number of the document to jump to.
    #[clap(short, long)]
    line: u32,
}

fn main() -> Result<()> {
    let opts = Opts::parse();
    setup_logger(&opts);

    match opts.command.unwrap_or(Command::Run) {
        Command::Run => {
            let (connection, threads) = Connection::stdio();
            Server::exec(connection)?;
            threads.join()?;
        }
        Command::InverseSearch(opts) => {
            let Some(uri) = opts
                .input
                .canonicalize()
                .ok()
                .and_then(|path| Url::from_file_path(path).ok())
            else {
                eprintln!("Failed to convert input path to a URI.");
                std::process::exit(-1);
            };

            let params = lsp_types::TextDocumentPositionParams::new(
                lsp_types::TextDocumentIdentifier::new(uri),
                lsp_types::Position::new(opts.line, 0),
            );

            if let Err(why) = ipc::send_request(params) {
                eprintln!("Failed to send inverse search request to the main instance. Is the server running?");
                eprintln!("Details: {why:?}");
                std::process::exit(-1);
            }
        }
    }

    Ok(())
}

fn setup_logger(opts: &Opts) {
    let verbosity_level = if !opts.quiet {
        match opts.verbosity {
            0 => LevelFilter::Error,
            1 => LevelFilter::Warn,
            2 => LevelFilter::Info,
            3 => LevelFilter::Debug,
            _ => LevelFilter::Trace,
        }
    } else {
        LevelFilter::Off
    };

    let logger = fern::Dispatch::new()
        .format(|out, message, record| out.finish(format_args!("{} - {}", record.level(), message)))
        .level(verbosity_level)
        .chain(io::stderr());

    let logger = match &opts.log_file {
        Some(log_file) => logger.chain(
            OpenOptions::new()
                .write(true)
                .create(true)
                .open(log_file)
                .expect("failed to open log file"),
        ),
        None => logger,
    };

    logger.apply().expect("failed to initialize logger");
}