lmutil:getIndirectLinks() appears to work

(: =====================================================

   DITA Link Management Utilities

   Utilities that support general DITA link management
   actions.

   Author: W. Eliot Kimber

   Copyright (c) 2015 DITA For Small Teams
   Licensed under Apache License 2

   ===================================================== :)

module namespace lmutil="http://dita-for-small-teams.org/xquery/modules/linkmgmt-utils";

declare namespace dfst="http://dita-for-small-teams.org";

import module namespace df="http://dita-for-small-teams.org/xquery/modules/dita-utils";
import module namespace bxutil="http://dita-for-small-teams.org/xquery/modules/basex-utils";
import module namespace dfstcnst="http://dita-for-small-teams.org/xquery/modules/dfst-constants";
import module namespace relpath="http://dita-for-small-teams.org/xquery/modules/relpath-utils";

declare variable $lmutil:useMatchParamsLocalMaps :=
                               map{'linktype' :'topicref',
                                   'format' : 'ditamap',
                                   'scope' : 'local'
                                  };
declare variable $lmutil:useMatchParamsPeerMaps :=
                               map{'linktype' :'topicref',
                                   'format' : 'ditamap',
                                   'scope' : 'peer'
                                  };

(:~
 : Find all links that use direct URI references to their target resources.
 : Returns list of link item maps
 :
 : Each link item map has the following items:
 :
 : 'link' : The element that is the link
 : 'rootMap' : The root map document that defines the namespace the link
 :             is resolved in.
 : 'resolvedMap' : The fully-resolved map that defines key space the key
 :                 reference is resolved in.
 : 'keySpace' : The constructed key space for the root map.
 : 'processingRole' : For topicrefs, the @processing-role value. For
 :                    other links, 'normal'.
 : 'linkContext': The relevant container type for the link, one of:
 :                - 'title' : Link occurs within a title element
 :                - 'prolog' : Link occurs with topicmeta (maps) or prolog (topics)
 :                - 'shortdesc' : Link occurs within a short description
 :                - 'abstract' : Link occurs within an abstract (but not within a
 :                               short description within an abstract)
 :                - 'body' : Link occurs within a topic body
 :                - 'reltable' : Link is a topicref within a relationship table.
 :                - 'navtree' : Link is a topicref with @processing-role of 'normal' and
 :                              is not within a relationship table
 :                - 'resources' : Link is a topicref with a processing role of "resource-only".
 :  'isDirect' : - 'true' if link is a direct URI reference
 :               - 'false' if link uses a resolvable key reference
 :
 : For direct links the link element is sufficient
 : to allow resolution as use context has no affect on how the link is resolved.
 : For "." ("this topic") fragment IDs, the context is always the containing topic.
 :
 : @param dbName Name of the database that contains the documents to be processed.
 : @param logID ID of the log to put log messages in.
 :)
declare function lmutil:findAllDirectLinks($dbName) as map(*)* {
  let $db := db:open($dbName)
  (: First do direct URI references, which don't require any
     context knowledge:
   :)
  let $links := collection($dbName)//*[df:isTopicRef(.) and not(@keyref)] |
                collection($dbName)//*[contains(@class, ' topic/xref ') and (@href and not(@keyref))] |
                collection($dbName)//*[contains(@class, ' topic/data-about ') and (@href and not(@keyref))] |
                collection($dbName)//*[contains(@class, ' topic/longdescref ') and (@href and not(@keyref))] |
                collection($dbName)//*[@conref]
   (: Construct a link item map for each link element :)
   for $link in $links
       return lmutil:constructLinkItemMap($link)
};

(:~
 : Constructs a link item map for a direct link.
 :
 : @param link The link element
 : @return Link item map
 :)
declare function lmutil:constructLinkItemMap(
                        $link as element()) as map(*) {
  let $result := lmutil:constructLinkItemMap($link, ())
  return $result
};

(:~
 : Constructs a link item map
 :
 : @param link The link element
 : @param topicref For indirect links, the topicref that establishes
 :                 the key resolution context for the link. Not set for direct URI links.
 :                 Note that this topicref element must be from the resolved map, not the
 :                 original source map.
 :)
