# jlistlib.tcl - procedures for manipulating lists and paths
# 
# Copyright 1994 by Jay Sekora.  All rights reserved, except 
# that this file may be freely redistributed in whole or in part 
# for non­profit, noncommercial use.
# 
# 
# these procedures are required by
#     browser.tk
#     edit.tk
#     help.tk
#     more.tk
#     people.tk
#     prefs.tk
# they may be located in the file "~/.tk/jlibrary.tcl" (where they will
# be source'd by those applications on startup), or in the site-wide
# tk library directory, where they will be found (and loaded) by the
# default tk  unknown  procedure.
######################################################################

###### maybe jlist:listtopath and jlist:pathtolist should be in the
###### browser rather than in a library (because might want to
###### override them for special modes).

######################################################################
# jlist:listtopath list - translate a list to a full unix path
######################################################################

proc jlist:listtopath {list} {
  if {"x$list" == "x"} {return "/"}
  set path ""
  foreach element $list {
    append path "/$element"
  }
  return $path
}

######################################################################
# jlist:pathtolist path - translate unix path to full list
#   if path is relative, it has [pwd] prepended
######################################################################

proc jlist:pathtolist {path} {
  if {! [string match "/*" $path]} {
    if [catch {pwd} cwd] {
      j:alert -text "Can't get current directory for relative path `$path'."
    } else {
      set path "$cwd/$path"
    }
  }
  set path [string trimleft $path /]
  return [split $path "/"]
}

######################################################################
# jlist:tail list - return last element of list
######################################################################

proc jlist:tail {list} {
  set last [expr [llength $list] - 1]
  return [lindex $list $last]		;# returns {} on negative numbers
}

######################################################################
# jlist:ancestor generation list - return generation'th ancestor of list
#   ([jlist:ancestor 0] is list itself; [jlist:ancestor 1] is parent)
######################################################################

proc jlist:ancestor {generation list} {
  if {$generation == 0} {return $list}
  set first [expr [llength $list] - $generation]
  if {$first < 0} {
    return {}
  } else {
    return [lreplace $list $first end]	;# with nothing
  }
}

