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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use std::ops::RangeBounds;

use types::{self as nvim, conversion::FromObject, Array, Integer};

use crate::choose;
use crate::ffi::extmark::*;
use crate::opts::*;
use crate::types::*;
use crate::utils;
use crate::Buffer;
use crate::SuperIterator;
use crate::{Error, Result};

/// Binding to [`nvim_create_namespace()`][1].
///
/// Creates a new namespace or gets the id of an existing one. If `name`
/// matches an existing namespace the associated id is returned.
///
/// [1]: https://neovim.io/doc/user/api.html#nvim_create_namespace()
pub fn create_namespace(name: &str) -> u32 {
    let name = nvim::String::from(name);
    unsafe { nvim_create_namespace(name.non_owning()) }
        .try_into()
        .expect("always positive")
}

/// Binding to [`nvim_get_namespaces()`][1].
///
/// Returns an iterator over all the existing, non-anonymous namespace names
/// and ids tuples `(name, id)`.
///
/// [1]: https://neovim.io/doc/user/api.html#nvim_get_namespaces()
pub fn get_namespaces() -> impl SuperIterator<(String, u32)> {
    unsafe {
        nvim_get_namespaces(
            #[cfg(feature = "neovim-0-10")] // On 0.10 and nightly.
            types::arena(),
        )
    }
    .into_iter()
    .map(|(k, v)| {
        let k = k.to_string_lossy().into();
        let v = u32::from_object(v).expect("namespace id is positive");
        (k, v)
    })
}

/// Binding to [`nvim_set_decoration_provider()`][1].
///
/// Sets or changes a decoration provider for a namespace.
///
/// [1]: https://neovim.io/doc/user/api.html#nvim_set_decoration_provider()
pub fn set_decoration_provider(
    ns_id: u32,
    opts: &DecorationProviderOpts,
) -> Result<()> {
    let mut err = nvim::Error::new();
    unsafe { nvim_set_decoration_provider(ns_id as Integer, opts, &mut err) };
    choose!(err, ())
}

impl Buffer {
    /// Binding to [`nvim_buf_add_highlight()`][1].
    ///
    /// Adds a highlight to the buffer. Both `line` and `byte_range` are
    /// 0-indexed.
    ///
    /// [1]: https://neovim.io/doc/user/api.html#nvim_buf_add_highlight()
    pub fn add_highlight<R>(
        &mut self,
        ns_id: u32,
        hl_group: &str,
        line: usize,
        byte_range: R,
    ) -> Result<i64>
    where
        R: RangeBounds<usize>,
    {
        let hl_group = nvim::String::from(hl_group);
        let mut err = nvim::Error::new();
        let (start, end) = utils::range_to_limits(byte_range);
        let ns_id = unsafe {
            nvim_buf_add_highlight(
                self.0,
                ns_id.into(),
                hl_group.non_owning(),
                line as Integer,
                start,
                end,
                &mut err,
            )
        };
        choose!(err, Ok(ns_id))
    }

    /// Binding to [`nvim_buf_clear_namespace()`][1].
    ///
    /// Clears namespaced objects like highlights, extmarks, or virtual text
    /// from a region.
    ///
    /// The line range is 0-indexed.
    ///
    /// [1]: https://neovim.io/doc/user/api.html#nvim_buf_clear_namespace()
    pub fn clear_namespace<R>(
        &mut self,
        ns_id: u32,
        line_range: R,
    ) -> Result<()>
    where
        R: RangeBounds<usize>,
    {
        let mut err = nvim::Error::new();
        let (start, end) = utils::range_to_limits(line_range);
        unsafe {
            nvim_buf_clear_namespace(
                self.0,
                ns_id as Integer,
                start,
                end,
                &mut err,
            )
        };
        choose!(err, ())
    }