declare function lmutil:constructLinkItemMap(
                        $link as element(),
                        $topicref as element()?) as map(*) {
   let $linkItem :=
      map{'link': $link,
          'resolvedMap': if ($topicref) then root($topicref)/* else (),
          'topicref' : $topicref,
          'processingRole':
             if (df:isTopicRef($link))
                then if ($link/@processing-role)
                        then string($link/@processing-role)
                        else 'normal' (: Default for topicref :)
                else 'normal', (: non-topicref links :)
          'linkContext': lmutil:getLinkContext($link)
         }
    return $linkItem
};

(: Give a document, finds all references to that document that match the
   type of uses as configured in the $useParams.

   @param doc Document to find uses of.
   @param useParams Use filter parameters. Only uses that match the parameters
                    will be reported.
   @return Zero or more use record elements.

   The use parameters are:

   linktype: List of base type names (e.g., 'topicref, xref) or qualified
             class names (e.g., 'map-d/navref') of the types of links
             to report usage for. If unspecifed, all link types are reported.
             The keyword "#conref" indicates uses via @conref or @conkeyref

   format:   List of @format values by which the document is used, e.g. "dita", "ditamap",
             etc. If unspecified, uses are not filtered by @format value.

   scope:    List of @scope values to filter the uses by. If unspecified, uses are not
             filtered by @scope value.

   TBD: Need for direct/indirect filter, other filters.

   FIXME: Need to rationalize the coding pattern for use parameters and
          their use by the useRecordMatcher() function. The code is a little
          confused right now as a result of some quick refactoring.

 :)
declare function lmutil:getUses($elem as element(), $useParams) as element()* {

   let $linktypes := if ($useParams('linktype'))
                        then $useParams('linktype')
                        else ('#any')
   let $formats   := if ($useParams('format'))
                        then $useParams('format')
                        else ('#any')
   let $scopes   := if ($useParams('scope'))
                        then $useParams('scope')
                        else ('#any')

   (: Note that all references are ultimately to elements,
      so resource keys are always for elements, not
      documents. Given an element we can always get its
      containing document.

      In DITA, except for <dita> documents, references to
      documents with no fragment identifier are implicitly
      to the root elements of those documents (i.e., a map
      or topic element).

      The resource key here is used as the name of the
      directory that contains the where-used records for
      this element.
    :)
   let $resKey := lmutil:constructResourceKeyForElement($elem)

   (: Now find all use records for the resource key that match the filter
      specification.

      :)
    let $dbName := bxutil:getMetadataDbNameForDoc(root($elem))
    let $collection := $dbName || $dfstcnst:where-used-dir || '/' || $resKey
    let $records := collection($collection)
                       /dfst:useRecord[lmutil:useRecordMatcher(., $linktypes, $formats, $scopes)]
    return $records

};

(: Given an element with an @id value, construct the unique resource key for it.
   For a given element the resource ID is guaranteed to be unique within
   a snapshot (git commit).

   @param elem Element to get resource ID for.
   @returns Resource key string.

   The resource key is a combination of the absolute URI of the containing
   document and the element's tree position within the document, producing
   a unique key for any element in any document on a given snapshot (version
   in time). Resource keys are not reliably unique across snapshots as the position of
   the element within its containing document could change from version to
   version.

   The resource key is used to look up the element in where-used records, either
   as the element used or the element doing the use (links).

 :)
declare function lmutil:constructResourceKeyForElement($elem as element()) as xs:string {
  let $targetDocHash := hash:md5(document-uri(root($elem)))
  let $treepos := for $anc in ($elem/ancestor-or-self::*)
                      return string(count($anc | $anc/preceding-sibling::*))
  let $key := string-join($treepos, '.')
  return $targetDocHash || '^' || $key

};

(:~
 : Determines if a given where-used record matches the filter
 : specified parameters.
 :
 : FIXME: Use a map to pass the filter parameters rather than
 : individual arguments.
 :)
declare function lmutil:useRecordMatcher($record as element(),
                                         $linktypes as xs:string*,
                                         $formats as xs:string*,
                                         $scopes as xs:string*) as xs:boolean {
   let $result := ((if ($linktypes = '#any')
                       then true()
                       else string($record/@linkType) = $linktypes) and
                   (if ($formats = '#any')
                       then true()
                       else string($record/@format) = $formats) and
                   (if ($scopes = '#any')
                       then true()
                       else string($record/@scope) = $scopes))
  return $result
};

(:~
 : Given a link element, determines the linkContext value for it.
 :)
declare function lmutil:getLinkContext($link as element()) as xs:string {
  if (df:class($link, 'map/topicref'))
     then if ($link/ancestor::*[df:class(., 'map/reltable')])
             then 'reltable'
          else if ($link/@processing-role = ('resource-only'))
               then 'resources'
          else 'navtree'
     else if ($link/ancestor::*[df:class(., 'topic/title')])
          then 'title'
     else if ($link/ancestor::*[df:class(., 'topic/shortdesc')])
          then 'shortdesc'
     else if ($link/ancestor::*[df:class(., 'topic/abstract')])
          then 'abstract'
     else if ($link/ancestor::*[df:class(., 'topic/prolog') or df:class(., 'map/topicmeta')])
          then 'prolog'
     else if ($link/ancestor::*[df:class(., 'topic/body')])
          then 'body'
     else 'unknown-context'

};

(:~
 : Given a link item map, attempts to resolve the link to an element (in DITA a given link
 : can address at most one element).
 :
 : Returns a map with the following members:
 : 'target': A sequence of zero or more elements addressed
 :           by the link.
 : 'log':    A sequence of zero or more log entry elements
 :           generated by the resolution attempt.
 :)
declare function lmutil:resolveDirectLink($linkItem as map(*)) as map(*) {

   let $link as element()? := $linkItem('link')
   return if ($link)
      then
       let $resultMap := if (df:class($link, 'map/topicref') and ($link/@href))
                            then df:resolveTopicRef($link)
                            else df:resolveNonTopicRefDirectLink($link)

       let $targets := $resultMap('target')
       let $log := (<info>Link: {
                   concat('<',
                          name($link), ' ',
                          lmutil:reportAtts($link, ('href', 'keyref', 'keys', 'conref', 'scope')),
                          '>')} [class: "{string($link/@class)}"], doc: "{document-uri(root($link))}"</info>,
                  if ($targets)
                     then <info>  Link resolved</info>
                     else $resultMap('log')
                  )
       return map{'target' : $targets, 'log' : $log, 'link' : $linkItem}
     else
       map{'target' : (),
                 'log' : (),
                 'link' : $linkItem
                }
};

(: Given a link descriptor map and the database that contains it, attempts
   to resolve the link to an element (in DITA a given link
   can address at most one element).

   Returns a map with the following members:
   'target': A sequence of zero or more elements addressed
             by the link.
   'log':    A sequence of zero or more log entry elements
             generated by the resolution attempt.
   'link':   The input link item.
 :)
declare function lmutil:resolveIndirectLink($linkItem as map(*)) as map(*) {

   let $topicref := $linkItem?topicref
   let $link := $linkItem?link
   let $keyName := df:getKeyNameForKeyref($link)
   (: Given the key name, look it up in the topicref's map (which must be a
      resolved map to find the key definition. The resolved map has had
      all key names expanded with their scope qualifications, so we can
      look up scope-qualified keys directly. :)
   let $keydef := lmutil:findKeyDefinition($keyName, $topicref)
   let $targets :=
       if ($keydef)
          then lmutil:resolveTopicRefFromResolvedMap($keydef)
          else ()

   let $log := ()
   return map{'target' : $targets, 'log' : $log , 'link' : $linkItem}
};

(:~
 : Given a key name and a topicref in a resolved map, find the applicable
 : key-defining topicref, if any.
 :
 : @param keyName The key name to look up.
 : @param topicref The topicref that establishes the map context (and thus
 :                 the starting key scope for the lookup)
 : @return The key-defining topicref or empty sequence if no key definition
 :             is found.
 :)
declare function lmutil:findKeyDefinition(
                            $keyName as xs:string,
                            $topicref as element()) as element()? {
  (: Key scope-defining element is either the nearest ancestor topicref that
     specifies @keyscope or the root map element.
   :)
  let $scope := ($topicref//ancestor-or-self::*[@keyscope], root($topicref)/*)[1]
  (: Within the scope, the effective key definition is the first definition,
     in depth-first (document) order that specifies the key name.
   :)
  let $result := ()
  return $result
};

(:~
 : Given a database, finds all the indirect links. Returns a map
 : the the members:
 : 'links' : A sequence of maps, where each map represents one link.
 : 'log' : A sequence of log entry elements.
 :
 : Each link map has the following items:
 :
 : 'link' : The element that is the link
 : 'rootMap' : The root map document that defines the namespace the link
 :             is resolved in.
 : 'resolvedMap' : The fully-resolved map that defines key space the key
 :                 reference is resolved in.
 : 'keySpace' : The constructed key space for the root map.
 :
 :)
declare function lmutil:findAllIndirectLinks($dbName) as map(*)* {
   (:

1. Find all root maps (maps with no local-scope topicref references or
   maps with peer topicref references). This requires that the direct-reference
   use records are up to date. It also requires that the resolved map and key space
   documents have already been created.

2. For each root map, Walk the resolved map, creating link items for each key-based topicref.
   Resolve topicrefs to topics and process each topic to create link items for each key-based
   link in each topic.

   :)

   let $rootMaps as element()* := lmutil:getRootMaps($dbName)

   let $linksFromTopics := lmutil:getIndirectLinksFromTopics($rootMaps)

    let $linksFromMaps := () (: FIXME: Build this list as well :)
    let $links := ($linksFromTopics, $linksFromMaps)

   return $links
};

(:~
 : Get all the indirect links in topics referenced from the root maps
 :
 : @para rootMaps list of root content maps.
 :
 : @return Sequence, possibly empty, of link item maps.
 :)
declare function lmutil:getIndirectLinksFromTopics($rootMaps as element()*) as map(*)* {
  let $result :=
     for $map in $rootMaps
         let $resolvedMap as element() := lmutil:getResolvedMapForMap($map)
         let $bos as map(*)* := lmutil:getMapBoundedObjectSet($resolvedMap, ('dita'))
         return for $member in $bos
            return lmutil:getIndirectLinks($bos)
  return $result
};

(:~
 : Takes a sequence of map BOS members and, for each member,
 : finds the key-based links in the member and returns a of link
 : structures reflecting those links.
 :
 : @param bos Sequence of maps, one for each use of a topic from a
 : DITA map. Each map has two members, "topicref", and "resource"
 : @return A sequence, possibly empty, of link maps.
 :)
declare function lmutil:getIndirectLinks($bos as map(*)*) as map(*)* {
   let $result as map(*)* :=
       for $member in $bos
           return lmutil:getIndirectLinksForBOSMember($member)
   return $result
};

(:~
 : Given a BOS member map for a topic, finds all key-based links in the
 : topic and returns a sequence of link items for the links.
 :
 : @param member BOS member map containing a topic BOS member.
 : @return A sequence, possibly empty, of link items.
 :)
declare function lmutil:getIndirectLinksForBOSMember($member as map(*)) as map(*)* {
   let $topicref := $member('topicref')
   let $topic := $member('resource')
   let $linkElems := $topic//*[@keyref]
   let $linkItems :=
       for $elem in $linkElems
           return lmutil:constructLinkItemMap($elem, $topicref)
   return $linkItems
};

(:~
 : Given a map resolves all the topicrefs to their local-scope resources
 : and returns the set of "BOS members", where each member is a map
 : with the topicref that pointed to the topic and the resolved topic.
 : The topicref is required in order to have the map context, which is required
 : in order to determine the key space within which any key references within the
 : topic are resolved. Note that a BOS member is a unique topicref/resource pair.
 : If the same resource is referenced multiple times in the map there will be one BOS member
 : for each reference.
 :
 : @param map Map to process. Does not resolve submap references, so if
 : you want the resources for a map tree supply the resolved map.
 :
 : @param formats A list of one or more @format values to return in the set.
 : The special value '#non-dita' matches any @format value that is not 'dita'
 : or 'dita-map'. Specify ('dita') to return only topic members of
 : the BOS. Non-DITA resources are represented by the topicrefs that point to
 : them. If not specified, all local-scope resources are returned.
 : @return Sequence of maps, one for each topicref/resource pair
 :)
declare function lmutil:getMapBoundedObjectSet(
                            $map as element(),
                            $formats as xs:string*) as map(*)* {
  let $topicrefs := $map//*[df:isTopicRef(.)]
                           [df:isLocalScope(.)]
                           [not($formats) or
                            df:getEffectiveFormat(.) = $formats]
  let $members :=
      for $topicref in $topicrefs
          let $resource := if (df:getEffectiveFormat($topicref) = ('dita'))
             then lmutil:resolveTopicRefFromResolvedMap($topicref)
             else $topicref
          return map { 'topicref' : $topicref,
                       'resource' : $resource }
  return $members

};

(:~
 : Resolves a topicref from a resolved map. Uses the additional metadata
 : in the resolved map to determine the target document that contains
 : the element.
 :)
declare function lmutil:resolveTopicRefFromResolvedMap($topicref as element())
                                                                    as element()? {
  let $baseURI := string(($topicref/ancestor::*[@origMapURI]/@origMapURI)[1])
  let $targetURI := string($topicref/@href)
  let $resolvedURI := relpath:resolveURI($targetURI, $baseURI)
  let $result := try {
    let $doc as document-node()? := doc($resolvedURI)
    let $elem := if ($doc) then $doc/* else()
    return $elem
  } catch * {
    (: Document not found :)
    ()
  }
  return $result
};

(:~
 : Find maps that either have no local-scope topicrefs to them or that have
 : any peer-scope topicrefs to them.
 :
 : @param dbName Name of the content database that holds the map to examine.
 : @return List, possibly empty, of root maps.
 :)
declare function lmutil:getRootMaps($dbName as xs:string) as element()* {
  let $candMaps := collection($dbName)/*[df:class(., 'map/map')]
  let $result :=
      for $candMap in $candMaps
          return if (lmutil:isRootMap($candMap))
                   then $candMap
                   else ()
  return $result
};

(:~
 : Returns true if the specified map element is a root map.
 :
 : Note that there are many ways that root mapness could be determined.
 : The logic used here is any map that has no direct map local-scope references
 : or any peer-scope references. This is based on the presumption that a root
 : map would not normally be useable as local-scope submap. DITA 1.3's new
 : meaning for scope="peer" on topicrefs to maps explicitly means "the referenced
 : map is a root map".
 :
 : Other options would be to have a master map that uses peer map references to
 : explicitly identify root maps and use only that to determine rootness, to
 : maintain some sort of metadata that indicates rootness, use a specific map
 : specialization or map specialization plus descendant element configuration
 : (e.g., bookmaps that have booktitle elements are root maps, all others are
 : not).
 :
 : @param map Map to check for rootness
 : @return true() if the map is a root map.
 :)
declare function lmutil:isRootMap($map as element()) as xs:boolean {
  let $result := ((lmutil:getRefCount($map, $lmutil:useMatchParamsLocalMaps) = 0) or
                  (lmutil:getRefCount($map, $lmutil:useMatchParamsPeerMaps) > 0))
  return $result
};

(:~
 : Gets the number of references to the specified element that match the specified
 : match criteria.
 :
 : @param elem Element to get reference count for.
 : @param matcher Use record matcher to use for selecting references
 : @return Number of matches
 :)
declare function lmutil:getRefCount($elem as element(),
                                    $matchParams as map(*)) as xs:integer {
  let $uses := lmutil:getUses($elem, $matchParams)
  let $result := count($uses)
  return $result
};

(: Construct a string report of the listed attributes :)
declare function lmutil:reportAtts($elem as element(), $attNames) as xs:string {
   let $result := for $att in $elem/@*
                      return if (name($att) = $attNames)
                                then concat(name($att), '="', string($att), '"')
                                else ()
   return string-join($result, ' ')
};

(:~
 : Report a link item map as XML
 :
 : @param linkItem
 : @return XML representation of the link
 :)
declare function lmutil:reportLinkItemMap($linkItem as map(*)) as element() {
(:
 : 'link' : The element that is the link
 : 'rootMap' : The root map document that defines the namespace the link
 :             is resolved in.
 : 'resolvedMap' : The fully-resolved map that defines key space the key
 :                 reference is resolved in.
 : 'keySpace' : The constructed key space for the root map.
 :)
  <linkItem>{
     bxutil:reportMapAsXML($linkItem)
}</linkItem>
};

(:~
 : Get the resolved map document for a map. The resolved map must have already
 : been constructed (XQuery doesn't let use do updating actions wherever we
 : want).
 :
 : @param map Content map to get the resolved map for.
 : @return the resolved map or an empty sequence if there is no resolved map
 : (for example, because the map is not a root map).
 :)
declare function lmutil:getResolvedMapForMap($map as element()) as element()? {
  let $resolvedMapURI as xs:string := lmutil:getResolvedMapURIForMap($map)
  let $metadataDbName as xs:string := bxutil:getMetadataDbNameForDoc(root($map))

  let $resolvedMap := collection($metadataDbName || $resolvedMapURI)
  return $resolvedMap/*
};

(:~
 : Construct the database URI to use for a resolved map.
 :
 : @param map DITA map element to get the URI for
 : @returns The URI of the resolved map as a string
 :)
declare function lmutil:getResolvedMapURIForMap(
                        $map as element()) as xs:string {
  let $mapDocHash := hash:md5(document-uri(root($map)))
  return $dfstcnst:resolved-map-dir ||
         "/" || $mapDocHash || ".ditamap"
};

(: End of Module :)

(: =====================================================

   DITA Link Management Utilities

   Utilities that support general DITA link management
   actions.

   Author: W. Eliot Kimber

   Copyright (c) 2015 DITA For Small Teams
   Licensed under Apache License 2

   ===================================================== :)

module namespace lmutil="http://dita-for-small-teams.org/xquery/modules/linkmgmt-utils";

declare namespace dfst="http://dita-for-small-teams.org";

import module namespace df="http://dita-for-small-teams.org/xquery/modules/dita-utils";
import module namespace bxutil="http://dita-for-small-teams.org/xquery/modules/basex-utils";
import module namespace dfstcnst="http://dita-for-small-teams.org/xquery/modules/dfst-constants";
import module namespace relpath="http://dita-for-small-teams.org/xquery/modules/relpath-utils";

declare variable $lmutil:useMatchParamsLocalMaps :=
                               map{'linktype' :'topicref',
                                   'format' : 'ditamap',
                                   'scope' : 'local'
                                  };
declare variable $lmutil:useMatchParamsPeerMaps :=
                               map{'linktype' :'topicref',
                                   'format' : 'ditamap',
                                   'scope' : 'peer'
                                  };

(:~
 : Find all links that use direct URI references to their target resources.
 : Returns list of link item maps
 :
 : Each link item map has the following items:
 :
 : 'link' : The element that is the link
 : 'rootMap' : The root map document that defines the namespace the link
 :             is resolved in.
 : 'resolvedMap' : The fully-resolved map that defines key space the key
 :                 reference is resolved in.
 : 'keySpace' : The constructed key space for the root map.
 : 'processingRole' : For topicrefs, the @processing-role value. For
 :                    other links, 'normal'.
 : 'linkContext': The relevant container type for the link, one of:
 :                - 'title' : Link occurs within a title element
 :                - 'prolog' : Link occurs with topicmeta (maps) or prolog (topics)
 :                - 'shortdesc' : Link occurs within a short description
 :                - 'abstract' : Link occurs within an abstract (but not within a
 :                               short description within an abstract)
 :                - 'body' : Link occurs within a topic body
 :                - 'reltable' : Link is a topicref within a relationship table.
 :                - 'navtree' : Link is a topicref with @processing-role of 'normal' and
 :                              is not within a relationship table
 :                - 'resources' : Link is a topicref with a processing role of "resource-only".
 :  'isDirect' : - 'true' if link is a direct URI reference
 :               - 'false' if link uses a resolvable key reference
 :
 : For direct links the link element is sufficient
 : to allow resolution as use context has no affect on how the link is resolved.
 : For "." ("this topic") fragment IDs, the context is always the containing topic.
 :
 : @param dbName Name of the database that contains the documents to be processed.
 : @param logID ID of the log to put log messages in.
 :)
declare function lmutil:findAllDirectLinks($dbName) as map(*)* {
  let $db := db:open($dbName)
  (: First do direct URI references, which don't require any
     context knowledge:
   :)
  let $links := collection($dbName)//*[df:isTopicRef(.) and not(@keyref)] |
                collection($dbName)//*[contains(@class, ' topic/xref ') and (@href and not(@keyref))] |
                collection($dbName)//*[contains(@class, ' topic/data-about ') and (@href and not(@keyref))] |
                collection($dbName)//*[contains(@class, ' topic/longdescref ') and (@href and not(@keyref))] |
                collection($dbName)//*[@conref]
   (: Construct a link item map for each link element :)
   for $link in $links
       return lmutil:constructLinkItemMap($link)
};

(:~
 : Constructs a link item map for a direct link.
 :
 : @param link The link element
 : @return Link item map
 :)
declare function lmutil:constructLinkItemMap(
                        $link as element()) as map(*) {
  let $result := lmutil:constructLinkItemMap($link, ())
  return $result
};

(:~
 : Constructs a link item map
 :
 : @param link The link element
 : @param topicref For indirect links, the topicref that establishes
 :                 the key resolution context for the link. Not set for direct URI links.
 :                 Note that this topicref element must be from the resolved map, not the
 :                 original source map.
 :)
declare function lmutil:constructLinkItemMap(
                        $link as element(),
                        $topicref as element()?) as map(*) {
   let $linkItem :=
      map{'link': $link,
          'resolvedMap': if ($topicref) then root($topicref)/* else (),
          'topicref' : $topicref,
          'processingRole':
             if (df:isTopicRef($link))
                then if ($link/@processing-role)
                        then string($link/@processing-role)
                        else 'normal' (: Default for topicref :)
                else 'normal', (: non-topicref links :)
          'linkContext': lmutil:getLinkContext($link)
         }
    return $linkItem
};

(: Give a document, finds all references to that document that match the
   type of uses as configured in the $useParams.

   @param doc Document to find uses of.
   @param useParams Use filter parameters. Only uses that match the parameters
                    will be reported.
   @return Zero or more use record elements.

   The use parameters are:

   linktype: List of base type names (e.g., 'topicref, xref) or qualified
             class names (e.g., 'map-d/navref') of the types of links
             to report usage for. If unspecifed, all link types are reported.
             The keyword "#conref" indicates uses via @conref or @conkeyref

   format:   List of @format values by which the document is used, e.g. "dita", "ditamap",
             etc. If unspecified, uses are not filtered by @format value.

   scope:    List of @scope values to filter the uses by. If unspecified, uses are not
             filtered by @scope value.

   TBD: Need for direct/indirect filter, other filters.

   FIXME: Need to rationalize the coding pattern for use parameters and
          their use by the useRecordMatcher() function. The code is a little
          confused right now as a result of some quick refactoring.

 :)
declare function lmutil:getUses($elem as element(), $useParams) as element()* {

   let $linktypes := if ($useParams('linktype'))
                        then $useParams('linktype')
                        else ('#any')
   let $formats   := if ($useParams('format'))
                        then $useParams('format')
                        else ('#any')
   let $scopes   := if ($useParams('scope'))
                        then $useParams('scope')
                        else ('#any')

   (: Note that all references are ultimately to elements,
      so resource keys are always for elements, not
      documents. Given an element we can always get its
      containing document.

      In DITA, except for <dita> documents, references to
      documents with no fragment identifier are implicitly
      to the root elements of those documents (i.e., a map
      or topic element).

      The resource key here is used as the name of the
      directory that contains the where-used records for
      this element.
    :)
   let $resKey := lmutil:constructResourceKeyForElement($elem)

   (: Now find all use records for the resource key that match the filter
      specification.

      :)
    let $dbName := bxutil:getMetadataDbNameForDoc(root($elem))
    let $collection := $dbName || $dfstcnst:where-used-dir || '/' || $resKey
    let $records := collection($collection)
                       /dfst:useRecord[lmutil:useRecordMatcher(., $linktypes, $formats, $scopes)]
    return $records

};

(: Given an element with an @id value, construct the unique resource key for it.
   For a given element the resource ID is guaranteed to be unique within
   a snapshot (git commit).

   @param elem Element to get resource ID for.
   @returns Resource key string.

   The resource key is a combination of the absolute URI of the containing
   document and the element's tree position within the document, producing
   a unique key for any element in any document on a given snapshot (version
   in time). Resource keys are not reliably unique across snapshots as the position of
   the element within its containing document could change from version to
   version.

   The resource key is used to look up the element in where-used records, either
   as the element used or the element doing the use (links).

 :)
declare function lmutil:constructResourceKeyForElement($elem as element()) as xs:string {
  let $targetDocHash := hash:md5(document-uri(root($elem)))
  let $treepos := for $anc in ($elem/ancestor-or-self::*)
                      return string(count($anc | $anc/preceding-sibling::*))
  let $key := string-join($treepos, '.')
  return $targetDocHash || '^' || $key

};

(:~
 : Determines if a given where-used record matches the filter
 : specified parameters.
 :
 : FIXME: Use a map to pass the filter parameters rather than
 : individual arguments.
 :)
declare function lmutil:useRecordMatcher($record as element(),
                                         $linktypes as xs:string*,
                                         $formats as xs:string*,
                                         $scopes as xs:string*) as xs:boolean {
   let $result := ((if ($linktypes = '#any')
                       then true()
                       else string($record/@linkType) = $linktypes) and
                   (if ($formats = '#any')
                       then true()
                       else string($record/@format) = $formats) and
                   (if ($scopes = '#any')
                       then true()
                       else string($record/@scope) = $scopes))
  return $result
};

(:~
 : Given a link element, determines the linkContext value for it.
 :)
declare function lmutil:getLinkContext($link as element()) as xs:string {
  if (df:class($link, 'map/topicref'))
     then if ($link/ancestor::*[df:class(., 'map/reltable')])
             then 'reltable'
          else if ($link/@processing-role = ('resource-only'))
               then 'resources'
          else 'navtree'
     else if ($link/ancestor::*[df:class(., 'topic/title')])
          then 'title'
     else if ($link/ancestor::*[df:class(., 'topic/shortdesc')])
          then 'shortdesc'
     else if ($link/ancestor::*[df:class(., 'topic/abstract')])
          then 'abstract'
     else if ($link/ancestor::*[df:class(., 'topic/prolog') or df:class(., 'map/topicmeta')])
          then 'prolog'
     else if ($link/ancestor::*[df:class(., 'topic/body')])
          then 'body'
     else 'unknown-context'

};

(:~
 : Given a link item map, attempts to resolve the link to an element (in DITA a given link
 : can address at most one element).
 :
 : Returns a map with the following members:
 : 'target': A sequence of zero or more elements addressed
 :           by the link.
 : 'log':    A sequence of zero or more log entry elements
 :           generated by the resolution attempt.
 :)
declare function lmutil:resolveDirectLink($linkItem as map(*)) as map(*) {

   let $link as element()? := $linkItem('link')
   return if ($link)
      then
       let $resultMap := if (df:class($link, 'map/topicref') and ($link/@href))
                            then df:resolveTopicRef($link)
                            else df:resolveNonTopicRefDirectLink($link)

       let $targets := $resultMap('target')
       let $log := (<info>Link: {
                   concat('<',
                          name($link), ' ',
                          lmutil:reportAtts($link, ('href', 'keyref', 'keys', 'conref', 'scope')),
                          '>')} [class: "{string($link/@class)}"], doc: "{document-uri(root($link))}"</info>,
                  if ($targets)
                     then <info>  Link resolved</info>
                     else $resultMap('log')
                  )
       return map{'target' : $targets, 'log' : $log, 'link' : $linkItem}
     else
       map{'target' : (),
                 'log' : (),
                 'link' : $linkItem
                }
};

(: Given a link descriptor map and the database that contains it, attempts
   to resolve the link to an element (in DITA a given link
   can address at most one element).

   Returns a map with the following members:
   'target': A sequence of zero or more elements addressed
             by the link.
   'log':    A sequence of zero or more log entry elements
             generated by the resolution attempt.
   'link':   The input link item.
 :)
declare function lmutil:resolveIndirectLink($linkItem as map(*)) as map(*) {

   let $topicref := $linkItem?topicref
   let $link := $linkItem?link
   let $keyName := df:getKeyNameForKeyref($link)
   (: Given the key name, look it up in the topicref's map (which must be a
      resolved map to find the key definition. The resolved map has had
      all key names expanded with their scope qualifications, so we can
      look up scope-qualified keys directly. :)
   let $keydef := lmutil:findKeyDefinition($keyName, $topicref)
   let $targets :=
       if ($keydef)
          then lmutil:resolveTopicRefFromResolvedMap($keydef)
          else ()

   let $log := ()
   return map{'target' : $targets, 'log' : $log , 'link' : $linkItem}
};

(:~
 : Given a key name and a topicref in a resolved map, find the applicable
 : key-defining topicref, if any.
 :
 : @param keyName The key name to look up.
 : @param topicref The topicref that establishes the map context (and thus
 :                 the starting key scope for the lookup)
 : @return The key-defining topicref or empty sequence if no key definition
 :             is found.
 :)
declare function lmutil:findKeyDefinition(
                            $keyName as xs:string,
                            $topicref as element()) as element()? {
  (: Key scope-defining element is either the nearest ancestor topicref that
     specifies @keyscope or the root map element.
   :)
  let $scope := ($topicref//ancestor-or-self::*[@keyscope], root($topicref)/*)[1]
  (: Within the scope, the effective key definition is the first definition,
     in depth-first (document) order that specifies the key name.
   :)
  let $result := ()
  return $result
};

(:~
 : Given a database, finds all the indirect links. Returns a map
 : the the members:
 : 'links' : A sequence of maps, where each map represents one link.
 : 'log' : A sequence of log entry elements.
 :
 : Each link map has the following items:
 :
 : 'link' : The element that is the link
 : 'rootMap' : The root map document that defines the namespace the link
 :             is resolved in.
 : 'resolvedMap' : The fully-resolved map that defines key space the key
 :                 reference is resolved in.
 : 'keySpace' : The constructed key space for the root map.
 :
 :)
declare function lmutil:findAllIndirectLinks($dbName) as map(*)* {
   (:

1. Find all root maps (maps with no local-scope topicref references or
   maps with peer topicref references). This requires that the direct-reference
   use records are up to date. It also requires that the resolved map and key space
   documents have already been created.

2. For each root map, Walk the resolved map, creating link items for each key-based topicref.
   Resolve topicrefs to topics and process each topic to create link items for each key-based
   link in each topic.

   :)

   let $rootMaps as element()* := lmutil:getRootMaps($dbName)

   let $linksFromTopics := lmutil:getIndirectLinksFromTopics($rootMaps)

    let $linksFromMaps := () (: FIXME: Build this list as well :)
    let $links := ($linksFromTopics, $linksFromMaps)

   return $links
};

(:~
 : Get all the indirect links in topics referenced from the root maps
 :
 : @para rootMaps list of root content maps.
 :
 : @return Sequence, possibly empty, of link item maps.
 :)
declare function lmutil:getIndirectLinksFromTopics($rootMaps as element()*) as map(*)* {
  let $result :=
     for $map in $rootMaps
         let $resolvedMap as element() := lmutil:getResolvedMapForMap($map)
         let $bos as map(*)* := lmutil:getMapBoundedObjectSet($resolvedMap, ('dita'))
         return for $member in $bos
            return lmutil:getIndirectLinks($bos)
  return $result
};

(:~
 : Takes a sequence of map BOS members and, for each member,
 : finds the key-based links in the member and returns a of link
 : structures reflecting those links.
 :
 : @param bos Sequence of maps, one for each use of a topic from a
 : DITA map. Each map has two members, "topicref", and "resource"
 : @return A sequence, possibly empty, of link maps.
 :)
declare function lmutil:getIndirectLinks($bos as map(*)*) as map(*)* {
   let $result as map(*)* :=
       for $member in $bos
           return lmutil:getIndirectLinksForBOSMember($member)
   return () (: $result :)
};

(:~
 : Given a BOS member map for a topic, finds all key-based links in the
 : topic and returns a sequence of link items for the links.
 :
 : @param member BOS member map containing a topic BOS member.
 : @return A sequence, possibly empty, of link items.
 :)
declare function lmutil:getIndirectLinksForBOSMember($member as map(*)) as map(*)* {
   let $topicref := $member('topicref')
   let $topic := $member('resource')
   let $linkElems := $topic//*[@keyref]
   let $linkItems :=
       for $elem in $linkElems
           return lmutil:constructLinkItemMap($elem, $topicref)
   return $linkItems
};

(:~
 : Given a map resolves all the topicrefs to their local-scope resources
 : and returns the set of "BOS members", where each member is a map
 : with the topicref that pointed to the topic and the resolved topic.
 : The topicref is required in order to have the map context, which is required
 : in order to determine the key space within which any key references within the
 : topic are resolved. Note that a BOS member is a unique topicref/resource pair.
 : If the same resource is referenced multiple times in the map there will be one BOS member
 : for each reference.
 :
 : @param map Map to process. Does not resolve submap references, so if
 : you want the resources for a map tree supply the resolved map.
 :
 : @param formats A list of one or more @format values to return in the set.
 : The special value '#non-dita' matches any @format value that is not 'dita'
 : or 'dita-map'. Specify ('dita') to return only topic members of
 : the BOS. Non-DITA resources are represented by the topicrefs that point to
 : them. If not specified, all local-scope resources are returned.
 : @return Sequence of maps, one for each topicref/resource pair
 :)
declare function lmutil:getMapBoundedObjectSet(
                            $map as element(),
                            $formats as xs:string*) as map(*)* {
  let $topicrefs := $map//*[df:isTopicRef(.)]
                           [df:isLocalScope(.)]
                           [not($formats) or
                            df:getEffectiveFormat(.) = $formats]
  let $members :=
      for $topicref in $topicrefs
          let $resource := if (df:getEffectiveFormat($topicref) = ('dita'))
             then lmutil:resolveTopicRefFromResolvedMap($topicref)
             else $topicref
          return map { 'topicref' : $topicref,
                       'resource' : $resource }
  return $members

};

(:~
 : Resolves a topicref from a resolved map. Uses the additional metadata
 : in the resolved map to determine the target document that contains
 : the element.
 :)
declare function lmutil:resolveTopicRefFromResolvedMap($topicref as element())
                                                                    as element()? {
  let $baseURI := string(($topicref/ancestor::*[@origMapURI]/@origMapURI)[1])
  let $targetURI := string($topicref/@href)
  let $resolvedURI := relpath:resolveURI($targetURI, $baseURI)
  let $result := try {
    let $doc as document-node()? := doc($resolvedURI)
    let $elem := if ($doc) then $doc/* else()
    return $elem
  } catch * {
    (: Document not found :)
    ()
  }
  return $result
};

(:~
 : Find maps that either have no local-scope topicrefs to them or that have
 : any peer-scope topicrefs to them.
 :
 : @param dbName Name of the content database that holds the map to examine.
 : @return List, possibly empty, of root maps.
 :)
declare function lmutil:getRootMaps($dbName as xs:string) as element()* {
  let $candMaps := collection($dbName)/*[df:class(., 'map/map')]
  let $result :=
      for $candMap in $candMaps
          return if (lmutil:isRootMap($candMap))
                   then $candMap
                   else ()
  return $result
};

(:~
 : Returns true if the specified map element is a root map.
 :
 : Note that there are many ways that root mapness could be determined.
 : The logic used here is any map that has no direct map local-scope references
 : or any peer-scope references. This is based on the presumption that a root
 : map would not normally be useable as local-scope submap. DITA 1.3's new
 : meaning for scope="peer" on topicrefs to maps explicitly means "the referenced
 : map is a root map".
 :
 : Other options would be to have a master map that uses peer map references to
 : explicitly identify root maps and use only that to determine rootness, to
 : maintain some sort of metadata that indicates rootness, use a specific map
 : specialization or map specialization plus descendant element configuration
 : (e.g., bookmaps that have booktitle elements are root maps, all others are
 : not).
 :
 : @param map Map to check for rootness
 : @return true() if the map is a root map.
 :)
declare function lmutil:isRootMap($map as element()) as xs:boolean {
  let $result := ((lmutil:getRefCount($map, $lmutil:useMatchParamsLocalMaps) = 0) or
                  (lmutil:getRefCount($map, $lmutil:useMatchParamsPeerMaps) > 0))
  return $result
};

(:~
 : Gets the number of references to the specified element that match the specified
 : match criteria.
 :
 : @param elem Element to get reference count for.
 : @param matcher Use record matcher to use for selecting references
 : @return Number of matches
 :)
declare function lmutil:getRefCount($elem as element(),
                                    $matchParams as map(*)) as xs:integer {
  let $uses := lmutil:getUses($elem, $matchParams)
  let $result := count($uses)
  return $result
};

(: Construct a string report of the listed attributes :)
declare function lmutil:reportAtts($elem as element(), $attNames) as xs:string {
   let $result := for $att in $elem/@*
                      return if (name($att) = $attNames)
                                then concat(name($att), '="', string($att), '"')
                                else ()
   return string-join($result, ' ')
};

(:~
 : Report a link item map as XML
 :
 : @param linkItem
 : @return XML representation of the link
 :)
declare function lmutil:reportLinkItemMap($linkItem as map(*)) as element() {
(:
 : 'link' : The element that is the link
 : 'rootMap' : The root map document that defines the namespace the link
 :             is resolved in.
 : 'resolvedMap' : The fully-resolved map that defines key space the key
 :                 reference is resolved in.
 : 'keySpace' : The constructed key space for the root map.
 :)
  <linkItem>{
   for $key in map:keys($linkItem)
       return element {$key} { $linkItem($key) }
  }</linkItem>
};

(:~
 : Get the resolved map document for a map. The resolved map must have already
 : been constructed (XQuery doesn't let use do updating actions wherever we
 : want).
 :
 : @param map Content map to get the resolved map for.
 : @return the resolved map or an empty sequence if there is no resolved map
 : (for example, because the map is not a root map).
 :)
declare function lmutil:getResolvedMapForMap($map as element()) as element()? {
  let $resolvedMapURI as xs:string := lmutil:getResolvedMapURIForMap($map)
  let $metadataDbName as xs:string := bxutil:getMetadataDbNameForDoc(root($map))

  let $resolvedMap := collection($metadataDbName || $resolvedMapURI)
  return $resolvedMap/*
};

(:~
 : Construct the database URI to use for a resolved map.
 :
 : @param map DITA map element to get the URI for
 : @returns The URI of the resolved map as a string
 :)
declare function lmutil:getResolvedMapURIForMap(
                        $map as element()) as xs:string {
  let $mapDocHash := hash:md5(document-uri(root($map)))
  return $dfstcnst:resolved-map-dir ||
         "/" || $mapDocHash || ".ditamap"
};

(: End of Module :)


-- Fixed query

-- Fixed query

declare function recursiveActor($destinations as xs:string*, $actor as xs:string) as node()*
{
let $db := <film><filmName>x</filmName><actorName>Sean Connery</actorName></film>
let $val := $db//filmName[../actorName=$actor]
let $cnt := count($destinations)
let $pos := ($cnt div 2) cast as xs:integer
let $dsts1 := subsequence($destinations, 1, $pos)
let $dsts2 := subsequence($destinations, $pos+1)
return
(
if ($cnt > 1)
then recursiveActor($dsts1, $actor)
else ()
,
$val
,
if ($cnt > 2)
then recursiveActor($dsts2, $actor)
else ()
)
};

recursiveActor(("http://a.org","http://b.org","http://c.org","http://d.org","http://e.org"), "Sean Connery")

declare function recursiveActor($destinations as xs:string*, $actor as xs:string) as node()
{
let $db := <film><filmName>x</filmName><actorName>Sean Connery</actorName></film>
let $val := $db//filmName[../actorName=$actor]
let $cnt := count($destinations)
let $pos := ($cnt / 2) cast as xs:integer
let $dsts1 := subsequence($destinations, 1, $pos)
let $dsts2 := subsequence($destinations, $pos+1)
return
(
if ($cnt > 1)
then recursiveActor($dsts1, $actor)
else ()
,
$val
,
if ($cnt > 2)
then recursiveActor($dsts2, $actor)
else ()
)
};

recursiveActor(("http://a.org","http://b.org","http://c.org","http://d.org","http://e.org"), "Sean Connery")


Annotate the MarkLogic semantics functions with versioned type restrictions.

xquery version "1.0-ml";
(:~
 : MarkLogic semantics functions
 :
 : @see https://docs.marklogic.com/xdmp/extension
 : @see https://docs.marklogic.com/sem/semantic-functions
 :)
module namespace sem = "http://marklogic.com/xdmp/semantics";

declare namespace a = "http://reecedunn.co.uk/xquery/annotations";
declare namespace o = "http://reecedunn.co.uk/xquery/options";

declare option o:requires "marklogic/7.0";

declare %a:since("marklogic", "7.0") function sem:binding() as sem:binding external;
declare %a:since("marklogic", "7.0") function sem:binding($map as element(json:object)) as sem:binding external;
declare %a:since("marklogic", "8.0") function sem:bnode() as sem:blank external;
declare %a:since("marklogic", "8.0") function sem:bnode($value as xs:anyAtomicType) as sem:blank external;
declare %a:since("marklogic", "7.0") function sem:coalesce($parameters as item()*...) as item()* external;
declare %a:since("marklogic", "7.0") function sem:datatype($value as xs:anyAtomicType) as sem:iri external;
declare %a:since("marklogic", "8.0") function sem:default-graph-iri() as sem:iri external;
declare %a:since("marklogic", "8.0") function sem:graph-add-permissions($graph as sem:iri, $permissions as element(sec:permission)*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:graph-get-permissions($graph as sem:iri) as element(sec:permission)* external;
declare %a:since("marklogic", "8.0") function sem:graph-get-permissions($graph as sem:iri, $format as xs:string) as element(sec:permission)* external;
declare %a:since("marklogic", "8.0") function sem:graph-remove-permissions($graph as sem:iri, $permissions as element(sec:permission)*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:graph-set-permissions($graph as sem:iri, $permissions as element(sec:permission)*) as empty-sequence() external;
declare %a:since("marklogic", "7.0") function sem:if($condition as xs:boolean, $then as item()*, $else as item()*) as item()* external;
declare %a:since("marklogic", "8.0") function sem:in-memory-store($dataset as sem:triple*) as sem:store external;
declare %a:since("marklogic", "7.0") function sem:invalid($string as xs:string, $datatype as sem:iri) as sem:invalid external;
declare %a:since("marklogic", "7.0") function sem:invalid-datatype($val as sem:invalid) as sem:iri external;
declare %a:since("marklogic", "7.0") function sem:isBlank($value as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:isIRI($value as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:isLiteral($value as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "8.0") function sem:isNumeric($value as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:lang($value as xs:anyAtomicType) as xs:string external;
declare %a:since("marklogic", "7.0") function sem:langMatches($lang-tag as xs:string, $lang-range as xs:string) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:random() as xs:double external;
declare %a:since("marklogic", "8.0") function sem:resolve-iri($relative as xs:string) as sem:iri external;
declare %a:since("marklogic", "8.0") function sem:resolve-iri($relative as xs:string, $base as xs:string) as sem:iri external;
declare %a:since("marklogic", "8.0") function sem:ruleset-store($locations as xs:string*) as sem:store external;
declare %a:since("marklogic", "8.0") function sem:ruleset-store($locations as xs:string*, $store as sem:store*) as sem:store external;
declare %a:since("marklogic", "8.0") function sem:ruleset-store($locations as xs:string*, $store as sem:store*, $options as xs:string*) as sem:store external;
declare %a:since("marklogic", "7.0") function sem:sameTerm($a as xs:anyAtomicType, $b as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:sparql($sparql as xs:string) as item()* external;
declare %a:since("marklogic", "7.0") function sem:sparql($sparql as xs:string, $bindings as map:map?) as item()* external;
declare %a:since("marklogic", "7.0") function sem:sparql($sparql as xs:string, $bindings as map:map?, $options as xs:string*) as item()* external;
declare %a:restrict-until("$query_or_store", "marklogic", "8.0", "cts:query?")
        %a:restrict-since("$query_or_store", "marklogic", "8.0", "sem:store*")
        %a:since("marklogic", "7.0") function sem:sparql($sparql as xs:string, $bindings as map:map?, $options as xs:string*, $query_or_store as (cts:query?|sem:store*)) as item()* external;
declare %a:since("marklogic", "7.0") %a:until("marklogic", "8.0") function sem:sparql($sparql as xs:string, $bindings as map:map?, $options as xs:string*, $query as cts:query?, $forest-ids as xs:unsignedLong*) as item()* external;
declare %a:since("marklogic", "9.0") function sem:sparql-plan($sparql as xs:string) as element() external;
declare %a:since("marklogic", "9.0") function sem:sparql-plan($sparql as xs:string, $bindingNames as xs:string*) as element() external;
declare %a:since("marklogic", "9.0") function sem:sparql-plan($sparql as xs:string, $bindingNames as xs:string*, $options as xs:string*) as element() external;
declare %a:since("marklogic", "7.0") %a:until("marklogic", "8.0") function sem:sparql-triples($sparql as xs:string, $dataset as sem:triple*) as item()* external;
declare %a:since("marklogic", "7.0") %a:until("marklogic", "8.0") function sem:sparql-triples($sparql as xs:string, $dataset as sem:triple*, $bindings as map:map?) as item()* external;
declare %a:since("marklogic", "7.0") %a:until("marklogic", "8.0") function sem:sparql-triples($sparql as xs:string, $dataset as sem:triple*, $bindings as map:map?, $options as xs:string*) as item()* external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string, $bindings as map:map?) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string, $bindings as map:map?, $options as xs:string*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string, $bindings as map:map?, $options as xs:string*, $store as sem:store*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string, $bindings as map:map?, $options as xs:string*, $store as sem:store*, $default-permissions as element(sec:permission)*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:store() as sem:store external;
declare %a:since("marklogic", "8.0") function sem:store($options as xs:string*) as sem:store external;
declare %a:since("marklogic", "8.0") function sem:store($options as xs:string*, $query as cts:query?) as sem:store external;
declare %a:since("marklogic", "7.0") function sem:timezone-string($value as xs:dateTime) as xs:string external;
declare %a:since("marklogic", "7.0") function sem:triple($subject_or_node as item()) as sem:triple external;
declare %a:since("marklogic", "7.0") function sem:triple($subject_or_node as item(), $predicate as xs:anyAtomicType) as sem:triple external;
declare %a:since("marklogic", "7.0") function sem:triple($subject_or_node as item(), $predicate as xs:anyAtomicType, $object as xs:anyAtomicType) as sem:triple external;
declare %a:since("marklogic", "7.0") function sem:triple($subject_or_node as item(), $predicate as xs:anyAtomicType, $object as xs:anyAtomicType, $graph as sem:iri?) as sem:triple external;
declare %a:since("marklogic", "7.0") function sem:triple-graph($triple as sem:triple) as sem:iri? external;
declare %a:since("marklogic", "7.0") function sem:triple-object($triple as sem:triple) as xs:anyAtomicType external;
declare %a:since("marklogic", "7.0") function sem:triple-predicate($triple as sem:triple) as xs:anyAtomicType external;
declare %a:since("marklogic", "7.0") function sem:triple-subject($triple as sem:triple) as xs:anyAtomicType external;
declare %a:since("marklogic", "7.0") function sem:typed-literal($value as xs:string, $datatype as sem:iri) as xs:anyAtomicType external;
declare %a:since("marklogic", "7.0") function sem:unknown($string as xs:string, $datatype as sem:iri) as sem:unknown external;
declare %a:since("marklogic", "7.0") function sem:unknown-datatype($val as sem:unknown) as sem:iri external;
declare %a:since("marklogic", "7.0") function sem:uuid() as sem:iri external;
declare %a:since("marklogic", "7.0") function sem:uuid-string() as xs:string external;

xquery version "1.0-ml";
(:~
 : MarkLogic semantics functions
 :
 : @see https://docs.marklogic.com/xdmp/extension
 : @see https://docs.marklogic.com/sem/semantic-functions
 :)
module namespace sem = "http://marklogic.com/xdmp/semantics";

declare namespace a = "http://reecedunn.co.uk/xquery/annotations";
declare namespace o = "http://reecedunn.co.uk/xquery/options";

declare option o:requires "marklogic/7.0";

declare %a:since("marklogic", "7.0") function sem:binding() as sem:binding external;
declare %a:since("marklogic", "7.0") function sem:binding($map as element(json:object)) as sem:binding external;
declare %a:since("marklogic", "8.0") function sem:bnode() as sem:blank external;
declare %a:since("marklogic", "8.0") function sem:bnode($value as xs:anyAtomicType) as sem:blank external;
declare %a:since("marklogic", "7.0") function sem:coalesce($parameters as item()*...) as item()* external;
declare %a:since("marklogic", "7.0") function sem:datatype($value as xs:anyAtomicType) as sem:iri external;
declare %a:since("marklogic", "8.0") function sem:default-graph-iri() as sem:iri external;
declare %a:since("marklogic", "8.0") function sem:graph-add-permissions($graph as sem:iri, $permissions as element(sec:permission)*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:graph-get-permissions($graph as sem:iri) as element(sec:permission)* external;
declare %a:since("marklogic", "8.0") function sem:graph-get-permissions($graph as sem:iri, $format as xs:string) as element(sec:permission)* external;
declare %a:since("marklogic", "8.0") function sem:graph-remove-permissions($graph as sem:iri, $permissions as element(sec:permission)*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:graph-set-permissions($graph as sem:iri, $permissions as element(sec:permission)*) as empty-sequence() external;
declare %a:since("marklogic", "7.0") function sem:if($condition as xs:boolean, $then as item()*, $else as item()*) as item()* external;
declare %a:since("marklogic", "8.0") function sem:in-memory-store($dataset as sem:triple*) as sem:store external;
declare %a:since("marklogic", "7.0") function sem:invalid($string as xs:string, $datatype as sem:iri) as sem:invalid external;
declare %a:since("marklogic", "7.0") function sem:invalid-datatype($val as sem:invalid) as sem:iri external;
declare %a:since("marklogic", "7.0") function sem:isBlank($value as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:isIRI($value as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:isLiteral($value as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "8.0") function sem:isNumeric($value as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:lang($value as xs:anyAtomicType) as xs:string external;
declare %a:since("marklogic", "7.0") function sem:langMatches($lang-tag as xs:string, $lang-range as xs:string) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:random() as xs:double external;
declare %a:since("marklogic", "8.0") function sem:resolve-iri($relative as xs:string) as sem:iri external;
declare %a:since("marklogic", "8.0") function sem:resolve-iri($relative as xs:string, $base as xs:string) as sem:iri external;
declare %a:since("marklogic", "8.0") function sem:ruleset-store($locations as xs:string*) as sem:store external;
declare %a:since("marklogic", "8.0") function sem:ruleset-store($locations as xs:string*, $store as sem:store*) as sem:store external;
declare %a:since("marklogic", "8.0") function sem:ruleset-store($locations as xs:string*, $store as sem:store*, $options as xs:string*) as sem:store external;
declare %a:since("marklogic", "7.0") function sem:sameTerm($a as xs:anyAtomicType, $b as xs:anyAtomicType) as xs:boolean external;
declare %a:since("marklogic", "7.0") function sem:sparql($sparql as xs:string) as item()* external;
declare %a:since("marklogic", "7.0") function sem:sparql($sparql as xs:string, $bindings as map:map?) as item()* external;
declare %a:since("marklogic", "7.0") function sem:sparql($sparql as xs:string, $bindings as map:map?, $options as xs:string*) as item()* external;
declare %a:since("marklogic", "7.0") function sem:sparql($sparql as xs:string, $bindings as map:map?, $options as xs:string*, $query_or_store (: as [7.0]cts:query? [8.0]sem:store* :)) as item()* external;
declare %a:since("marklogic", "7.0") %a:until("marklogic", "8.0") function sem:sparql($sparql as xs:string, $bindings as map:map?, $options as xs:string*, $query as cts:query?, $forest-ids as xs:unsignedLong*) as item()* external;
declare %a:since("marklogic", "9.0") function sem:sparql-plan($sparql as xs:string) as element() external;
declare %a:since("marklogic", "9.0") function sem:sparql-plan($sparql as xs:string, $bindingNames as xs:string*) as element() external;
declare %a:since("marklogic", "9.0") function sem:sparql-plan($sparql as xs:string, $bindingNames as xs:string*, $options as xs:string*) as element() external;
declare %a:since("marklogic", "7.0") %a:until("marklogic", "8.0") function sem:sparql-triples($sparql as xs:string, $dataset as sem:triple*) as item()* external;
declare %a:since("marklogic", "7.0") %a:until("marklogic", "8.0") function sem:sparql-triples($sparql as xs:string, $dataset as sem:triple*, $bindings as map:map?) as item()* external;
declare %a:since("marklogic", "7.0") %a:until("marklogic", "8.0") function sem:sparql-triples($sparql as xs:string, $dataset as sem:triple*, $bindings as map:map?, $options as xs:string*) as item()* external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string, $bindings as map:map?) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string, $bindings as map:map?, $options as xs:string*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string, $bindings as map:map?, $options as xs:string*, $store as sem:store*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:sparql-update($sparql as xs:string, $bindings as map:map?, $options as xs:string*, $store as sem:store*, $default-permissions as element(sec:permission)*) as empty-sequence() external;
declare %a:since("marklogic", "8.0") function sem:store() as sem:store external;
declare %a:since("marklogic", "8.0") function sem:store($options as xs:string*) as sem:store external;
declare %a:since("marklogic", "8.0") function sem:store($options as xs:string*, $query as cts:query?) as sem:store external;
declare %a:since("marklogic", "7.0") function sem:timezone-string($value as xs:dateTime) as xs:string external;
declare %a:since("marklogic", "7.0") function sem:triple($subject_or_node as item()) as sem:triple external;
declare %a:since("marklogic", "7.0") function sem:triple($subject_or_node as item(), $predicate as xs:anyAtomicType) as sem:triple external;
declare %a:since("marklogic", "7.0") function sem:triple($subject_or_node as item(), $predicate as xs:anyAtomicType, $object as xs:anyAtomicType) as sem:triple external;
declare %a:since("marklogic", "7.0") function sem:triple($subject_or_node as item(), $predicate as xs:anyAtomicType, $object as xs:anyAtomicType, $graph as sem:iri?) as sem:triple external;
declare %a:since("marklogic", "7.0") function sem:triple-graph($triple as sem:triple) as sem:iri? external;
declare %a:since("marklogic", "7.0") function sem:triple-object($triple as sem:triple) as xs:anyAtomicType external;
declare %a:since("marklogic", "7.0") function sem:triple-predicate($triple as sem:triple) as xs:anyAtomicType external;
declare %a:since("marklogic", "7.0") function sem:triple-subject($triple as sem:triple) as xs:anyAtomicType external;
declare %a:since("marklogic", "7.0") function sem:typed-literal($value as xs:string, $datatype as sem:iri) as xs:anyAtomicType external;
declare %a:since("marklogic", "7.0") function sem:unknown($string as xs:string, $datatype as sem:iri) as sem:unknown external;
declare %a:since("marklogic", "7.0") function sem:unknown-datatype($val as sem:unknown) as sem:iri external;
declare %a:since("marklogic", "7.0") function sem:uuid() as sem:iri external;
declare %a:since("marklogic", "7.0") function sem:uuid-string() as xs:string external;


[feature] Add the facility to wrap text nodes in <text-node> elements for debugging

(:~
    KWIC module: formats query results to display keywords in context (KWIC). A configurable
    amount of text is displayed to the left and right of a matching keyword (or phrase).

    The module works with all indexes that support match highlighting (matches are tagged
    with an <exist:match> element or exist:matches attribute). This includes the old
    full text index, the new Lucene-based full text index, as well as the NGram index.

    The kwic:summarize() function represents the main entry point into the module.
    To have more control over the text extraction context, you can also call
    kwic:get-summary() instead. For example, the following snippet will only print the
    first match within a given set of context nodes ($ancestor):

    let $matches := kwic:get-matches($hit)

    for $ancestor in $matches/ancestor::para | $matches/ancestor::title | $matches/ancestor::td

    return

        kwic:get-summary($ancestor, ($ancestor//exist:match, $ancestor//*[@exist:matches])[1], $config)

    The configuration element used by some functions has the following structure:

    <config
        width="character width"
        table="yes|no"
        link="URL to which the match is linked"
        whitespace-text-nodes="collapse|drop|leave"
        debug-text-nodes="yes|no"/>
:)
xquery version "3.0";

module namespace kwic = "http://exist-db.org/xquery/kwic";

import module namespace util = "http://exist-db.org/xquery/util";

declare namespace exist = "http://exist.sourceforge.net/NS/exist";

declare variable $kwic:MODE_BEFORE := "before";
declare variable $kwic:MODE_AFTER := "after";

declare %private variable $kwic:CHARS_SUMMARY := 120;
declare %private variable $kwic:CHARS_KWIC := 40;

(:~
	Like fn:substring, but takes a node argument. If the node is an element,
	a new element is created with the same node-name as the old one and the
	shortened text content.
:)
declare
    %private
function kwic:substring($node as item(), $start as xs:integer, $count as xs:integer) as node() {
	let $str := substring($node, $start, $count)
	return
		if ($node instance of element()) then
			element { node-name($node) } { $str }
		else
			text { $str }
};

declare
    %private
function kwic:display-text($text as text()?) as node()? {
    if ($text/parent::exist:match) then
    	{$text}
    else
        $text
};

declare
    %private
function kwic:callback($callback as (function(text(), xs:string) as text()?)?, $node as text(), $mode as xs:string) as text()? {
    if (exists($callback)) then
        $callback($node, $mode)
    else
        $node
};

(:~
	Generate the left-hand context of the match. Returns a sequence of nodes
	and strings, whose total string length is less than or equal to $max characters.

	Note: this function calls itself recursively until $nodes is empty or
	the returned sequence has the desired total string length.
:)
declare
    %private
function kwic:truncate-previous($root as node(), $node as node()?, $truncated as item()*,
	   $max as xs:integer, $chars as xs:integer, $callback as (function(text(), xs:string) as text()?)?) {
	if ($node) then
		let $next := $node/preceding::text()[1] intersect $root//text()
		return
			if (empty($next)) then
				$truncated
			else if ($chars + string-length($next) gt $max) then
			    let $str := kwic:callback($callback, $next, $kwic:MODE_BEFORE)
			    return
    			    if (exists($str)) then
        				let $remaining := $max - $chars
        				return (
        				    text { "..." },
        				    kwic:substring($str, string-length($str) - $remaining + 1, $remaining),
        				    $truncated
        			    )
        			else
        			    kwic:truncate-previous($root, $next, $truncated, $max, $chars, $callback)
			else
				kwic:truncate-previous($root, $next,
				    (kwic:callback($callback, $next, $kwic:MODE_BEFORE), $truncated),
					$max, $chars + string-length($next), $callback)
	else
		$truncated
};

(:~
	Generate the right-hand context of the match. Returns a sequence of nodes
	and strings, whose total string length is less than or equal to $max characters.

	Note: this function calls itself recursively until $nodes is empty or
	the returned sequence has the desired total string length.
:)
declare
    %private
function kwic:truncate-following($root as node(), $node as node()?, $truncated as item()*,
	$max as xs:integer, $chars as xs:integer, $callback as (function(text(), xs:string) as text()?)?) {
	if ($node) then
		let $next := $node/following::text()[1] intersect $root//text()
		return
			if (empty($next)) then
				$truncated
			else if ($chars + string-length($next) gt $max) then
			    let $str := kwic:callback($callback, $next, $kwic:MODE_AFTER)
			    return
    			    if (exists($str)) then
        				let $remaining := $max - $chars
        				return (
        				    $truncated, kwic:substring($next, 1, $remaining), text { "..." }
        			    )
        			else
        			    kwic:truncate-following($root, $next, $truncated, $max, $chars, $callback)
			else
				kwic:truncate-following($root, $next,
				    ($truncated, kwic:callback($callback, $next, $kwic:MODE_AFTER)),
					$max, $chars + string-length($next), $callback)
	else
		$truncated
};

(:~
	Computes the total string length of the nodes in the argument sequence
:)
declare
    %private
function kwic:string-length($nodes as item()*) as xs:integer {
	if (exists($nodes)) then
		sum($nodes ! string-length(.))
	else
		0
};

declare
    %private
function kwic:collapse-whitespace-fn($callback as (function(text(), xs:string) as text()?)?) as (function(text(), xs:string) as text()) {
    function($text as text(), $mode as xs:string) as text()? {
        let $text :=
            if (matches($text, "\s+")) then
                text { " " }
            else
                $text
        return
            if (exists($callback)) then
                $callback($text, $mode)
            else
                $text
    }
};

declare
    %private
function kwic:drop-whitespace-fn($callback as (function(text(), xs:string) as text()?)?) as (function(text(), xs:string) as text()?) {
    function($text as text(), $mode as xs:string) as text()? {
        let $text :=
            if (matches($text, "\s+")) then
                ()
            else
                $text
        return
            if (exists($text) and exists($callback)) then
                $callback($text, $mode)
            else
                $text
    }
};

declare
    %private
function kwic:output-text($debug-text-nodes as xs:boolean, $text-nodes as text()*) as node()* {
    if($debug-text-nodes) then
        $text-nodes ! <text-node>{.}</text-node>
    else
        $text-nodes
};

declare function kwic:get-summary($root as node(), $node as element(),
	$config as element(config)?) as element() {
	kwic:get-summary($root, $node, $config, ())
};

(:~
	Print a summary of the match in $node. Output a predefined amount of text to
	the left and the right of the match.

	@param $root root element which should be used as context for the match. It defines the
	    boundaries for the text extraction. Text will be taken from this context.
	@param $node the exist:match element or the element with @exist:macthes attribute to process.
	@param $config configuration element which determines the behaviour of the function
	@param $callback (optional) reference to a callback function which will be called
	once for every text node before it is appended to the displayed text. The function
	should accept 2 parameters: 1) a single text node, 2) a string indicating the
	current direction in which text is appended, i.e. $kwic:MODE_BEFORE or $kwic:MODE_AFTER.
	The function may return the empty sequence if the current node should be ignore
	(e.g. if it belongs to a "footnote" which should not be displayed). Otherwise it should
	return a single string.
:)
declare function kwic:get-summary($root as node(), $node as element(),
	$config as element(config)?,
    $callback as (function(text(), xs:string) as text()?)?
) as element() {
	let $chars := xs:integer(($config/@width, $kwic:CHARS_KWIC)[1])
	let $table := $config/@table = ('yes', 'true')
	let $whitespace-text-nodes := string($config/@whitespace-text-nodes)
	let $debug-text-nodes := $config/@debug-text-nodes = ('yes', 'true')

	let $callback :=
	   if ($whitespace-text-nodes = "collapse") then
	       kwic:collapse-whitespace-fn($callback)
	   else if ($whitespace-text-nodes = "drop") then
	       kwic:drop-whitespace-fn($callback)
	   else
	       $callback

	let $prevTrunc := kwic:truncate-previous($root, $node, (), $chars, 0, $callback)
	let $remain :=
		if (not($table)) then
			$chars * 2 - kwic:string-length($prevTrunc)
		else
			$chars
	let $followingTrunc := kwic:truncate-following($root, $node, (), $remain, 0, $callback)
	return
		if (not($table)) then

				{kwic:output-text($debug-text-nodes, $prevTrunc)}
				{
					if ($config/@link) then
						{kwic:output-text($debug-text-nodes, $node/text())}
					else
						{kwic:output-text($debug-text-nodes, $node/text())}
				}
				{kwic:output-text($debug-text-nodes, $followingTrunc)}

		else

				{kwic:output-text($debug-text-nodes, $prevTrunc)}

				{
					if ($config/@link) then
						{kwic:output-text($debug-text-nodes, $node/text())}
					else
						kwic:output-text($debug-text-nodes, $node/text())
				}

				{kwic:output-text($debug-text-nodes, $followingTrunc)}

};

(:~
    Expand the element in $hit. Creates an in-memory copy of the element and marks
    all element matches with an exist:match tag and attribute matches with an
    exist:matches tag, which will be used by all other functions in
    this module. You need to call kwic:expand before kwic:get-summary.
    kwic:summarize will call it automatically.
:)
declare function kwic:expand($hit as element()) as element() {
    util:expand($hit, "expand-xincludes=no highlight-matches=both")
};

(:~
    Return all matches within the specified element, $hit. Matches are returned as
    exist:match elements or elements with exist:matches attribute. The returned nodes
    are part of a new document whose root element is a copy of the specified $hit element.

    @param $hit an arbitrary XML element which has been selected by one of the full text
		operations or an ngram search.
:)
declare function kwic:get-matches($hit as element()) as element()* {
    let $expanded := kwic:expand($hit)
	return ($expanded//exist:match, $expanded//*[@exist:matches])
};

declare function kwic:summarize($hit as element(), $config as element(config)?) as element()* {
    kwic:summarize($hit, $config, ())
};

(:~
	Main function of the KWIC module: takes the passed element and returns an
	XHTML fragment containing a chunk of text before and after the first full text
	match in the node.

	The optional config parameter is used to configure the behaviour of the function:

	<config width="character width" table="yes|no" link="URL to which the match is linked"/>

	By default, kwic:summarize returns an XHTML fragment with the following structure:

	<p xmlns="http://www.w3.org/1999/xhtml">
		<span class="previous">Text before match</span>
		<a href="passed URL if any" class="hi">The highlighted term</a>
		<span class="following">Text after match</span>
	</p>

	If table=yes is passed with the config element, a tr table row will be returned instead
	of a span (using the same class names).

	@param $hit an arbitrary XML element which has been selected by one of the full text
		operations or an ngram search.
	@param $config configuration element to configure the behaviour of the function
:)
declare function kwic:summarize($hit as element(), $config as element(config)?,
    $callback as (function(text(), xs:string) as text()?)?) as element()* {
    let $expanded := util:expand($hit, "expand-xincludes=no highlight-matches=both")
	for $match in ($expanded//exist:match, $expanded//*[@exist:matches])
	return
		kwic:get-summary($expanded, $match, $config, $callback)
};

(:
declare function kwic:summarize-all($hits as element()*, $config as element(config),
    $wrap as function(node(), function(node()) as element()) as element()) {
    let $hits := util:expand($hits, "expand-xincludes=no")
    for $hit in $hits
    return
        $wrap($hit, function($node) {
            for $match in $node//exist:match
            return
        		kwic:get-summary($node, $match, $config, ())
        })
};
:)

(:~
    KWIC module: formats query results to display keywords in context (KWIC). A configurable
    amount of text is displayed to the left and right of a matching keyword (or phrase).

    The module works with all indexes that support match highlighting (matches are tagged
    with an <exist:match> element or exist:matches attribute). This includes the old
    full text index, the new Lucene-based full text index, as well as the NGram index.

    The kwic:summarize() function represents the main entry point into the module.
    To have more control over the text extraction context, you can also call
    kwic:get-summary() instead. For example, the following snippet will only print the
    first match within a given set of context nodes ($ancestor):

    let $matches := kwic:get-matches($hit)

    for $ancestor in $matches/ancestor::para | $matches/ancestor::title | $matches/ancestor::td

    return

        kwic:get-summary($ancestor, ($ancestor//exist:match, $ancestor//*[@exist:matches])[1], $config)

    The configuration element used by some functions has the following structure:

    <config
        width="character width"
        table="yes|no"
        link="URL to which the match is linked"
        whitespace-text-nodes="collapse|drop|leave"/>
:)
xquery version "3.0";

module namespace kwic = "http://exist-db.org/xquery/kwic";

import module namespace util = "http://exist-db.org/xquery/util";

declare namespace exist = "http://exist.sourceforge.net/NS/exist";

declare variable $kwic:MODE_BEFORE := "before";
declare variable $kwic:MODE_AFTER := "after";

declare %private variable $kwic:CHARS_SUMMARY := 120;
declare %private variable $kwic:CHARS_KWIC := 40;

(:~
	Like fn:substring, but takes a node argument. If the node is an element,
	a new element is created with the same node-name as the old one and the
	shortened text content.
:)
declare
    %private
function kwic:substring($node as item(), $start as xs:integer, $count as xs:integer) as node() {
	let $str := substring($node, $start, $count)
	return
		if ($node instance of element()) then
			element { node-name($node) } { $str }
		else
			text { $str }
};

declare
    %private
function kwic:display-text($text as text()?) as node()? {
    if ($text/parent::exist:match) then
    	{$text}
    else
        $text
};

declare
    %private
function kwic:callback($callback as (function(text(), xs:string) as text()?)?, $node as text(), $mode as xs:string) as text()? {
    if (exists($callback)) then
        $callback($node, $mode)
    else
        $node
};

(:~
	Generate the left-hand context of the match. Returns a sequence of nodes
	and strings, whose total string length is less than or equal to $max characters.

	Note: this function calls itself recursively until $nodes is empty or
	the returned sequence has the desired total string length.
:)
declare
    %private
function kwic:truncate-previous($root as node(), $node as node()?, $truncated as item()*,
	   $max as xs:integer, $chars as xs:integer, $callback as (function(text(), xs:string) as text()?)?) {
	if ($node) then
		let $next := $node/preceding::text()[1] intersect $root//text()
		return
			if (empty($next)) then
				$truncated
			else if ($chars + string-length($next) gt $max) then
			    let $str := kwic:callback($callback, $next, $kwic:MODE_BEFORE)
			    return
    			    if (exists($str)) then
        				let $remaining := $max - $chars
        				return (
        				    text { "..." },
        				    kwic:substring($str, string-length($str) - $remaining + 1, $remaining),
        				    $truncated
        			    )
        			else
        			    kwic:truncate-previous($root, $next, $truncated, $max, $chars, $callback)
			else
				kwic:truncate-previous($root, $next,
				    (kwic:callback($callback, $next, $kwic:MODE_BEFORE), $truncated),
					$max, $chars + string-length($next), $callback)
	else
		$truncated
};

(:~
	Generate the right-hand context of the match. Returns a sequence of nodes
	and strings, whose total string length is less than or equal to $max characters.

	Note: this function calls itself recursively until $nodes is empty or
	the returned sequence has the desired total string length.
:)
declare
    %private
function kwic:truncate-following($root as node(), $node as node()?, $truncated as item()*,
	$max as xs:integer, $chars as xs:integer, $callback as (function(text(), xs:string) as text()?)?) {
	if ($node) then
		let $next := $node/following::text()[1] intersect $root//text()
		return
			if (empty($next)) then
				$truncated
			else if ($chars + string-length($next) gt $max) then
			    let $str := kwic:callback($callback, $next, $kwic:MODE_AFTER)
			    return
    			    if (exists($str)) then
        				let $remaining := $max - $chars
        				return (
        				    $truncated, kwic:substring($next, 1, $remaining), text { "..." }
        			    )
        			else
        			    kwic:truncate-following($root, $next, $truncated, $max, $chars, $callback)
			else
				kwic:truncate-following($root, $next,
				    ($truncated, kwic:callback($callback, $next, $kwic:MODE_AFTER)),
					$max, $chars + string-length($next), $callback)
	else
		$truncated
};

(:~
	Computes the total string length of the nodes in the argument sequence
:)
declare
    %private
function kwic:string-length($nodes as item()*) as xs:integer {
	if (exists($nodes)) then
		sum($nodes ! string-length(.))
	else
		0
};

declare
    %private
function kwic:collapse-whitespace-fn($callback as (function(text(), xs:string) as text()?)?) as (function(text(), xs:string) as text()) {
    function($text as text(), $mode as xs:string) as text()? {
        let $text :=
            if (matches($text, "\s+")) then
                text { " " }
            else
                $text
        return
            if (exists($callback)) then
                $callback($text, $mode)
            else
                $text
    }
};

declare
    %private
function kwic:drop-whitespace-fn($callback as (function(text(), xs:string) as text()?)?) as (function(text(), xs:string) as text()?) {
    function($text as text(), $mode as xs:string) as text()? {
        let $text :=
            if (matches($text, "\s+")) then
                ()
            else
                $text
        return
            if (exists($text) and exists($callback)) then
                $callback($text, $mode)
            else
                $text
    }
};

declare function kwic:get-summary($root as node(), $node as element(),
	$config as element(config)?) as element() {
	kwic:get-summary($root, $node, $config, ())
};

(:~
	Print a summary of the match in $node. Output a predefined amount of text to
	the left and the right of the match.

	@param $root root element which should be used as context for the match. It defines the
	    boundaries for the text extraction. Text will be taken from this context.
	@param $node the exist:match element or the element with @exist:macthes attribute to process.
	@param $config configuration element which determines the behaviour of the function
	@param $callback (optional) reference to a callback function which will be called
	once for every text node before it is appended to the displayed text. The function
	should accept 2 parameters: 1) a single text node, 2) a string indicating the
	current direction in which text is appended, i.e. $kwic:MODE_BEFORE or $kwic:MODE_AFTER.
	The function may return the empty sequence if the current node should be ignore
	(e.g. if it belongs to a "footnote" which should not be displayed). Otherwise it should
	return a single string.
:)
declare function kwic:get-summary($root as node(), $node as element(),
	$config as element(config)?,
    $callback as (function(text(), xs:string) as text()?)?
) as element() {
	let $chars := xs:integer(($config/@width, $kwic:CHARS_KWIC)[1])
	let $table := $config/@table = ('yes', 'true')
	let $whitespace-text-nodes := string($config/@whitespace-text-nodes)

	let $callback :=
	   if ($whitespace-text-nodes = "collapse") then
	       kwic:collapse-whitespace-fn($callback)
	   else if ($whitespace-text-nodes = "drop") then
	       kwic:drop-whitespace-fn($callback)
	   else
	       $callback

	let $prevTrunc := kwic:truncate-previous($root, $node, (), $chars, 0, $callback)
	let $remain :=
		if (not($table)) then
			$chars * 2 - kwic:string-length($prevTrunc)
		else
			$chars
	let $followingTrunc := kwic:truncate-following($root, $node, (), $remain, 0, $callback)
	return
		if (not($table)) then

				{$prevTrunc}
				{
					if ($config/@link) then
						{ $node/text() }
					else
						{ $node/text() }
				}
				{$followingTrunc}

		else

				{$prevTrunc}

				{
					if ($config/@link) then
						{$node/text()}
					else
						$node/text()
				}

				{$followingTrunc}

};

(:~
    Expand the element in $hit. Creates an in-memory copy of the element and marks
    all element matches with an exist:match tag and attribute matches with an
    exist:matches tag, which will be used by all other functions in
    this module. You need to call kwic:expand before kwic:get-summary.
    kwic:summarize will call it automatically.
:)
declare function kwic:expand($hit as element()) as element() {
    util:expand($hit, "expand-xincludes=no highlight-matches=both")
};

(:~
    Return all matches within the specified element, $hit. Matches are returned as
    exist:match elements or elements with exist:matches attribute. The returned nodes
    are part of a new document whose root element is a copy of the specified $hit element.

    @param $hit an arbitrary XML element which has been selected by one of the full text
		operations or an ngram search.
:)
declare function kwic:get-matches($hit as element()) as element()* {
    let $expanded := kwic:expand($hit)
	return ($expanded//exist:match, $expanded//*[@exist:matches])
};

declare function kwic:summarize($hit as element(), $config as element(config)?) as element()* {
    kwic:summarize($hit, $config, ())
};

(:~
	Main function of the KWIC module: takes the passed element and returns an
	XHTML fragment containing a chunk of text before and after the first full text
	match in the node.

	The optional config parameter is used to configure the behaviour of the function:

	<config width="character width" table="yes|no" link="URL to which the match is linked"/>

	By default, kwic:summarize returns an XHTML fragment with the following structure:

	<p xmlns="http://www.w3.org/1999/xhtml">
		<span class="previous">Text before match</span>
		<a href="passed URL if any" class="hi">The highlighted term</a>
		<span class="following">Text after match</span>
	</p>

	If table=yes is passed with the config element, a tr table row will be returned instead
	of a span (using the same class names).

	@param $hit an arbitrary XML element which has been selected by one of the full text
		operations or an ngram search.
	@param $config configuration element to configure the behaviour of the function
:)
declare function kwic:summarize($hit as element(), $config as element(config)?,
    $callback as (function(text(), xs:string) as text()?)?) as element()* {
    let $expanded := util:expand($hit, "expand-xincludes=no highlight-matches=both")
	for $match in ($expanded//exist:match, $expanded//*[@exist:matches])
	return
		kwic:get-summary($expanded, $match, $config, $callback)
};

(:
declare function kwic:summarize-all($hits as element()*, $config as element(config),
    $wrap as function(node(), function(node()) as element()) as element()) {
    let $hits := util:expand($hits, "expand-xincludes=no")
    for $hit in $hits
    return
        $wrap($hit, function($node) {
            for $match in $node//exist:match
            return
        		kwic:get-summary($node, $match, $config, ())
        })
};
:)