apollo-language-server 0.7.0

A GraphQL language server with first-class support for Apollo Federation
Documentation
use apollo_parser::TextRange;
use ropey::Rope;

pub(crate) fn lsp_range_from_cst_textrange(
    range: TextRange,
    source_text: &Rope,
    offset: Option<u32>,
) -> lsp::Range {
    let start_offset = u32::from(range.start()) + offset.unwrap_or(0);
    let length = u32::from(range.end()) + offset.unwrap_or(0) - start_offset;

    // ask ropey for the start line, given the start offset
    let start_line = source_text.byte_to_line(start_offset as usize);
    // ask ropey for the character offset of the beginning of the start line
    let character_at_line = source_text.line_to_byte(start_line);
    // calculate the start character by subtracting the character offset of
    // the beginning of the line from the start offset
    let start_character = start_offset - character_at_line as u32;
    // only whitespace tokens can span multiple lines (and we're not really
    // interested in those), so the end line is the same as the start line
    let end_line = start_line;
    // calculate the end character by adding the length to the start character
    let end_character = start_character + length;

    lsp::Range {
        start: lsp::Position {
            line: start_line as u32,
            character: start_character,
        },
        end: lsp::Position {
            line: end_line as u32,
            character: end_character,
        },
    }
}