(: context information xpath functions etc
@author Andy Bunce
:)
module namespace ctx="lsp/context";
import module namespace lspt = 'lsp-typedefs' at 'lsp-typedefs.xqm';
declare namespace fos="http://www.w3.org/xpath-functions/spec/namespace";

declare variable $ctx:catalog:=doc("etc/function-catalog.xml");
declare variable $ctx:ns:=('fn', 'op','math','map','array');
declare variable $ctx:doclink:="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-";

declare function ctx:functions($ns as xs:string)
as element(fos:function)*{
$ctx:catalog//fos:function[@prefix=$ns]
};

declare function ctx:map($fn as element(fos:function))
{
  $fn!map{
   "label":string(@name),
   "kind": $lspt:CompletionItemKindMap("Function"),
   "detail":string($fn/fos:summary/*),
   "documentation":`{ ctx:summary(.) } <a href="{ $ctx:doclink }{ string(@name) }" target="_blank">Spec</a>`
                   !lspt:MarkupContent("markdown",.)
}
 
};

declare function ctx:summary($fn as element(fos:function))
{
$fn/fos:summary/*
=>ctx:strip-ns()
=>serialize({  'method': 'html' })
};

declare function ctx:strip-ns($n as node()) as node() {
  if($n instance of element()) then (
    element { node-name($n) } {
      $n/@*,
      $n/node()/ctx:strip-ns(.)
    }
  ) else if($n instance of document-node()) then (
    document { ctx:strip-ns($n/node()) }
  ) else (
    $n
  )
};