# 会话与命令

用脚本读取选区与内容、修改幻灯片，并让修改进入撤销历史。

会话上的命令和界面操作走同一条编辑路径：每次调用是一步可撤销的编辑，界面立刻更新。会话的取得方式见[打开与保存](/pptx/files)。

## 调用命令

```ts
const added = session.commands.addSlide({ after: 0, title: '第二页', body: '要点' })
```

每个命令接受一个选项对象，返回是否生效。不适用时返回 `false`，演示文稿不变，例如指定的幻灯片或形状不存在。

多步修改用 `chain()` 合成一步撤销；其中任何一步不适用，整组都不保留：

```ts
session.chain()
  .addSlide({ after: 1, title: '第三页' })
  .addSlide({ after: 2, title: '第四页' })
  .run()

await session.undo()   // 一次撤销整组
await session.redo()
```

## 定位幻灯片与形状

命令用幻灯片部件名（如 `/ppt/slides/slide3.xml`）和形状 id 指向对象，幻灯片移动后仍然有效。

用户选中的形状从 `selection()` 取得：

```ts
for (const shape of session.selection()) {
  session.commands.setShapeFill({ slide: shape.slide, shapes: [shape.shape], color: '#2F6FED' })
}
```

要遍历全部幻灯片，用 MIT 包 `@quirekit/office-kit-pptx` 读取当前内容：

```ts
import { getShapeId, getShapeName, getShapeText, getSlidePartName, getSlides, getSlideShapes, loadPresentation } from '@quirekit/office-kit-pptx'

const deck = await loadPresentation(await session.snapshot())
for (const slide of getSlides(deck)) {
  const part = getSlidePartName(slide)
  for (const shape of getSlideShapes(slide)) console.log(part, getShapeId(shape), getShapeName(shape), getShapeText(shape))
}
```

## 单位

位置和尺寸以 EMU 为单位：1 英寸 = 914400，1 厘米 = 360000，1 磅 = 12700。16:9 幻灯片默认宽 12192000、高 6858000。字号以磅为单位，颜色写成 `#RRGGBB`。

## 常用命令

| 用途 | 命令 |
| --- | --- |
| 幻灯片 | `addSlide`、`duplicateSlide`、`moveSlide`、`deleteSlide`、`setSlideHidden`、`setSlideNotes`、`setSlideLayout`、`setSlideBackground` |
| 文字 | `setShapeText`、`replaceShapeText`、`setTextFormat`、`setTextAlignment`、`setTextAnchor`、`setParagraphBullets`、`setLineSpacing` |
| 插入 | `addTextBox`、`addShape`、`addPicture`、`addTable`、`addChart`、`addMedia`、`addEquation`、`addFreeform` |
| 形状 | `setShapeBounds`、`moveShapes`、`setShapeFill`、`setShapeOutline`、`rotateShapes`、`flipShapes`、`deleteShape`、`duplicateShapes` |
| 排列 | `arrangeShapes`、`alignShapes`、`distributeShapes`、`groupShapes`、`ungroupShapes` |
| 表格与图表 | `setTableCellText`、`setTableStyle`、`setChartData` |
| 切换与动画 | `setSlideTransition`、`addShapeAnimation`、`updateAnimation`、`removeAnimation`、`moveAnimation` |
| 链接 | `setShapeLink` |

完整的命令名和每个命令的选项以类型为准：在编辑器中输入 `session.commands.` 即可看到全部命令及其说明。

```ts
session.commands.addTextBox({
  slide: '/ppt/slides/slide1.xml',
  text: '第三季度销售额 2.1 亿元',
  x: 914400, y: 4572000, width: 6096000, height: 685800,
})
```