    /// Binding to [`nvim_buf_del_extmark()`][1].
    ///
    /// Removes an extmark from the buffer.
    ///
    /// [1]: https://neovim.io/doc/user/api.html#nvim_buf_del_extmark()
    pub fn del_extmark(&mut self, ns_id: u32, extmark_id: u32) -> Result<()> {
        let mut err = nvim::Error::new();
        let was_found = unsafe {
            nvim_buf_del_extmark(
                self.0,
                ns_id as Integer,
                extmark_id as Integer,
                &mut err,
            )
        };
        choose!(
            err,
            match was_found {
                true => Ok(()),
                _ => Err(Error::custom(format!(
                    "No extmark with id {extmark_id} was found"
                ))),
            }
        )
    }

    /// Binding to [`nvim_buf_get_extmark_by_id()`][1].
    ///
    /// The first two elements of the returned tuple represent the 0-indexed
    /// `row, col` position of the extmark. The last element is only present if
    /// the [`details`](crate::opts::GetExtmarkByIdOptsBuilder::details) option
    /// field was set to `true`.
    ///
    /// [1]: https://neovim.io/doc/user/api.html#nvim_buf_get_extmark_by_id()
    pub fn get_extmark_by_id(
        &self,
        ns_id: u32,
        extmark_id: u32,
        opts: &GetExtmarkByIdOpts,
    ) -> Result<(usize, usize, Option<ExtmarkInfos>)> {
        #[cfg(not(feature = "neovim-0-10"))] // 0nly on 0.9.
        let opts = types::Dictionary::from(opts);
        let mut err = nvim::Error::new();
        let tuple = unsafe {
            nvim_buf_get_extmark_by_id(
                self.0,
                ns_id as Integer,
                extmark_id as Integer,
                #[cfg(not(feature = "neovim-0-10"))] // 0nly on 0.9.
                opts.non_owning(),
                #[cfg(feature = "neovim-0-10")] // On 0.10 and nightly.
                opts,
                #[cfg(feature = "neovim-0-10")] // On 0.10 and nightly.
                types::arena(),
                &mut err,
            )
        };
        choose!(err, {
            if tuple.is_empty() {
                return Err(Error::custom(format!(
                    "No extmark with id {extmark_id} was found"
                )));
            }

            let mut iter = tuple.into_iter();
            let row =
                usize::from_object(iter.next().expect("row is present"))?;
            let col =
                usize::from_object(iter.next().expect("col is present"))?;
            let infos =
                iter.next().map(ExtmarkInfos::from_object).transpose()?;
            Ok((row, col, infos))
        })
    }

    /// Bindings to [`nvim_buf_get_extmarks`][1].
    ///
    /// Gets all the extmarks in a buffer region specified by start and end
    /// positions. Returns an iterator over `(extmark_id, row, col, infos)`
    /// tuples in "traversal order". Like for [`Buffer::get_extmark_by_id`],
    /// the `infos` are present only if the
    /// [`details`](crate::opts::GetExtmarksOptsBuilder::details) option field
    /// was set to `true`.
    ///
    /// [1]: https://neovim.io/doc/user/api.html#nvim_buf_get_extmarks()
    pub fn get_extmarks(
        &self,
        ns_id: u32,
        start: ExtmarkPosition,
        end: ExtmarkPosition,
        opts: &GetExtmarksOpts,
    ) -> Result<impl SuperIterator<(u32, usize, usize, Option<ExtmarkInfos>)>>
    {
        #[cfg(not(feature = "neovim-0-10"))] // 0nly on 0.9.
        let opts = types::Dictionary::from(opts);
        let mut err = nvim::Error::new();
        let extmarks = unsafe {
            nvim_buf_get_extmarks(
                self.0,
                ns_id as Integer,
                start.into(),
                end.into(),
                #[cfg(not(feature = "neovim-0-10"))] // 0nly on 0.9.
                opts.non_owning(),
                #[cfg(feature = "neovim-0-10")] // On 0.10 and nightly.
                opts,
                #[cfg(feature = "neovim-0-10")] // On 0.10 and nightly.
                types::arena(),
                &mut err,
            )
        };
        choose!(
            err,
            Ok({
                extmarks.into_iter().map(|tuple| {
                    let mut iter =
                        Array::from_object(tuple).unwrap().into_iter();
                    let id =
                        u32::from_object(iter.next().expect("id is present"))
                            .unwrap();
                    let row = usize::from_object(
                        iter.next().expect("row is present"),
                    )
                    .unwrap();
                    let col = usize::from_object(
                        iter.next().expect("col is present"),
                    )
                    .unwrap();
                    let infos = iter
                        .next()
                        .map(ExtmarkInfos::from_object)
                        .transpose()
                        .unwrap();
                    (id, row, col, infos)
                })
            })
        )
    }

