# skd-edit v1.18 — Atomic 1C DCS editor
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
param(
[Parameter(Mandatory)]
[Alias('Path')]
[string]$TemplatePath,
[Parameter(Mandatory)]
[ValidateSet(
"add-field","add-total","add-calculated-field","add-parameter","add-filter",
"add-dataParameter","add-order","add-selection","add-dataSetLink",
"add-dataSet","add-variant","add-conditionalAppearance","add-drilldown",
"set-query","patch-query","set-outputParameter","set-structure",
"modify-field","modify-filter","modify-dataParameter","modify-parameter","modify-structure","set-field-role",
"rename-parameter","reorder-parameters",
"clear-selection","clear-order","clear-filter","clear-conditionalAppearance",
"remove-field","remove-total","remove-calculated-field","remove-parameter","remove-filter")]
[string]$Operation,
[Parameter(Mandatory)]
[string]$Value,
[string]$DataSet,
[string]$Variant,
[switch]$NoSelection
)
$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# --- 1. Resolve path ---
if (-not $TemplatePath.EndsWith(".xml")) {
$candidate = Join-Path (Join-Path $TemplatePath "Ext") "Template.xml"
if (Test-Path $candidate) {
$TemplatePath = $candidate
}
}
if (-not (Test-Path $TemplatePath)) {
Write-Error "File not found: $TemplatePath"
exit 1
}
$resolvedPath = (Resolve-Path $TemplatePath).Path
function Esc-Xml {
param([string]$s)
return $s.Replace('&','&').Replace('<','<').Replace('>','>').Replace('"','"')
}
function Resolve-QueryValue {
param([string]$val, [string]$baseDir)
if (-not $val.StartsWith("@")) { return $val }
$filePath = $val.Substring(1)
if ([System.IO.Path]::IsPathRooted($filePath)) {
$candidates = @($filePath)
} else {
$candidates = @(
(Join-Path $baseDir $filePath),
(Join-Path (Get-Location).Path $filePath)
)
}
foreach ($c in $candidates) {
if (Test-Path $c) {
return (Get-Content -Raw -Encoding UTF8 $c).TrimEnd()
}
}
Write-Error "Query file not found: $filePath (searched: $($candidates -join ', '))"
exit 1
}
$script:queryBaseDir = [System.IO.Path]::GetDirectoryName($resolvedPath)
# --- 2. Type system (copied from skd-compile) ---
$script:typeSynonyms = New-Object System.Collections.Hashtable
$script:typeSynonyms["число"] = "decimal"
$script:typeSynonyms["строка"] = "string"
$script:typeSynonyms["булево"] = "boolean"
$script:typeSynonyms["дата"] = "date"
$script:typeSynonyms["датавремя"] = "dateTime"
$script:typeSynonyms["стандартныйпериод"] = "StandardPeriod"
$script:typeSynonyms["bool"] = "boolean"
$script:typeSynonyms["str"] = "string"
$script:typeSynonyms["int"] = "decimal"
$script:typeSynonyms["integer"] = "decimal"
$script:typeSynonyms["number"] = "decimal"
$script:typeSynonyms["num"] = "decimal"
$script:typeSynonyms["справочникссылка"] = "CatalogRef"
$script:typeSynonyms["документссылка"] = "DocumentRef"
$script:typeSynonyms["перечислениессылка"] = "EnumRef"
$script:typeSynonyms["плансчетовссылка"] = "ChartOfAccountsRef"
$script:typeSynonyms["планвидовхарактеристикссылка"] = "ChartOfCharacteristicTypesRef"
$script:outputParamTypes = @{
"Заголовок" = "mltext"
"ВыводитьЗаголовок" = "dcsset:DataCompositionTextOutputType"
"ВыводитьПараметрыДанных" = "dcsset:DataCompositionTextOutputType"
"ВыводитьОтбор" = "dcsset:DataCompositionTextOutputType"
"МакетОформления" = "xs:string"
"РасположениеПолейГруппировки" = "dcsset:DataCompositionGroupFieldsPlacement"
"РасположениеРеквизитов" = "dcsset:DataCompositionAttributesPlacement"
"ГоризонтальноеРасположениеОбщихИтогов" = "dcscor:DataCompositionTotalPlacement"
"ВертикальноеРасположениеОбщихИтогов" = "dcscor:DataCompositionTotalPlacement"
}
function Resolve-TypeStr {
param([string]$typeStr)
if (-not $typeStr) { return $typeStr }
if ($typeStr -match '^([^(]+)\((.+)\)$') {
$baseName = $Matches[1].Trim()
$params = $Matches[2]
$resolved = $script:typeSynonyms[$baseName.ToLower()]
if ($resolved) { return "$resolved($params)" }
return $typeStr
}
if ($typeStr.Contains('.')) {
$dotIdx = $typeStr.IndexOf('.')
$prefix = $typeStr.Substring(0, $dotIdx)
$suffix = $typeStr.Substring($dotIdx)
$resolved = $script:typeSynonyms[$prefix.ToLower()]
if ($resolved) { return "$resolved$suffix" }
return $typeStr
}
$resolved = $script:typeSynonyms[$typeStr.ToLower()]
if ($resolved) { return $resolved }
return $typeStr
}
# --- 3. Parsers ---
function Parse-FieldShorthand {
param([string]$s)
$result = @{
dataPath = ""; field = ""; title = ""; type = ""
roles = @(); restrict = @()
}
# Extract [Title]
if ($s -match '\[([^\]]+)\]') {
$result.title = $Matches[1]
$s = $s -replace '\s*\[[^\]]+\]', ''
}
# Extract @roles
$roleMatches = [regex]::Matches($s, '@(\w+)')
foreach ($m in $roleMatches) {
$result.roles += $m.Groups[1].Value
}
$s = [regex]::Replace($s, '\s*@\w+', '')
# Extract #restrictions
$restrictMatches = [regex]::Matches($s, '#(\w+)')
foreach ($m in $restrictMatches) {
$result.restrict += $m.Groups[1].Value
}
$s = [regex]::Replace($s, '\s*#\w+', '')
# Split name: type
$s = $s.Trim()
if ($s.Contains(':')) {
$parts = $s -split ':', 2
$result.dataPath = $parts[0].Trim()
$result.type = Resolve-TypeStr ($parts[1].Trim())
} else {
$result.dataPath = $s
}
$result.field = $result.dataPath
return $result
}
function Read-FieldProperties($fieldEl) {
$props = @{
dataPath = ""; field = ""; title = ""; type = ""
roles = @(); restrict = @()
}
foreach ($ch in $fieldEl.ChildNodes) {
if ($ch.NodeType -ne 'Element') { continue }
switch ($ch.LocalName) {
"dataPath" { $props.dataPath = $ch.InnerText.Trim() }
"field" { $props.field = $ch.InnerText.Trim() }
"title" {
# Extract text from LocalStringType
foreach ($item in $ch.ChildNodes) {
if ($item.NodeType -eq 'Element' -and $item.LocalName -eq 'item') {
foreach ($gc in $item.ChildNodes) {
if ($gc.NodeType -eq 'Element' -and $gc.LocalName -eq 'content') {
$props.title = $gc.InnerText.Trim()
}
}
}
}
}
"valueType" {
# Read type info — store the raw element for now, we'll use type from parsed if overridden
$typeEl = $null
foreach ($gc in $ch.ChildNodes) {
if ($gc.NodeType -eq 'Element' -and $gc.LocalName -eq 'Type') {
$typeEl = $gc; break
}
}
if ($typeEl) {
$props["_rawTypeText"] = $typeEl.InnerText.Trim()
}
}
"role" {
foreach ($gc in $ch.ChildNodes) {
if ($gc.NodeType -eq 'Element') {
if ($gc.LocalName -eq 'periodNumber') {
$props.roles += "period"
} elseif ($gc.InnerText.Trim() -eq 'true') {
$props.roles += $gc.LocalName
}
}
}
}
"useRestriction" {
$revMap = @{ "field" = "noField"; "condition" = "noFilter"; "group" = "noGroup"; "order" = "noOrder" }
foreach ($gc in $ch.ChildNodes) {
if ($gc.NodeType -eq 'Element' -and $gc.InnerText.Trim() -eq 'true') {
$mapped = $revMap[$gc.LocalName]
if ($mapped) { $props.restrict += $mapped }
}
}
}
}
}
return $props
}
function Parse-TotalShorthand {
param([string]$s)
# "DataPath: Func" or "DataPath: Func(expr)" or "DataPath: ИмяРесурса" (identity)
$parts = $s -split ':', 2
$dataPath = $parts[0].Trim()
$funcPart = $parts[1].Trim()
# Known DCS aggregate functions (ru + en)
$aggFuncs = @('Сумма','Количество','Минимум','Максимум','Среднее',
'Sum','Count','Min','Max','Avg',
'Minimum','Maximum','Average')
if ($funcPart -match '^\w+\(') {
# Already has expression form: Func(expr)
return @{ dataPath = $dataPath; expression = $funcPart }
} elseif ($funcPart -in $aggFuncs) {
# Short: Func → Func(DataPath)
return @{ dataPath = $dataPath; expression = "$funcPart($dataPath)" }
} else {
# Identity or custom expression — use as-is
return @{ dataPath = $dataPath; expression = $funcPart }
}
}
function Parse-CalcShorthand {
param([string]$s)
# Pattern: "Name [Title]: type = Expression #noField #noFilter ...".
# - `[Title]` is extracted only from the LHS of '=' so that `[...]` inside
# an expression (e.g. index access) isn't interpreted as a title.
# - `#restrict` flags use a known-names pattern and are extracted globally —
# the docs put them after `=`, and the closed flag set avoids matching
# `#word` that happens to appear inside a string literal.
$restrictPattern = '#(noField|noFilter|noCondition|noGroup|noOrder)\b'
$restrict = @()
foreach ($m in [regex]::Matches($s, $restrictPattern)) {
$restrict += $m.Groups[1].Value
}
$s = [regex]::Replace($s, "\s*$restrictPattern", '')
$eqIdx = $s.IndexOf('=')
if ($eqIdx -gt 0) {
$lhs = $s.Substring(0, $eqIdx)
$rhs = $s.Substring($eqIdx + 1).Trim()
} else {
$lhs = $s
$rhs = $null
}
$title = ""
if ($lhs -match '\[([^\]]+)\]') {
$title = $Matches[1]
$lhs = $lhs -replace '\s*\[[^\]]+\]', ''
}
$lhs = $lhs.Trim()
if ($null -ne $rhs) {
if ($lhs.Contains(':')) {
$colonIdx = $lhs.IndexOf(':')
$dataPath = $lhs.Substring(0, $colonIdx).Trim()
$type = Resolve-TypeStr ($lhs.Substring($colonIdx + 1).Trim())
return @{ dataPath = $dataPath; expression = $rhs; type = $type; title = $title; restrict = $restrict }
}
return @{ dataPath = $lhs; expression = $rhs; type = ""; title = $title; restrict = $restrict }
}
return @{ dataPath = $lhs; expression = ""; type = ""; title = $title; restrict = $restrict }
}
function Parse-ParamShorthand {
param([string]$s)
$result = @{ name = ""; type = ""; value = $null; autoDates = $false; title = $null; hidden = $false; always = $false; availableValues = @() }
# Extract availableValue=... (must be before main parse — captures to end of string)
if ($s -match '\s*availableValue=(.+)$') {
$result.availableValues = Parse-AvailableValueList $Matches[1].Trim()
$s = ($s -replace '\s*availableValue=.+$', '').Trim()
}
if ($s -match '@autoDates') {
$result.autoDates = $true
$s = $s -replace '\s*@autoDates', ''
}
if ($s -match '@hidden\b') {
$result.hidden = $true
$s = $s -replace '\s*@hidden\b', ''
}
if ($s -match '@always\b') {
$result.always = $true
$s = $s -replace '\s*@always\b', ''
}
# Extract optional [Title] (mirrors Parse-FieldShorthand)
if ($s -match '\[([^\]]*)\]') {
$result.title = $Matches[1].Trim()
$s = ($s -replace '\s*\[[^\]]*\]\s*', ' ').Trim()
}
if ($s -match '^([^:]+):\s*(\S+)(\s*=\s*(.+))?$') {
$result.name = $Matches[1].Trim()
$result.type = Resolve-TypeStr ($Matches[2].Trim())
if ($Matches[4]) {
$result.value = $Matches[4].Trim()
}
} else {
$result.name = $s.Trim()
}
return $result
}
function Parse-FilterShorthand {
param([string]$s)
# use is tristate: $null = not specified (modify-* won't touch),
# $false = @off (explicit), $true = @on (explicit). add-* writes only when $false.
$result = @{ field = ""; op = "Equal"; value = $null; use = $null; userSettingID = $null; viewMode = $null }
if ($s -match '@user') {
$result.userSettingID = "auto"
$s = $s -replace '\s*@user', ''
}
if ($s -match '@off') {
$result.use = $false
$s = $s -replace '\s*@off', ''
}
if ($s -match '@on\b') {
$result.use = $true
$s = $s -replace '\s*@on\b', ''
}
if ($s -match '@quickAccess') {
$result.viewMode = "QuickAccess"
$s = $s -replace '\s*@quickAccess', ''
}
if ($s -match '@normal') {
$result.viewMode = "Normal"
$s = $s -replace '\s*@normal', ''
}
if ($s -match '@inaccessible') {
$result.viewMode = "Inaccessible"
$s = $s -replace '\s*@inaccessible', ''
}
$s = $s.Trim()
$opPatterns = @('<>', '>=', '<=', '=', '>', '<',
'notIn\b', 'in\b', 'inHierarchy\b', 'inListByHierarchy\b',
'notContains\b', 'contains\b', 'notBeginsWith\b', 'beginsWith\b',
'notFilled\b', 'filled\b')
$opJoined = $opPatterns -join '|'
if ($s -match "^(.+?)\s+($opJoined)\s*(.*)?$") {
$result.field = $Matches[1].Trim()
$opRaw = $Matches[2].Trim()
$valPart = if ($Matches[3]) { $Matches[3].Trim() } else { "" }
$opMap = @{
"=" = "Equal"; "<>" = "NotEqual"; ">" = "Greater"; ">=" = "GreaterOrEqual"
"<" = "Less"; "<=" = "LessOrEqual"; "in" = "InList"; "notIn" = "NotInList"
"inHierarchy" = "InHierarchy"; "inListByHierarchy" = "InListByHierarchy"
"contains" = "Contains"; "notContains" = "NotContains"
"beginsWith" = "BeginsWith"; "notBeginsWith" = "NotBeginsWith"
"filled" = "Filled"; "notFilled" = "NotFilled"
}
$mapped = $opMap[$opRaw]
if ($mapped) { $result.op = $mapped } else { $result.op = $opRaw }
if ($valPart -and $valPart -ne "_") {
if ($valPart -eq "true" -or $valPart -eq "false") {
$result.value = $valPart
$result["valueType"] = "xs:boolean"
} elseif ($valPart -match '^\d{4}-\d{2}-\d{2}T') {
$result.value = $valPart
$result["valueType"] = "xs:dateTime"
} elseif ($valPart -match '^\d+(\.\d+)?$') {
$result.value = $valPart
$result["valueType"] = "xs:decimal"
} elseif ($valPart -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета)\.') {
$result.value = $valPart
$result["valueType"] = "dcscor:DesignTimeValue"
} else {
$result.value = $valPart
$result["valueType"] = "xs:string"
}
}
} else {
$result.field = $s
}
return $result
}
function Parse-DataParamShorthand {
param([string]$s)
# use is tristate: $null = not specified (modify-* won't touch),
# $false = @off (explicit), $true = @on (explicit). add-* writes only when $false.
$result = @{ parameter = ""; value = $null; use = $null; userSettingID = $null; viewMode = $null }
if ($s -match '@user') {
$result.userSettingID = "auto"
$s = $s -replace '\s*@user', ''
}
if ($s -match '@off') {
$result.use = $false
$s = $s -replace '\s*@off', ''
}
if ($s -match '@on\b') {
$result.use = $true
$s = $s -replace '\s*@on\b', ''
}
if ($s -match '@quickAccess') {
$result.viewMode = "QuickAccess"
$s = $s -replace '\s*@quickAccess', ''
}
if ($s -match '@normal') {
$result.viewMode = "Normal"
$s = $s -replace '\s*@normal', ''
}
$s = $s.Trim()
if ($s -match '^([^=]+)=\s*(.+)$') {
$result.parameter = $Matches[1].Trim()
$valStr = $Matches[2].Trim()
$periodVariants = @("Custom","Today","ThisWeek","ThisTenDays","ThisMonth","ThisQuarter","ThisHalfYear","ThisYear","FromBeginningOfThisWeek","FromBeginningOfThisTenDays","FromBeginningOfThisMonth","FromBeginningOfThisQuarter","FromBeginningOfThisHalfYear","FromBeginningOfThisYear","LastWeek","LastTenDays","LastMonth","LastQuarter","LastHalfYear","LastYear","NextDay","NextWeek","NextTenDays","NextMonth","NextQuarter","NextHalfYear","NextYear","TillEndOfThisWeek","TillEndOfThisTenDays","TillEndOfThisMonth","TillEndOfThisQuarter","TillEndOfThisHalfYear","TillEndOfThisYear")
if ($periodVariants -contains $valStr) {
$result.value = @{ variant = $valStr }
} elseif ($valStr -match '^\d{4}-\d{2}-\d{2}T') {
$result.value = $valStr
} elseif ($valStr -eq "true" -or $valStr -eq "false") {
$result.value = $valStr
} else {
$result.value = $valStr
}
} else {
$result.parameter = $s
}
return $result
}
function Parse-OrderShorthand {
param([string]$s)
$s = $s.Trim()
if ($s -eq "Auto") {
return @{ field = "Auto"; direction = "" }
}
$parts = $s -split '\s+', 2
$field = $parts[0]
$dir = "Asc"
if ($parts.Count -gt 1 -and $parts[1] -match '(?i)^desc$') { $dir = "Desc" }
return @{ field = $field; direction = $dir }
}
function Parse-DataSetLinkShorthand {
param([string]$s)
$result = @{ source = ""; dest = ""; sourceExpr = ""; destExpr = ""; parameter = "" }
# Extract optional [param ParamName]
if ($s -match '\[param\s+([^\]]+)\]') {
$result.parameter = $Matches[1].Trim()
$s = $s -replace '\s*\[param\s+[^\]]+\]', ''
}
# Pattern: "Source > Dest on FieldA = FieldB"
if ($s -match '^(.+?)\s*>\s*(.+?)\s+on\s+(.+?)\s*=\s*(.+)$') {
$result.source = $Matches[1].Trim()
$result.dest = $Matches[2].Trim()
$result.sourceExpr = $Matches[3].Trim()
$result.destExpr = $Matches[4].Trim()
} else {
Write-Error "Invalid dataSetLink shorthand: $s. Expected: 'Source > Dest on FieldA = FieldB [param Name]'"
exit 1
}
return $result
}
function Parse-DataSetShorthand {
param([string]$s)
$s = $s.Trim()
# "Name: QUERY" — split on first ": " only if prefix is a single word (no spaces)
if ($s -match '^(\S+):\s(.+)$') {
return @{ name = $Matches[1]; query = $Matches[2] }
}
return @{ name = ""; query = $s }
}
function Parse-VariantShorthand {
param([string]$s)
$presentation = ""
if ($s -match '\[([^\]]+)\]') {
$presentation = $Matches[1]
$s = $s -replace '\s*\[[^\]]+\]', ''
}
$name = $s.Trim()
if (-not $presentation) { $presentation = $name }
return @{ name = $name; presentation = $presentation }
}
function Parse-ConditionalAppearanceShorthand {
param([string]$s)
$result = @{ param = ""; value = ""; filter = $null; fields = @() }
# Extract " when ..." — condition part
$whenIdx = $s.IndexOf(' when ')
$forIdx = $s.IndexOf(' for ')
# Determine boundaries
$mainEnd = $s.Length
if ($whenIdx -ge 0 -and $forIdx -ge 0) {
$mainEnd = [Math]::Min($whenIdx, $forIdx)
} elseif ($whenIdx -ge 0) {
$mainEnd = $whenIdx
} elseif ($forIdx -ge 0) {
$mainEnd = $forIdx
}
# Parse "for" fields
if ($forIdx -ge 0) {
$forEnd = $s.Length
if ($whenIdx -gt $forIdx) { $forEnd = $whenIdx }
$forPart = $s.Substring($forIdx + 5, $forEnd - $forIdx - 5).Trim()
$result.fields = @($forPart -split '\s*,\s*' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
}
# Parse "when" filter (supports " or " for OrGroup)
if ($whenIdx -ge 0) {
$whenEnd = $s.Length
if ($forIdx -gt $whenIdx) { $whenEnd = $forIdx }
$whenPart = $s.Substring($whenIdx + 6, $whenEnd - $whenIdx - 6).Trim()
$orParts = $whenPart -split '\s+or\s+'
if ($orParts.Count -gt 1) {
$result.filter = @($orParts | ForEach-Object { Parse-FilterShorthand $_.Trim() })
} else {
$result.filter = Parse-FilterShorthand $whenPart
}
}
# Parse main part: "Param = Value"
$mainPart = $s.Substring(0, $mainEnd).Trim()
$eqIdx = $mainPart.IndexOf('=')
if ($eqIdx -gt 0) {
$result.param = $mainPart.Substring(0, $eqIdx).Trim()
$result.value = $mainPart.Substring($eqIdx + 1).Trim()
} else {
$result.param = $mainPart
}
return $result
}
function Parse-StructureShorthand {
param([string]$s)
$segments = $s -split '\s*>\s*'
$result = @()
$innermost = $null
for ($i = $segments.Count - 1; $i -ge 0; $i--) {
$seg = $segments[$i].Trim()
$group = @{ type = "group" }
if ($seg -match '@name=(?:"([^"]+)"|''([^'']+)''|(\S+))') {
$rawName = if ($Matches[1]) { $Matches[1] } elseif ($Matches[2]) { $Matches[2] } else { $Matches[3] }
$group["name"] = $rawName.Trim()
$seg = ($seg -replace '\s*@name=(?:"[^"]+"|''[^'']+''|\S+)', '').Trim()
}
if ($seg -match '^(?i)(details|детали)$') {
$group["groupBy"] = @()
} else {
$fields = @($seg -split '\s*,\s*' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$group["groupBy"] = $fields
}
if ($null -ne $innermost) {
$group["children"] = @($innermost)
}
$innermost = $group
}
if ($innermost) { $result += $innermost }
return ,$result
}
function Parse-OutputParamShorthand {
param([string]$s)
$idx = $s.IndexOf('=')
if ($idx -gt 0) {
return @{
key = $s.Substring(0, $idx).Trim()
value = $s.Substring($idx + 1).Trim()
}
}
return @{ key = $s.Trim(); value = "" }
}
function Parse-AvailableValueList {
# Returns array of @{ value=...; presentation=... } from comma-separated list.
# Items can use 'single' or "double" quotes (stripped). Quoted spans preserve commas/colons.
param([string]$s)
$result = @()
if (-not $s) { return ,$result }
# Tokenize by ',' respecting quoted spans
$items = @()
$buf = New-Object System.Text.StringBuilder
$inQuote = $null
for ($i = 0; $i -lt $s.Length; $i++) {
$ch = $s[$i]
if ($inQuote) {
[void]$buf.Append($ch)
if ($ch -eq $inQuote) { $inQuote = $null }
} elseif ($ch -eq "'" -or $ch -eq '"') {
$inQuote = $ch
[void]$buf.Append($ch)
} elseif ($ch -eq ',') {
$items += $buf.ToString()
[void]$buf.Clear()
} else {
[void]$buf.Append($ch)
}
}
if ($buf.Length -gt 0) { $items += $buf.ToString() }
# For each item: split into value[:presentation], strip quotes
$stripQuotes = {
param($t)
$t = $t.Trim()
if ($t.Length -ge 2 -and (($t[0] -eq "'" -and $t[-1] -eq "'") -or ($t[0] -eq '"' -and $t[-1] -eq '"'))) {
return $t.Substring(1, $t.Length - 2)
}
return $t
}
foreach ($raw in $items) {
$item = $raw.Trim()
if (-not $item) { continue }
# Find first ':' outside quotes
$colonIdx = -1
$q = $null
for ($j = 0; $j -lt $item.Length; $j++) {
$c = $item[$j]
if ($q) {
if ($c -eq $q) { $q = $null }
} elseif ($c -eq "'" -or $c -eq '"') {
$q = $c
} elseif ($c -eq ':') {
$colonIdx = $j; break
}
}
if ($colonIdx -ge 0) {
$valPart = $item.Substring(0, $colonIdx)
$presPart = $item.Substring($colonIdx + 1)
$result += @{ value = (& $stripQuotes $valPart); presentation = (& $stripQuotes $presPart) }
} else {
$result += @{ value = (& $stripQuotes $item); presentation = "" }
}
}
return ,$result
}
# --- 4. Build-* functions (XML fragment generators) ---
function Build-ValueTypeXml {
param([string]$typeStr, [string]$indent)
if (-not $typeStr) { return "" }
$typeStr = Resolve-TypeStr $typeStr
$lines = @()
if ($typeStr -eq "boolean") {
$lines += "$indentxs:boolean"
return $lines -join "`r`n"
}
if ($typeStr -match '^string(\((\d+)\))?$') {
$len = if ($Matches[2]) { $Matches[2] } else { "0" }
$lines += "$indentxs:string"
$lines += "$indent"
$lines += "$indent`t$len"
$lines += "$indent`tVariable"
$lines += "$indent"
return $lines -join "`r`n"
}
if ($typeStr -match '^decimal\((\d+),(\d+)(,nonneg)?\)$') {
$digits = $Matches[1]
$fraction = $Matches[2]
$sign = if ($Matches[3]) { "Nonnegative" } else { "Any" }
$lines += "$indentxs:decimal"
$lines += "$indent"
$lines += "$indent`t$digits"
$lines += "$indent`t$fraction"
$lines += "$indent`t$sign"
$lines += "$indent"
return $lines -join "`r`n"
}
if ($typeStr -match '^(date|dateTime)$') {
$fractions = switch ($typeStr) {
"date" { "Date" }
"dateTime" { "DateTime" }
}
$lines += "$indentxs:dateTime"
$lines += "$indent"
$lines += "$indent`t$fractions"
$lines += "$indent"
return $lines -join "`r`n"
}
if ($typeStr -eq "StandardPeriod") {
$lines += "$indentv8:StandardPeriod"
return $lines -join "`r`n"
}
if ($typeStr -match '^(CatalogRef|DocumentRef|EnumRef|ChartOfAccountsRef|ChartOfCharacteristicTypesRef)\.') {
$lines += "$indentd5p1:$(Esc-Xml $typeStr)"
return $lines -join "`r`n"
}
if ($typeStr.Contains('.')) {
$lines += "$indentd5p1:$(Esc-Xml $typeStr)"
return $lines -join "`r`n"
}
$lines += "$indent$(Esc-Xml $typeStr)"
return $lines -join "`r`n"
}
function Build-MLTextXml {
param([string]$tag, [string]$text, [string]$indent)
$lines = @()
$lines += "$indent<$tag xsi:type=`"v8:LocalStringType`">"
$lines += "$indent`t"
$lines += "$indent`t`tru"
$lines += "$indent`t`t$(Esc-Xml $text)"
$lines += "$indent`t"
$lines += "$indent$tag>"
return $lines -join "`r`n"
}
function Build-RoleXml {
param([string[]]$roles, [string]$indent)
if (-not $roles -or $roles.Count -eq 0) { return "" }
$lines = @()
$lines += "$indent"
foreach ($role in $roles) {
if ($role -eq "period") {
$lines += "$indent`t1"
$lines += "$indent`tMain"
} else {
$lines += "$indent`ttrue"
}
}
$lines += "$indent"
return $lines -join "`r`n"
}
function Build-RestrictionXml {
param([string[]]$restrict, [string]$indent)
if (-not $restrict -or $restrict.Count -eq 0) { return "" }
$restrictMap = @{
"noField" = "field"; "noFilter" = "condition"; "noCondition" = "condition"
"noGroup" = "group"; "noOrder" = "order"
}
$lines = @()
$lines += "$indent"
foreach ($r in $restrict) {
$xmlName = $restrictMap["$r"]
if ($xmlName) {
$lines += "$indent`t<$xmlName>true$xmlName>"
}
}
$lines += "$indent"
return $lines -join "`r`n"
}
function Build-FieldFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
$lines += "$i`t$(Esc-Xml $parsed.dataPath)"
$lines += "$i`t$(Esc-Xml $parsed.field)"
if ($parsed.title) {
$lines += (Build-MLTextXml -tag "title" -text $parsed.title -indent "$i`t")
}
if ($parsed.restrict -and $parsed.restrict.Count -gt 0) {
$lines += (Build-RestrictionXml -restrict $parsed.restrict -indent "$i`t")
}
$roleXml = Build-RoleXml -roles $parsed.roles -indent "$i`t"
if ($roleXml) { $lines += $roleXml }
if ($parsed.type) {
$lines += "$i`t"
$lines += (Build-ValueTypeXml -typeStr $parsed.type -indent "$i`t`t")
$lines += "$i`t"
}
$lines += "$i"
return $lines -join "`r`n"
}
function Build-TotalFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
$lines += "$i`t$(Esc-Xml $parsed.dataPath)"
$lines += "$i`t$(Esc-Xml $parsed.expression)"
$lines += "$i"
return $lines -join "`r`n"
}
function Build-CalcFieldFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
$lines += "$i`t$(Esc-Xml $parsed.dataPath)"
$lines += "$i`t$(Esc-Xml $parsed.expression)"
if ($parsed.title) {
$lines += (Build-MLTextXml -tag "title" -text $parsed.title -indent "$i`t")
}
if ($parsed.restrict -and $parsed.restrict.Count -gt 0) {
$lines += (Build-RestrictionXml -restrict $parsed.restrict -indent "$i`t")
}
if ($parsed.type) {
$lines += "$i`t"
$lines += (Build-ValueTypeXml -typeStr $parsed.type -indent "$i`t`t")
$lines += "$i`t"
}
$lines += "$i"
return $lines -join "`r`n"
}
function Build-ParamValueXml {
# Returns array of XML lines for a ... element (or StandardPeriod block).
# Selects xsi:type by declared type, then falls back to value pattern.
param([string]$type, [string]$value, [string]$indent, [string]$tagName = "value", [string]$tagNs = "")
$i = $indent
$valStr = "$value"
$open = if ($tagNs) { "$tagNs`:$tagName" } else { $tagName }
$lines = @()
if ($type -eq "StandardPeriod") {
$lines += "$i<$open xsi:type=`"v8:StandardPeriod`">"
$lines += "$i`t$(Esc-Xml $valStr)"
$lines += "$i`t0001-01-01T00:00:00"
$lines += "$i`t0001-01-01T00:00:00"
$lines += "$i$open>"
return $lines
}
$xsi = $null
if ($type -match '^date') { $xsi = "xs:dateTime" }
elseif ($type -eq "boolean") { $xsi = "xs:boolean" }
elseif ($type -match '^decimal') { $xsi = "xs:decimal" }
elseif ($type -match '^string') { $xsi = "xs:string" }
elseif ($type -match '^(CatalogRef|DocumentRef|EnumRef|ChartOfAccountsRef|ChartOfCharacteristicTypesRef|ChartOfCalculationTypesRef|BusinessProcessRef|TaskRef|ExchangePlanRef)\.') {
$xsi = "dcscor:DesignTimeValue"
}
else {
# Type unknown or empty — guess from value
if ($valStr -match '^\d{4}-\d{2}-\d{2}T') { $xsi = "xs:dateTime" }
elseif ($valStr -eq "true" -or $valStr -eq "false") { $xsi = "xs:boolean" }
elseif ($valStr -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена)\.' -or
$valStr -match '^(Catalog|Document|Enum|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.') {
$xsi = "dcscor:DesignTimeValue"
}
else { $xsi = "xs:string" }
}
$lines += "$i<$open xsi:type=`"$xsi`">$(Esc-Xml $valStr)$open>"
return $lines
}
function Build-AvailableValueFragment {
# Returns XML lines (array) for a single block.
param($item, [string]$declaredType, [string]$indent)
$lines = @()
$lines += "$indent"
$valueLines = Build-ParamValueXml -type $declaredType -value $item.value -indent "$indent`t"
foreach ($vl in $valueLines) { $lines += $vl }
if ($item.presentation) {
$lines += "$indent`t"
$lines += "$indent`t`t"
$lines += "$indent`t`t`tru"
$lines += "$indent`t`t`t$(Esc-Xml $item.presentation)"
$lines += "$indent`t`t"
$lines += "$indent`t"
}
$lines += "$indent"
return $lines
}
function Build-ParamFragment {
param($parsed, [string]$indent)
$i = $indent
$fragments = @()
$lines = @()
$lines += "$i"
$lines += "$i`t$(Esc-Xml $parsed.name)"
if ($parsed.title) {
$lines += (Build-MLTextXml -tag "title" -text $parsed.title -indent "$i`t")
}
if ($parsed.type) {
$lines += "$i`t"
$lines += (Build-ValueTypeXml -typeStr $parsed.type -indent "$i`t`t")
$lines += "$i`t"
}
if ($null -ne $parsed.value) {
$valueLines = Build-ParamValueXml -type $parsed.type -value $parsed.value -indent "$i`t"
foreach ($vl in $valueLines) { $lines += $vl }
}
if ($parsed.hidden) {
$lines += "$i`ttrue"
$lines += "$i`tfalse"
}
if ($parsed.availableValues -and $parsed.availableValues.Count -gt 0) {
foreach ($av in $parsed.availableValues) {
$avLines = Build-AvailableValueFragment -item $av -declaredType $parsed.type -indent "$i`t"
foreach ($l in $avLines) { $lines += $l }
}
}
if ($parsed.always) {
$lines += "$i`t"
}
$lines += "$i"
$fragments += ($lines -join "`r`n")
if ($parsed.autoDates) {
$paramName = $parsed.name
# Canonical БСП pattern: title + valueType + value + useRestriction + expression
$bLines = @()
$bLines += "$i"
$bLines += "$i`tДатаНачала"
$bLines += (Build-MLTextXml -tag "title" -text "Начало периода" -indent "$i`t")
$bLines += "$i`t"
$bLines += (Build-ValueTypeXml -typeStr "date" -indent "$i`t`t")
$bLines += "$i`t"
$bLines += "$i`t0001-01-01T00:00:00"
$bLines += "$i`ttrue"
$bLines += "$i`t$(Esc-Xml "&$paramName.ДатаНачала")"
$bLines += "$i"
$fragments += ($bLines -join "`r`n")
$eLines = @()
$eLines += "$i"
$eLines += "$i`tДатаОкончания"
$eLines += (Build-MLTextXml -tag "title" -text "Конец периода" -indent "$i`t")
$eLines += "$i`t"
$eLines += (Build-ValueTypeXml -typeStr "date" -indent "$i`t`t")
$eLines += "$i`t"
$eLines += "$i`t0001-01-01T00:00:00"
$eLines += "$i`ttrue"
$eLines += "$i`t$(Esc-Xml "&$paramName.ДатаОкончания")"
$eLines += "$i"
$fragments += ($eLines -join "`r`n")
}
return ,$fragments
}
function Build-FilterItemFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
if ($parsed.use -eq $false) {
$lines += "$i`tfalse"
}
$lines += "$i`t$(Esc-Xml $parsed.field)"
$lines += "$i`t$(Esc-Xml $parsed.op)"
if ($null -ne $parsed.value) {
$vt = if ($parsed["valueType"]) { $parsed["valueType"] } else { "xs:string" }
$lines += "$i`t$(Esc-Xml "$($parsed.value)")"
}
if ($parsed.viewMode) {
$lines += "$i`t$(Esc-Xml $parsed.viewMode)"
}
if ($parsed.userSettingID) {
$uid = if ($parsed.userSettingID -eq "auto") { [System.Guid]::NewGuid().ToString() } else { $parsed.userSettingID }
$lines += "$i`t$(Esc-Xml $uid)"
}
$lines += "$i"
return $lines -join "`r`n"
}
function Build-SelectionItemFragment {
param([string]$fieldName, [string]$indent)
$i = $indent
$lines = @()
if ($fieldName -eq "Auto") {
$lines += "$i"
} elseif ($fieldName -match '^Folder\((.+)\)$') {
$inner = $Matches[1]
$colonIdx = $inner.IndexOf(':')
if ($colonIdx -gt 0) {
$title = $inner.Substring(0, $colonIdx).Trim()
$items = $inner.Substring($colonIdx + 1) -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }
} else {
$title = ""
$items = $inner -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }
}
$lines += "$i"
if ($title) {
$lines += "$i`t"
$lines += "$i`t`t"
$lines += "$i`t`t`tru"
$lines += "$i`t`t`t$(Esc-Xml $title)"
$lines += "$i`t`t"
$lines += "$i`t"
}
foreach ($item in $items) {
$lines += "$i`t"
$lines += "$i`t`t$(Esc-Xml $item)"
$lines += "$i`t"
}
$lines += "$i`tAuto"
$lines += "$i"
} else {
$lines += "$i"
$lines += "$i`t$(Esc-Xml $fieldName)"
$lines += "$i"
}
return $lines -join "`r`n"
}
function Build-DataParamFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
if ($parsed.use -eq $false) {
$lines += "$i`tfalse"
}
$lines += "$i`t$(Esc-Xml $parsed.parameter)"
if ($null -ne $parsed.value) {
if ($parsed.value -is [hashtable] -and $parsed.value.variant) {
$lines += "$i`t"
$lines += "$i`t`t$(Esc-Xml $parsed.value.variant)"
$lines += "$i`t`t0001-01-01T00:00:00"
$lines += "$i`t`t0001-01-01T00:00:00"
$lines += "$i`t"
} elseif ("$($parsed.value)" -match '^\d{4}-\d{2}-\d{2}T') {
$lines += "$i`t$(Esc-Xml "$($parsed.value)")"
} elseif ("$($parsed.value)" -eq "true" -or "$($parsed.value)" -eq "false") {
$lines += "$i`t$(Esc-Xml "$($parsed.value)")"
} else {
$lines += "$i`t$(Esc-Xml "$($parsed.value)")"
}
}
if ($parsed.viewMode) {
$lines += "$i`t$(Esc-Xml $parsed.viewMode)"
}
if ($parsed.userSettingID) {
$uid = if ($parsed.userSettingID -eq "auto") { [System.Guid]::NewGuid().ToString() } else { $parsed.userSettingID }
$lines += "$i`t$(Esc-Xml $uid)"
}
$lines += "$i"
return $lines -join "`r`n"
}
function Build-OrderItemFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
if ($parsed.field -eq "Auto") {
$lines += "$i"
} else {
$lines += "$i"
$lines += "$i`t$(Esc-Xml $parsed.field)"
$lines += "$i`t$($parsed.direction)"
$lines += "$i"
}
return $lines -join "`r`n"
}
function Build-DataSetLinkFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
$lines += "$i`t$(Esc-Xml $parsed.source)"
$lines += "$i`t$(Esc-Xml $parsed.dest)"
$lines += "$i`t$(Esc-Xml $parsed.sourceExpr)"
$lines += "$i`t$(Esc-Xml $parsed.destExpr)"
if ($parsed.parameter) {
$lines += "$i`t$(Esc-Xml $parsed.parameter)"
}
$lines += "$i"
return $lines -join "`r`n"
}
function Build-DataSetQueryFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
$lines += "$i`t$(Esc-Xml $parsed.name)"
$lines += "$i`t$(Esc-Xml $parsed.dataSource)"
$lines += "$i`t$(Esc-Xml $parsed.query)"
$lines += "$i"
return $lines -join "`r`n"
}
function Build-VariantFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
$lines += "$i`t$(Esc-Xml $parsed.name)"
$lines += (Build-MLTextXml -tag "dcsset:presentation" -text $parsed.presentation -indent "$i`t")
$lines += "$i`t"
$lines += "$i`t`t"
$lines += "$i`t`t`t"
$lines += "$i`t`t"
$lines += "$i`t`t"
$lines += "$i`t`t`t"
$lines += "$i`t`t`t"
$lines += "$i`t`t`t`t"
$lines += "$i`t`t`t"
$lines += "$i`t`t`t"
$lines += "$i`t`t`t`t"
$lines += "$i`t`t`t"
$lines += "$i`t`t"
$lines += "$i`t"
$lines += "$i"
return $lines -join "`r`n"
}
function Emit-FilterComparison {
param($f, [string]$indent)
$lines = @()
$lines += "$indent"
$lines += "$indent`t$(Esc-Xml $f.field)"
$lines += "$indent`t$(Esc-Xml $f.op)"
if ($null -ne $f.value) {
$vt = if ($f["valueType"]) { $f["valueType"] } else { "xs:string" }
$lines += "$indent`t$(Esc-Xml "$($f.value)")"
}
$lines += "$indent"
return $lines
}
function Build-ConditionalAppearanceItemFragment {
param($parsed, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
# selection
if ($parsed.fields -and $parsed.fields.Count -gt 0) {
$lines += "$i`t"
foreach ($fld in $parsed.fields) {
$lines += "$i`t`t"
$lines += "$i`t`t`t$(Esc-Xml $fld)"
$lines += "$i`t`t"
}
$lines += "$i`t"
} else {
$lines += "$i`t"
}
# filter
if ($parsed.filter) {
$lines += "$i`t"
if ($parsed.filter -is [array]) {
# OrGroup
$lines += "$i`t`t"
$lines += "$i`t`t`tOrGroup"
foreach ($f in $parsed.filter) {
$lines += Emit-FilterComparison $f "$i`t`t`t"
}
$lines += "$i`t`t"
} else {
$lines += Emit-FilterComparison $parsed.filter "$i`t`t"
}
$lines += "$i`t"
} else {
$lines += "$i`t"
}
# appearance
$lines += "$i`t"
$val = $parsed.value
$lines += "$i`t`t"
$lines += "$i`t`t`t$(Esc-Xml $parsed.param)"
if ($val -match '^(web|style|win):') {
$lines += "$i`t`t`t$(Esc-Xml $val)"
} elseif ($val -eq "true" -or $val -eq "false") {
$lines += "$i`t`t`t$(Esc-Xml $val)"
} elseif ($parsed.param -eq "Формат" -or $parsed.param -eq "Текст" -or $parsed.param -eq "Заголовок") {
$lines += "$i`t`t`t"
$lines += "$i`t`t`t`t"
$lines += "$i`t`t`t`t`tru"
$lines += "$i`t`t`t`t`t$(Esc-Xml $val)"
$lines += "$i`t`t`t`t"
$lines += "$i`t`t`t"
} else {
$lines += "$i`t`t`t$(Esc-Xml $val)"
}
$lines += "$i`t`t"
$lines += "$i`t"
$lines += "$i"
return $lines -join "`r`n"
}
function Build-StructureItemFragment {
param($item, [string]$indent)
$i = $indent
$lines = @()
$lines += "$i"
# name
if ($item["name"]) {
$lines += "$i`t$(Esc-Xml $item["name"])"
}
# groupItems
$groupBy = $item["groupBy"]
if (-not $groupBy -or $groupBy.Count -eq 0) {
$lines += "$i`t"
} else {
$lines += "$i`t"
foreach ($field in $groupBy) {
$lines += "$i`t`t"
$lines += "$i`t`t`t$(Esc-Xml $field)"
$lines += "$i`t`t`tItems"
$lines += "$i`t`t`tNone"
$lines += "$i`t`t`t0001-01-01T00:00:00"
$lines += "$i`t`t`t0001-01-01T00:00:00"
$lines += "$i`t`t"
}
$lines += "$i`t"
}
# order (Auto)
$lines += "$i`t"
$lines += "$i`t`t"
$lines += "$i`t"
# selection (Auto)
$lines += "$i`t"
$lines += "$i`t`t"
$lines += "$i`t"
# Recursive children
if ($item["children"]) {
foreach ($child in $item["children"]) {
$childXml = Build-StructureItemFragment -item $child -indent "$i`t"
$lines += $childXml
}
}
$lines += "$i"
return $lines -join "`r`n"
}
function Build-OutputParamFragment {
param($parsed, [string]$indent)
$i = $indent
$key = $parsed.key
$val = $parsed.value
$ptype = $script:outputParamTypes[$key]
if (-not $ptype) { $ptype = "xs:string" }
$lines = @()
$lines += "$i"
$lines += "$i`t$(Esc-Xml $key)"
if ($ptype -eq "mltext") {
$lines += "$i`t"
$lines += "$i`t`t"
$lines += "$i`t`t`tru"
$lines += "$i`t`t`t$(Esc-Xml $val)"
$lines += "$i`t`t"
$lines += "$i`t"
} else {
$lines += "$i`t$(Esc-Xml $val)"
}
$lines += "$i"
return $lines -join "`r`n"
}
# --- 5. XML helpers ---
function Import-Fragment($doc, [string]$xmlString) {
$wrapper = @"
<_W xmlns="http://v8.1c.ru/8.1/data-composition-system/schema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:v8="http://v8.1c.ru/8.1/data/core"
xmlns:dcscom="http://v8.1c.ru/8.1/data-composition-system/common"
xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core"
xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings"
xmlns:v8ui="http://v8.1c.ru/8.1/data/ui">$xmlString
"@
$frag = New-Object System.Xml.XmlDocument
$frag.PreserveWhitespace = $true
$frag.LoadXml($wrapper)
$nodes = @()
foreach ($child in $frag.DocumentElement.ChildNodes) {
if ($child.NodeType -eq 'Element') {
$nodes += $doc.ImportNode($child, $true)
}
}
return ,$nodes
}
function Get-ChildIndent($container) {
foreach ($child in $container.ChildNodes) {
if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
$text = $child.Value
if ($text -match '^\r?\n(\t+)$') { return $Matches[1] }
if ($text -match '^\r?\n(\t+)') { return $Matches[1] }
}
}
$depth = 0
$current = $container
while ($current -and $current -ne $xmlDoc.DocumentElement) {
$depth++
$current = $current.ParentNode
}
return "`t" * ($depth + 1)
}
function Insert-BeforeElement($container, $newNode, $refNode, $childIndent) {
$ws = $xmlDoc.CreateWhitespace("`r`n$childIndent")
if ($refNode) {
$container.InsertBefore($ws, $refNode) | Out-Null
$container.InsertBefore($newNode, $ws) | Out-Null
} else {
$trailing = $container.LastChild
if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
$container.InsertBefore($ws, $trailing) | Out-Null
$container.InsertBefore($newNode, $trailing) | Out-Null
} else {
$container.AppendChild($ws) | Out-Null
$container.AppendChild($newNode) | Out-Null
$parentIndent = if ($childIndent.Length -gt 1) { $childIndent.Substring(0, $childIndent.Length - 1) } else { "" }
$closeWs = $xmlDoc.CreateWhitespace("`r`n$parentIndent")
$container.AppendChild($closeWs) | Out-Null
}
}
}
function Clear-ContainerChildren($container) {
$toRemove = @()
foreach ($child in $container.ChildNodes) {
if ($child.NodeType -eq 'Element') {
$toRemove += $child
}
}
foreach ($el in $toRemove) {
Remove-NodeWithWhitespace $el
}
}
function Remove-NodeWithWhitespace($node) {
$parent = $node.ParentNode
$prev = $node.PreviousSibling
$next = $node.NextSibling
if ($prev -and ($prev.NodeType -eq 'Whitespace' -or $prev.NodeType -eq 'SignificantWhitespace')) {
$parent.RemoveChild($prev) | Out-Null
} elseif ($next -and ($next.NodeType -eq 'Whitespace' -or $next.NodeType -eq 'SignificantWhitespace')) {
$parent.RemoveChild($next) | Out-Null
}
$parent.RemoveChild($node) | Out-Null
}
function Find-FirstElement($container, [string[]]$localNames, [string]$nsUri) {
foreach ($child in $container.ChildNodes) {
if ($child.NodeType -eq 'Element') {
foreach ($name in $localNames) {
if ($child.LocalName -eq $name) {
if (-not $nsUri -or $child.NamespaceURI -eq $nsUri) {
return $child
}
}
}
}
}
return $null
}
function Find-LastElement($container, [string]$localName, [string]$nsUri) {
$last = $null
foreach ($child in $container.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $localName) {
if (-not $nsUri -or $child.NamespaceURI -eq $nsUri) {
$last = $child
}
}
}
return $last
}
function Find-ElementByChildValue($container, [string]$elemName, [string]$childName, [string]$childValue, [string]$nsUri) {
foreach ($child in $container.ChildNodes) {
if ($child.NodeType -ne 'Element') { continue }
if ($child.LocalName -ne $elemName) { continue }
if ($nsUri -and $child.NamespaceURI -ne $nsUri) { continue }
foreach ($gc in $child.ChildNodes) {
if ($gc.NodeType -eq 'Element' -and $gc.LocalName -eq $childName -and $gc.InnerText.Trim() -eq $childValue) {
return $child
}
}
}
return $null
}
function Set-OrCreateChildElement($parent, [string]$localName, [string]$nsUri, [string]$value, [string]$indent) {
$existing = $null
foreach ($ch in $parent.ChildNodes) {
if ($ch.NodeType -eq 'Element' -and $ch.LocalName -eq $localName -and $ch.NamespaceURI -eq $nsUri) {
$existing = $ch
break
}
}
if ($existing) {
$existing.InnerText = $value
} else {
$prefix = $parent.GetPrefixOfNamespace($nsUri)
$qualName = if ($prefix) { "${prefix}:$localName" } else { $localName }
$fragXml = "$indent<$qualName>$(Esc-Xml $value)$qualName>"
$nodes = Import-Fragment $xmlDoc $fragXml
foreach ($node in $nodes) {
Insert-BeforeElement $parent $node $null $indent
}
}
}
function Set-OrCreateChildElementWithAttr($parent, [string]$localName, [string]$nsUri, [string]$value, [string]$xsiType, [string]$indent) {
$existing = $null
foreach ($ch in $parent.ChildNodes) {
if ($ch.NodeType -eq 'Element' -and $ch.LocalName -eq $localName -and $ch.NamespaceURI -eq $nsUri) {
$existing = $ch
break
}
}
if ($existing) {
$existing.InnerText = $value
if ($xsiType) {
$existing.SetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance", $xsiType) | Out-Null
}
} else {
$prefix = $parent.GetPrefixOfNamespace($nsUri)
$qualName = if ($prefix) { "${prefix}:$localName" } else { $localName }
$typeAttr = if ($xsiType) { " xsi:type=`"$xsiType`"" } else { "" }
$fragXml = "$indent<$qualName$typeAttr>$(Esc-Xml $value)$qualName>"
$nodes = Import-Fragment $xmlDoc $fragXml
foreach ($node in $nodes) {
Insert-BeforeElement $parent $node $null $indent
}
}
}
function Resolve-DataSet {
$schNs = "http://v8.1c.ru/8.1/data-composition-system/schema"
$root = $xmlDoc.DocumentElement
if ($DataSet) {
foreach ($child in $root.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq 'dataSet' -and $child.NamespaceURI -eq $schNs) {
$nameEl = $null
foreach ($gc in $child.ChildNodes) {
if ($gc.NodeType -eq 'Element' -and $gc.LocalName -eq 'name' -and $gc.NamespaceURI -eq $schNs) {
$nameEl = $gc
break
}
}
if ($nameEl -and $nameEl.InnerText -eq $DataSet) {
return $child
}
}
}
Write-Error "DataSet '$DataSet' not found"
exit 1
}
foreach ($child in $root.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq 'dataSet' -and $child.NamespaceURI -eq $schNs) {
return $child
}
}
Write-Error "No dataSet found in DCS"
exit 1
}
function Resolve-VariantSettings {
$schNs = "http://v8.1c.ru/8.1/data-composition-system/schema"
$setNs = "http://v8.1c.ru/8.1/data-composition-system/settings"
$root = $xmlDoc.DocumentElement
$sv = $null
if ($Variant) {
foreach ($child in $root.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq 'settingsVariant' -and $child.NamespaceURI -eq $schNs) {
$nameEl = $null
foreach ($gc in $child.ChildNodes) {
if ($gc.NodeType -eq 'Element' -and $gc.LocalName -eq 'name' -and $gc.NamespaceURI -eq $setNs) {
$nameEl = $gc
break
}
}
if ($nameEl -and $nameEl.InnerText -eq $Variant) {
$sv = $child
break
}
}
}
if (-not $sv) {
Write-Error "Variant '$Variant' not found"
exit 1
}
} else {
foreach ($child in $root.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq 'settingsVariant' -and $child.NamespaceURI -eq $schNs) {
$sv = $child
break
}
}
if (-not $sv) {
Write-Error "No settingsVariant found in DCS"
exit 1
}
}
foreach ($gc in $sv.ChildNodes) {
if ($gc.NodeType -eq 'Element' -and $gc.LocalName -eq 'settings' -and $gc.NamespaceURI -eq $setNs) {
return $gc
}
}
Write-Error "No found in variant"
exit 1
}
function Ensure-SettingsChild($settings, [string]$childName, [string[]]$afterSiblings) {
$el = Find-FirstElement $settings @($childName) $setNs
if ($el) { return $el }
$indent = Get-ChildIndent $settings
$fragXml = "$indent"
$nodes = Import-Fragment $xmlDoc $fragXml
$refNode = $null
foreach ($sibName in $afterSiblings) {
$sib = Find-FirstElement $settings @($sibName) $setNs
if ($sib) {
$refNode = $sib.NextSibling
while ($refNode -and ($refNode.NodeType -eq 'Whitespace' -or $refNode.NodeType -eq 'SignificantWhitespace')) {
$refNode = $refNode.NextSibling
}
break
}
}
foreach ($node in $nodes) {
Insert-BeforeElement $settings $node $refNode $indent
}
return Find-FirstElement $settings @($childName) $setNs
}
function Get-VariantName {
$schNs = "http://v8.1c.ru/8.1/data-composition-system/schema"
$setNs = "http://v8.1c.ru/8.1/data-composition-system/settings"
$root = $xmlDoc.DocumentElement
if ($Variant) { return $Variant }
foreach ($child in $root.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq 'settingsVariant' -and $child.NamespaceURI -eq $schNs) {
foreach ($gc in $child.ChildNodes) {
if ($gc.NodeType -eq 'Element' -and $gc.LocalName -eq 'name' -and $gc.NamespaceURI -eq $setNs) {
return $gc.InnerText
}
}
}
}
return "(unknown)"
}
function Get-DataSetName($dsNode) {
$schNs = "http://v8.1c.ru/8.1/data-composition-system/schema"
foreach ($gc in $dsNode.ChildNodes) {
if ($gc.NodeType -eq 'Element' -and $gc.LocalName -eq 'name' -and $gc.NamespaceURI -eq $schNs) {
return $gc.InnerText
}
}
return "(unknown)"
}
function Get-ContainerChildIndent($container) {
$hasElements = $false
foreach ($ch in $container.ChildNodes) {
if ($ch.NodeType -eq 'Element') { $hasElements = $true; break }
}
if ($hasElements) {
return Get-ChildIndent $container
} else {
$parentIndent = Get-ChildIndent $container.ParentNode
return $parentIndent + "`t"
}
}
# --- 6. Load XML ---
$xmlDoc = New-Object System.Xml.XmlDocument
$xmlDoc.PreserveWhitespace = $true
$xmlDoc.Load($resolvedPath)
$schNs = "http://v8.1c.ru/8.1/data-composition-system/schema"
$setNs = "http://v8.1c.ru/8.1/data-composition-system/settings"
$corNs = "http://v8.1c.ru/8.1/data-composition-system/core"
# --- 7. Batch value splitting ---
if ($Operation -eq "set-query" -or $Operation -eq "set-structure" -or $Operation -eq "modify-structure" -or $Operation -eq "add-dataSet") {
$values = @($Value)
} elseif ($Operation -eq "patch-query") {
$values = @($Value -split ';;' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
} elseif ($Operation -eq "add-drilldown") {
if ($Value.Contains(';;')) {
$values = @($Value -split ';;' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
} else {
$values = @($Value -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
}
} else {
$values = @($Value -split ';;' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
}
# --- 8. Main logic ---
switch ($Operation) {
"add-field" {
$dsNode = Resolve-DataSet
$dsName = Get-DataSetName $dsNode
foreach ($val in $values) {
$parsed = Parse-FieldShorthand $val
$childIndent = Get-ChildIndent $dsNode
# Duplicate check
$existing = Find-ElementByChildValue $dsNode "field" "dataPath" $parsed.dataPath $schNs
if ($existing) {
Write-Host "[WARN] Field `"$($parsed.dataPath)`" already exists in dataset `"$dsName`" — skipped"
continue
}
$fragXml = Build-FieldFragment -parsed $parsed -indent $childIndent
$nodes = Import-Fragment $xmlDoc $fragXml
$refNode = Find-FirstElement $dsNode @("dataSource") $schNs
foreach ($node in $nodes) {
Insert-BeforeElement $dsNode $node $refNode $childIndent
}
Write-Host "[OK] Field `"$($parsed.dataPath)`" added to dataset `"$dsName`""
if (-not $NoSelection) {
$settings = Resolve-VariantSettings
$varName = Get-VariantName
$selection = Ensure-SettingsChild $settings "selection" @()
$existingSel = Find-ElementByChildValue $selection "item" "field" $parsed.dataPath $setNs
if ($existingSel) {
Write-Host "[INFO] Field `"$($parsed.dataPath)`" already in selection — skipped"
} else {
$selIndent = Get-ContainerChildIndent $selection
$selXml = Build-SelectionItemFragment -fieldName $parsed.dataPath -indent $selIndent
$selNodes = Import-Fragment $xmlDoc $selXml
foreach ($node in $selNodes) {
Insert-BeforeElement $selection $node $null $selIndent
}
Write-Host "[OK] Field `"$($parsed.dataPath)`" added to selection of variant `"$varName`""
}
}
}
}
"add-total" {
foreach ($val in $values) {
$parsed = Parse-TotalShorthand $val
$childIndent = Get-ChildIndent $xmlDoc.DocumentElement
# Duplicate check
$existing = Find-ElementByChildValue $xmlDoc.DocumentElement "totalField" "dataPath" $parsed.dataPath $schNs
if ($existing) {
Write-Host "[WARN] TotalField `"$($parsed.dataPath)`" already exists — skipped"
continue
}
$fragXml = Build-TotalFragment -parsed $parsed -indent $childIndent
$nodes = Import-Fragment $xmlDoc $fragXml
$root = $xmlDoc.DocumentElement
$lastTotal = Find-LastElement $root "totalField" $schNs
if ($lastTotal) {
$refNode = $lastTotal.NextSibling
while ($refNode -and ($refNode.NodeType -eq 'Whitespace' -or $refNode.NodeType -eq 'SignificantWhitespace')) {
$refNode = $refNode.NextSibling
}
} else {
$refNode = Find-FirstElement $root @("parameter","template","groupTemplate","settingsVariant") $schNs
}
foreach ($node in $nodes) {
Insert-BeforeElement $root $node $refNode $childIndent
}
Write-Host "[OK] TotalField `"$($parsed.dataPath)`" = $($parsed.expression) added"
}
}
"add-calculated-field" {
foreach ($val in $values) {
$parsed = Parse-CalcShorthand $val
$childIndent = Get-ChildIndent $xmlDoc.DocumentElement
# Duplicate check
$existing = Find-ElementByChildValue $xmlDoc.DocumentElement "calculatedField" "dataPath" $parsed.dataPath $schNs
if ($existing) {
Write-Host "[WARN] CalculatedField `"$($parsed.dataPath)`" already exists — skipped"
continue
}
$fragXml = Build-CalcFieldFragment -parsed $parsed -indent $childIndent
$nodes = Import-Fragment $xmlDoc $fragXml
$root = $xmlDoc.DocumentElement
$lastCalc = Find-LastElement $root "calculatedField" $schNs
if ($lastCalc) {
$refNode = $lastCalc.NextSibling
while ($refNode -and ($refNode.NodeType -eq 'Whitespace' -or $refNode.NodeType -eq 'SignificantWhitespace')) {
$refNode = $refNode.NextSibling
}
} else {
$refNode = Find-FirstElement $root @("totalField","parameter","template","groupTemplate","settingsVariant") $schNs
}
foreach ($node in $nodes) {
Insert-BeforeElement $root $node $refNode $childIndent
}
Write-Host "[OK] CalculatedField `"$($parsed.dataPath)`" = $($parsed.expression) added"
if (-not $NoSelection) {
$settings = Resolve-VariantSettings
$varName = Get-VariantName
$selection = Ensure-SettingsChild $settings "selection" @()
$existingSel = Find-ElementByChildValue $selection "item" "field" $parsed.dataPath $setNs
if ($existingSel) {
Write-Host "[INFO] Field `"$($parsed.dataPath)`" already in selection — skipped"
} else {
$selIndent = Get-ContainerChildIndent $selection
$selXml = Build-SelectionItemFragment -fieldName $parsed.dataPath -indent $selIndent
$selNodes = Import-Fragment $xmlDoc $selXml
foreach ($node in $selNodes) {
Insert-BeforeElement $selection $node $null $selIndent
}
Write-Host "[OK] Field `"$($parsed.dataPath)`" added to selection of variant `"$varName`""
}
}
}
}
"add-parameter" {
foreach ($val in $values) {
$parsed = Parse-ParamShorthand $val
$childIndent = Get-ChildIndent $xmlDoc.DocumentElement
# Duplicate check
$existing = Find-ElementByChildValue $xmlDoc.DocumentElement "parameter" "name" $parsed.name $schNs
if ($existing) {
Write-Host "[WARN] Parameter `"$($parsed.name)`" already exists — skipped"
continue
}
$fragments = Build-ParamFragment -parsed $parsed -indent $childIndent
$root = $xmlDoc.DocumentElement
$lastParam = Find-LastElement $root "parameter" $schNs
if ($lastParam) {
$refNode = $lastParam.NextSibling
while ($refNode -and ($refNode.NodeType -eq 'Whitespace' -or $refNode.NodeType -eq 'SignificantWhitespace')) {
$refNode = $refNode.NextSibling
}
} else {
$refNode = Find-FirstElement $root @("template","groupTemplate","settingsVariant") $schNs
}
foreach ($fragXml in $fragments) {
$nodes = Import-Fragment $xmlDoc $fragXml
foreach ($node in $nodes) {
Insert-BeforeElement $root $node $refNode $childIndent
}
}
Write-Host "[OK] Parameter `"$($parsed.name)`" added"
if ($parsed.autoDates) {
Write-Host "[OK] Auto-parameters `"ДатаНачала`", `"ДатаОкончания`" added"
}
}
}
"modify-parameter" {
foreach ($val in $values) {
# Parse: "ParamName [Title] key=value key=value"
# Extract optional [Title] first (mirrors Parse-FieldShorthand)
$titleVal = $null
if ($val -match '\[([^\]]*)\]') {
$titleVal = $Matches[1].Trim()
$val = ($val -replace '\s*\[[^\]]*\]\s*', ' ').Trim()
}
$parts = $val -split '\s+', 2
$paramName = $parts[0].Trim()
$rest = if ($parts.Count -gt 1) { $parts[1].Trim() } else { "" }
# Extract @hidden / @always flags
$flagHidden = $false
$flagAlways = $false
if ($rest -match '@hidden\b') { $flagHidden = $true; $rest = ($rest -replace '\s*@hidden\b', '').Trim() }
if ($rest -match '@always\b') { $flagAlways = $true; $rest = ($rest -replace '\s*@always\b', '').Trim() }
# Find parameter element
$paramEl = Find-ElementByChildValue $xmlDoc.DocumentElement "parameter" "name" $paramName $schNs
if (-not $paramEl) {
Write-Host "[WARN] Parameter `"$paramName`" not found — skipped"
continue
}
$childIndent = Get-ChildIndent $paramEl
# Set/replace title (must come right after , before )
if ($null -ne $titleVal) {
$existingTitle = $null
foreach ($ch in $paramEl.ChildNodes) {
if ($ch.NodeType -eq 'Element' -and $ch.LocalName -eq 'title') {
$existingTitle = $ch; break
}
}
if ($existingTitle) {
Remove-NodeWithWhitespace $existingTitle
}
# Insert before first of (valueType, value, useRestriction, expression, availableAsField, ...)
$titleRef = $null
foreach ($ch in $paramEl.ChildNodes) {
if ($ch.NodeType -eq 'Element' -and $ch.LocalName -ne 'name') {
$titleRef = $ch; break
}
}
$titleFrag = Build-MLTextXml -tag "title" -text $titleVal -indent $childIndent
$titleNodes = Import-Fragment $xmlDoc $titleFrag
foreach ($node in $titleNodes) {
Insert-BeforeElement $paramEl $node $titleRef $childIndent
}
Write-Host "[OK] Parameter `"$paramName`": title set to `"$titleVal`""
}
# Separate availableValue=... from simple kv pairs
$simpleRest = $rest
$avPart = $null
$avIdx = $rest.IndexOf('availableValue=')
if ($avIdx -ge 0) {
$simpleRest = $rest.Substring(0, $avIdx).Trim()
$avPart = $rest.Substring($avIdx)
}
# Process simple key=value pairs (use, denyIncompleteValues, value, etc.)
if ($simpleRest) {
$kvPairs = [regex]::Matches($simpleRest, '(\w+)=(\S+)')
foreach ($kv in $kvPairs) {
$key = $kv.Groups[1].Value
$value = $kv.Groups[2].Value
# Namespace-aware lookup (children live in $schNs)
$existing = $null
foreach ($ch in $paramEl.ChildNodes) {
if ($ch.NodeType -eq 'Element' -and $ch.LocalName -eq $key -and $ch.NamespaceURI -eq $schNs) {
$existing = $ch; break
}
}
if ($key -eq "value") {
# Special-case: rebuild with correct xsi:type from
$declaredType = ""
$vtEl = $null
foreach ($ch in $paramEl.ChildNodes) {
if ($ch.NodeType -eq 'Element' -and $ch.LocalName -eq 'valueType' -and $ch.NamespaceURI -eq $schNs) { $vtEl = $ch; break }
}
if ($vtEl) {
foreach ($tnode in $vtEl.ChildNodes) {
if ($tnode.NodeType -eq 'Element' -and $tnode.LocalName -eq 'Type') {
$declaredType = $tnode.InnerText.Trim() -replace '^d\d+p\d+:', ''
break
}
}
}
$valueLines = Build-ParamValueXml -type $declaredType -value $value -indent $childIndent
$fragXml = $valueLines -join "`r`n"
$wasExisting = ($null -ne $existing)
if ($existing) {
# Capture position by next-element sibling, then remove existing
$refNode = $existing.NextSibling
while ($refNode -and ($refNode.NodeType -eq 'Whitespace' -or $refNode.NodeType -eq 'SignificantWhitespace')) {
$refNode = $refNode.NextSibling
}
Remove-NodeWithWhitespace $existing
} else {
# Insert before useRestriction/availableValue/denyIncompleteValues/use
$refNode = $null
foreach ($child in $paramEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -in @('useRestriction','availableValue','denyIncompleteValues','use')) {
$refNode = $child; break
}
}
}
$nodes = Import-Fragment $xmlDoc $fragXml
foreach ($node in $nodes) {
Insert-BeforeElement $paramEl $node $refNode $childIndent
}
$verb = if ($wasExisting) { "updated" } else { "added" }
Write-Host "[OK] Parameter `"$paramName`": value $verb to $value"
} elseif ($existing) {
$existing.InnerText = $value
Write-Host "[OK] Parameter `"$paramName`": $key updated to $value"
} else {
# Schema order: ...value, useRestriction, availableValue*, denyIncompleteValues, use
$refNode = $null
if ($key -eq "denyIncompleteValues") {
foreach ($child in $paramEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq 'use') {
$refNode = $child; break
}
}
}
$fragXml = "$childIndent<$key>$(Esc-Xml $value)$key>"
$nodes = Import-Fragment $xmlDoc $fragXml
foreach ($node in $nodes) {
Insert-BeforeElement $paramEl $node $refNode $childIndent
}
Write-Host "[OK] Parameter `"$paramName`": $key=$value added"
}
}
}
# Process availableValue — replace whole list with new items
if ($avPart) {
$avRest = ($avPart -replace '^availableValue=', '').Trim()
$avItems = Parse-AvailableValueList $avRest
# Detect value type: prefer declared of the parameter, else guess from value
$declaredType = ""
$vtEl = $null
foreach ($ch in $paramEl.ChildNodes) {
if ($ch.NodeType -eq 'Element' -and $ch.LocalName -eq 'valueType' -and $ch.NamespaceURI -eq $schNs) { $vtEl = $ch; break }
}
if ($vtEl) {
foreach ($tnode in $vtEl.ChildNodes) {
if ($tnode.NodeType -eq 'Element' -and $tnode.LocalName -eq 'Type') {
$declaredType = $tnode.InnerText.Trim() -replace '^d\d+p\d+:', ''
break
}
}
}
# Remove all existing elements
$toRemove = @()
foreach ($ch in $paramEl.ChildNodes) {
if ($ch.NodeType -eq 'Element' -and $ch.LocalName -eq 'availableValue' -and $ch.NamespaceURI -eq $schNs) {
$toRemove += $ch
}
}
foreach ($el in $toRemove) { Remove-NodeWithWhitespace $el }
# Insert each new before (denyIncompleteValues, use)
$refNode = $null
foreach ($child in $paramEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and ($child.LocalName -eq 'denyIncompleteValues' -or $child.LocalName -eq 'use')) {
$refNode = $child; break
}
}
foreach ($av in $avItems) {
$avLines = Build-AvailableValueFragment -item $av -declaredType $declaredType -indent $childIndent
$fragXml = $avLines -join "`r`n"
$nodes = Import-Fragment $xmlDoc $fragXml
foreach ($node in $nodes) {
Insert-BeforeElement $paramEl $node $refNode $childIndent
}
}
Write-Host "[OK] Parameter `"$paramName`": availableValue set to $($avItems.Count) item(s)"
}
# Process @hidden / @always flags (idempotent)
if ($flagHidden) {
# useRestriction → true (insert after , before //...)
$urEl = $null
foreach ($ch in $paramEl.ChildNodes) {
if ($ch.NodeType -eq 'Element' -and $ch.LocalName -eq 'useRestriction' -and $ch.NamespaceURI -eq $schNs) { $urEl = $ch; break }
}
if ($urEl) {
if ($urEl.InnerText.Trim() -ne 'true') { $urEl.InnerText = 'true' }
} else {
$refNode = $null
foreach ($child in $paramEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -in @('expression','availableAsField','availableValue','denyIncompleteValues','use')) { $refNode = $child; break }
}
$nodes = Import-Fragment $xmlDoc "$childIndenttrue"
foreach ($node in $nodes) { Insert-BeforeElement $paramEl $node $refNode $childIndent }
}
# availableAsField → false (insert after , before //