    /// Binding to [`nvim_buf_set_extmark()`][1].
    ///
    /// Creates or updates an extmark. Both `line` and `col` are 0-indexed.
    /// Returns the id of the created/updated extmark.
    ///
    /// [1]: https://neovim.io/doc/user/api.html#nvim_buf_set_extmark()
    pub fn set_extmark(
        &mut self,
        ns_id: u32,
        line: usize,
        col: usize,
        opts: &SetExtmarkOpts,
    ) -> Result<u32> {
        let mut err = nvim::Error::new();
        let id = unsafe {
            nvim_buf_set_extmark(
                self.0,
                ns_id as Integer,
                line as Integer,
                col as Integer,
                opts,
                &mut err,
            )
        };
        choose!(err, Ok(id.try_into().expect("always positive")))
    }
}

impl crate::Window {
    /// Binding to [`nvim__win_add_ns()`][1].
    ///
    /// Adds the namespace scope to the window, returning `true` if the
    /// namespace was added, and `false` otherwise.
    ///
    /// [1]: https://neovim.io/doc/user/api.html#nvim__win_add_ns()
    #[cfg(feature = "neovim-0-10")] // On 0.10 and nightly.
    #[cfg_attr(
        docsrs,
        doc(cfg(any(feature = "neovim-0-10", feature = "neovim-nightly")))
    )]
    pub fn add_ns(&mut self, ns_id: u32) -> Result<bool> {
        let mut err = nvim::Error::new();
        let was_added =
            unsafe { nvim__win_add_ns(self.0, ns_id as Integer, &mut err) };
        choose!(err, Ok(was_added))
    }

    /// Binding to [`nvim__win_get_ns()`][1].
    ///
    /// Gets all the namespaces scopes associated with a window.
    ///
    /// [1]: https://neovim.io/doc/user/api.html#nvim__win_get_ns()
    #[cfg(feature = "neovim-0-10")] // On 0.10 and nightly.
    #[cfg_attr(
        docsrs,
        doc(cfg(any(feature = "neovim-0-10", feature = "neovim-nightly")))
    )]
    pub fn get_ns(&self) -> Result<impl SuperIterator<u32>> {
        let mut err = nvim::Error::new();
        let namespaces =
            unsafe { nvim__win_get_ns(self.0, types::arena(), &mut err) };
        choose!(
            err,
            Ok(namespaces
                .into_iter()
                .map(|namespace| u32::from_object(namespace).unwrap()))
        )
    }

    /// Binding to [`nvim__win_del_ns()`][1].
    ///
    /// Removes the namespace scope from the window, returning `true` if the
    /// namespace was removed, and `false` otherwise.
    ///
    /// [1]: https://neovim.io/doc/user/api.html#nvim__win_del_ns()
    #[cfg(feature = "neovim-0-10")] // On 0.10 and nightly.
    #[cfg_attr(
        docsrs,
        doc(cfg(any(feature = "neovim-0-10", feature = "neovim-nightly")))
    )]
    pub fn del_ns(&mut self, ns_id: u32) -> Result<bool> {
        let mut err = nvim::Error::new();
        let was_removed =
            unsafe { nvim__win_del_ns(self.0, ns_id as Integer, &mut err) };
        choose!(err, Ok(was_removed))
    }
}