@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +28 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,621 @@
1
+ """
2
+ Google Docs Document Structure Parsing and Analysis
3
+
4
+ This module provides utilities for parsing and analyzing the structure
5
+ of Google Docs documents, including finding tables, cells, and other elements.
6
+ """
7
+
8
+ import logging
9
+ from collections.abc import Iterator
10
+ from typing import Any, Optional
11
+
12
+ from core.utils import UserInputError
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # Limit returned ranges; the count remains exact.
17
+ EMPTY_PARAGRAPH_RANGE_LIMIT = 100
18
+ HEADING_LIST_LIMIT = 50
19
+
20
+
21
+ def truncate_preview(text: str, preview_chars: Optional[int]) -> str:
22
+ """Truncate preview text; None or a non-positive limit disables truncation."""
23
+ return (
24
+ text[:preview_chars]
25
+ if preview_chars is not None and preview_chars > 0
26
+ else text
27
+ )
28
+
29
+
30
+ def parse_document_structure(
31
+ doc_data: dict[str, Any], preview_chars: Optional[int] = 100
32
+ ) -> dict[str, Any]:
33
+ """
34
+ Parse the full document structure into a navigable format.
35
+
36
+ Args:
37
+ doc_data: Raw document data from Google Docs API
38
+ preview_chars: Maximum characters of header/footer text preview.
39
+ None, zero or negative means no truncation.
40
+
41
+ Returns:
42
+ Dictionary containing parsed structure with elements and their positions
43
+ """
44
+ structure = {
45
+ "title": doc_data.get("title", ""),
46
+ "body": [],
47
+ "tables": [],
48
+ "section_breaks": [],
49
+ "headers": {},
50
+ "footers": {},
51
+ "named_ranges": {},
52
+ "total_length": 0,
53
+ }
54
+
55
+ body = doc_data.get("body", {})
56
+ content = body.get("content", [])
57
+
58
+ for element in content:
59
+ element_info = _parse_element(element)
60
+ if element_info:
61
+ structure["body"].append(element_info)
62
+ if element_info["type"] == "table":
63
+ structure["tables"].append(element_info)
64
+ elif element_info["type"] == "section_break":
65
+ structure["section_breaks"].append(element_info)
66
+
67
+ # Calculate total document length
68
+ if structure["body"]:
69
+ last_element = structure["body"][-1]
70
+ structure["total_length"] = last_element.get("end_index", 0)
71
+
72
+ # Parse headers and footers
73
+ for header_id, header_data in doc_data.get("headers", {}).items():
74
+ structure["headers"][header_id] = _parse_segment(header_data, preview_chars)
75
+
76
+ for footer_id, footer_data in doc_data.get("footers", {}).items():
77
+ structure["footers"][footer_id] = _parse_segment(footer_data, preview_chars)
78
+
79
+ for range_name, named_ranges in doc_data.get("namedRanges", {}).items():
80
+ ranges = []
81
+ for named_range in named_ranges.get("namedRanges", []):
82
+ for named_range_range in named_range.get("ranges", []):
83
+ ranges.append(
84
+ {
85
+ "named_range_id": named_range.get("namedRangeId"),
86
+ "start_index": named_range_range.get("startIndex"),
87
+ "end_index": named_range_range.get("endIndex"),
88
+ "segment_id": named_range_range.get("segmentId"),
89
+ "tab_id": named_range_range.get("tabId"),
90
+ }
91
+ )
92
+ structure["named_ranges"][range_name] = ranges
93
+
94
+ return structure
95
+
96
+
97
+ def _parse_element(element: dict[str, Any]) -> Optional[dict[str, Any]]:
98
+ """
99
+ Parse a single document element.
100
+
101
+ Args:
102
+ element: Element data from document
103
+
104
+ Returns:
105
+ Parsed element information or None
106
+ """
107
+ element_info = {
108
+ "start_index": element.get("startIndex", 0),
109
+ "end_index": element.get("endIndex", 0),
110
+ }
111
+
112
+ if "paragraph" in element:
113
+ paragraph = element["paragraph"]
114
+ element_info["type"] = "paragraph"
115
+ element_info["text"] = _extract_paragraph_text(paragraph)
116
+ element_info["style"] = paragraph.get("paragraphStyle", {})
117
+ element_info["is_list_item"] = "bullet" in paragraph
118
+ for api_key, key in (
119
+ ("positionedObjectIds", "positioned_object_ids"),
120
+ ("suggestedPositionedObjectIds", "suggested_positioned_object_ids"),
121
+ ):
122
+ if paragraph.get(api_key):
123
+ element_info[key] = paragraph[api_key]
124
+
125
+ elif "table" in element:
126
+ table = element["table"]
127
+ element_info["type"] = "table"
128
+ element_info["rows"] = len(table.get("tableRows", []))
129
+ element_info["columns"] = len(
130
+ table.get("tableRows", [{}])[0].get("tableCells", [])
131
+ )
132
+ element_info["cells"] = _parse_table_cells(table)
133
+ element_info["table_style"] = table.get("tableStyle", {})
134
+
135
+ elif "sectionBreak" in element:
136
+ element_info["type"] = "section_break"
137
+ element_info["section_style"] = element["sectionBreak"].get("sectionStyle", {})
138
+
139
+ elif "tableOfContents" in element:
140
+ element_info["type"] = "table_of_contents"
141
+
142
+ else:
143
+ return None
144
+
145
+ return element_info
146
+
147
+
148
+ def _parse_table_cells(table: dict[str, Any]) -> list[list[dict[str, Any]]]:
149
+ """
150
+ Parse table cells with their positions and content.
151
+
152
+ Args:
153
+ table: Table element data
154
+
155
+ Returns:
156
+ 2D list of cell information
157
+ """
158
+ cells = []
159
+ for row_idx, row in enumerate(table.get("tableRows", [])):
160
+ row_cells = []
161
+ for col_idx, cell in enumerate(row.get("tableCells", [])):
162
+ # Find the first paragraph in the cell for insertion
163
+ insertion_index = cell.get("startIndex", 0) + 1 # Default fallback
164
+
165
+ # Look for the first paragraph in cell content
166
+ content_elements = cell.get("content", [])
167
+ for element in content_elements:
168
+ if "paragraph" in element:
169
+ paragraph = element["paragraph"]
170
+ # Get the first element in the paragraph
171
+ para_elements = paragraph.get("elements", [])
172
+ if para_elements:
173
+ first_element = para_elements[0]
174
+ if "startIndex" in first_element:
175
+ insertion_index = first_element["startIndex"]
176
+ break
177
+
178
+ cell_info = {
179
+ "row": row_idx,
180
+ "column": col_idx,
181
+ "start_index": cell.get("startIndex", 0),
182
+ "end_index": cell.get("endIndex", 0),
183
+ "insertion_index": insertion_index, # Where to insert text in this cell
184
+ "content": _extract_cell_text(cell),
185
+ "content_elements": content_elements,
186
+ }
187
+ row_cells.append(cell_info)
188
+ cells.append(row_cells)
189
+ return cells
190
+
191
+
192
+ def _extract_paragraph_text(paragraph: dict[str, Any]) -> str:
193
+ """Extract text from a paragraph element."""
194
+ text_parts = []
195
+ for element in paragraph.get("elements", []):
196
+ if "textRun" in element:
197
+ text_parts.append(element["textRun"].get("content", ""))
198
+ return "".join(text_parts)
199
+
200
+
201
+ def _extract_cell_text(cell: dict[str, Any]) -> str:
202
+ """Extract text content from a table cell."""
203
+ text_parts = []
204
+ for element in cell.get("content", []):
205
+ if "paragraph" in element:
206
+ text_parts.append(_extract_paragraph_text(element["paragraph"]))
207
+ return "".join(text_parts)
208
+
209
+
210
+ def _parse_segment(
211
+ segment_data: dict[str, Any], preview_chars: Optional[int] = 100
212
+ ) -> dict[str, Any]:
213
+ """Parse a document segment (header/footer)."""
214
+ content = segment_data.get("content", [])
215
+ text_parts = []
216
+ for element in content:
217
+ if "paragraph" in element:
218
+ text_parts.append(_extract_paragraph_text(element["paragraph"]))
219
+
220
+ return {
221
+ "content": content,
222
+ "start_index": content[0].get("startIndex", 0) if content else 0,
223
+ "end_index": content[-1].get("endIndex", 0) if content else 0,
224
+ "text_preview": truncate_preview("".join(text_parts), preview_chars),
225
+ "element_count": len(content),
226
+ }
227
+
228
+
229
+ def find_tables(doc_data: dict[str, Any]) -> list[dict[str, Any]]:
230
+ """
231
+ Find all tables in the document with their positions and dimensions.
232
+
233
+ Args:
234
+ doc_data: Raw document data from Google Docs API
235
+
236
+ Returns:
237
+ List of table information dictionaries
238
+ """
239
+ tables = []
240
+ structure = parse_document_structure(doc_data)
241
+
242
+ for idx, table_info in enumerate(structure["tables"]):
243
+ tables.append(
244
+ {
245
+ "index": idx,
246
+ "start_index": table_info["start_index"],
247
+ "end_index": table_info["end_index"],
248
+ "rows": table_info["rows"],
249
+ "columns": table_info["columns"],
250
+ "cells": table_info["cells"],
251
+ }
252
+ )
253
+
254
+ return tables
255
+
256
+
257
+ def get_table_cell_indices(
258
+ doc_data: dict[str, Any], table_index: int = 0
259
+ ) -> Optional[list[list[tuple[int, int]]]]:
260
+ """
261
+ Get content indices for all cells in a specific table.
262
+
263
+ Args:
264
+ doc_data: Raw document data from Google Docs API
265
+ table_index: Index of the table (0-based)
266
+
267
+ Returns:
268
+ 2D list of (start_index, end_index) tuples for each cell, or None if table not found
269
+ """
270
+ tables = find_tables(doc_data)
271
+
272
+ if table_index >= len(tables):
273
+ logger.warning(
274
+ f"Table index {table_index} not found. Document has {len(tables)} tables."
275
+ )
276
+ return None
277
+
278
+ table = tables[table_index]
279
+ cell_indices = []
280
+
281
+ for row in table["cells"]:
282
+ row_indices = []
283
+ for cell in row:
284
+ # Each cell contains at least one paragraph
285
+ # Find the first paragraph in the cell for content insertion
286
+ cell_content = cell.get("content_elements", [])
287
+ if cell_content:
288
+ # Look for the first paragraph in cell content
289
+ first_para = None
290
+ for element in cell_content:
291
+ if "paragraph" in element:
292
+ first_para = element["paragraph"]
293
+ break
294
+
295
+ if first_para and "elements" in first_para and first_para["elements"]:
296
+ # Insert at the start of the first text run in the paragraph
297
+ first_text_element = first_para["elements"][0]
298
+ if "textRun" in first_text_element:
299
+ start_idx = first_text_element.get(
300
+ "startIndex", cell["start_index"] + 1
301
+ )
302
+ end_idx = first_text_element.get("endIndex", start_idx + 1)
303
+ row_indices.append((start_idx, end_idx))
304
+ continue
305
+
306
+ # Fallback: use cell boundaries with safe margins
307
+ content_start = cell["start_index"] + 1
308
+ content_end = cell["end_index"] - 1
309
+ row_indices.append((content_start, content_end))
310
+ cell_indices.append(row_indices)
311
+
312
+ return cell_indices
313
+
314
+
315
+ def find_element_at_index(
316
+ doc_data: dict[str, Any], index: int
317
+ ) -> Optional[dict[str, Any]]:
318
+ """
319
+ Find what element exists at a given index in the document.
320
+
321
+ Args:
322
+ doc_data: Raw document data from Google Docs API
323
+ index: Position in the document
324
+
325
+ Returns:
326
+ Information about the element at that position, or None
327
+ """
328
+ structure = parse_document_structure(doc_data)
329
+
330
+ for element in structure["body"]:
331
+ if element["start_index"] <= index < element["end_index"]:
332
+ element_copy = element.copy()
333
+
334
+ # If it's a table, find which cell contains the index
335
+ if element["type"] == "table" and "cells" in element:
336
+ for row_idx, row in enumerate(element["cells"]):
337
+ for col_idx, cell in enumerate(row):
338
+ if cell["start_index"] <= index < cell["end_index"]:
339
+ element_copy["containing_cell"] = {
340
+ "row": row_idx,
341
+ "column": col_idx,
342
+ "cell_start": cell["start_index"],
343
+ "cell_end": cell["end_index"],
344
+ }
345
+ break
346
+
347
+ return element_copy
348
+
349
+ return None
350
+
351
+
352
+ def get_next_paragraph_index(doc_data: dict[str, Any], after_index: int = 0) -> int:
353
+ """
354
+ Find the next safe position to insert content after a given index.
355
+
356
+ Args:
357
+ doc_data: Raw document data from Google Docs API
358
+ after_index: Index after which to find insertion point
359
+
360
+ Returns:
361
+ Safe index for insertion
362
+ """
363
+ structure = parse_document_structure(doc_data)
364
+
365
+ # Find the first paragraph element after the given index
366
+ for element in structure["body"]:
367
+ if element["type"] == "paragraph" and element["start_index"] > after_index:
368
+ # Insert at the end of the previous element or start of this paragraph
369
+ return element["start_index"]
370
+
371
+ # If no paragraph found, return the end of document
372
+ return structure["total_length"] - 1 if structure["total_length"] > 0 else 1
373
+
374
+
375
+ def _is_empty_paragraph(paragraph: dict[str, Any]) -> bool:
376
+ """A newline-only paragraph with no existing or suggested object anchors."""
377
+ return (
378
+ paragraph["end_index"] - paragraph["start_index"] == 1
379
+ and not paragraph.get("positioned_object_ids")
380
+ and not paragraph.get("suggested_positioned_object_ids")
381
+ )
382
+
383
+
384
+ def summarize_paragraph_layout(structure: dict[str, Any]) -> dict[str, Any]:
385
+ """Count empty body paragraphs and report the last paragraph's state.
386
+
387
+ Only top-level paragraphs are included; object anchors do not count as empty.
388
+ Ranges are capped extents, including protected newlines. last_paragraph is
389
+ None if absent.
390
+ """
391
+ paragraphs = [e for e in structure["body"] if e.get("type") == "paragraph"]
392
+
393
+ empty_ranges = [
394
+ {"start": p["start_index"], "end": p["end_index"]}
395
+ for p in paragraphs
396
+ if _is_empty_paragraph(p)
397
+ ]
398
+
399
+ last_paragraph = None
400
+ if paragraphs:
401
+ last = paragraphs[-1]
402
+ last_paragraph = {
403
+ "is_list_item": bool(last.get("is_list_item")),
404
+ "is_empty": _is_empty_paragraph(last),
405
+ }
406
+
407
+ return {
408
+ "empty_paragraphs": len(empty_ranges),
409
+ "empty_paragraph_ranges": empty_ranges[:EMPTY_PARAGRAPH_RANGE_LIMIT],
410
+ "empty_paragraph_ranges_truncated": len(empty_ranges)
411
+ > EMPTY_PARAGRAPH_RANGE_LIMIT,
412
+ "last_paragraph": last_paragraph,
413
+ }
414
+
415
+
416
+ def analyze_document_complexity(doc_data: dict[str, Any]) -> dict[str, Any]:
417
+ """
418
+ Analyze document complexity and provide statistics.
419
+
420
+ Args:
421
+ doc_data: Raw document data from Google Docs API
422
+
423
+ Returns:
424
+ Dictionary with document statistics
425
+ """
426
+ structure = parse_document_structure(doc_data)
427
+
428
+ stats = {
429
+ "total_elements": len(structure["body"]),
430
+ "tables": len(structure["tables"]),
431
+ "paragraphs": sum(1 for e in structure["body"] if e.get("type") == "paragraph"),
432
+ "section_breaks": sum(
433
+ 1 for e in structure["body"] if e.get("type") == "section_break"
434
+ ),
435
+ "total_length": structure["total_length"],
436
+ "has_headers": bool(structure["headers"]),
437
+ "has_footers": bool(structure["footers"]),
438
+ **summarize_paragraph_layout(structure),
439
+ }
440
+
441
+ # Add table statistics
442
+ if structure["tables"]:
443
+ total_cells = sum(
444
+ table["rows"] * table["columns"] for table in structure["tables"]
445
+ )
446
+ stats["total_table_cells"] = total_cells
447
+ stats["largest_table"] = max(
448
+ (t["rows"] * t["columns"] for t in structure["tables"]), default=0
449
+ )
450
+
451
+ return stats
452
+
453
+
454
+ def _iter_tabs(tabs: list[dict[str, Any]]) -> Iterator[dict[str, Any]]:
455
+ for tab in tabs:
456
+ yield tab
457
+ yield from _iter_tabs(tab.get("childTabs", []))
458
+
459
+
460
+ def _document_tab(doc: dict[str, Any], tab_id: Optional[str]) -> dict[str, Any]:
461
+ """Return the document tab ``tab_id``, or the only tab when omitted."""
462
+ tabs = list(_iter_tabs(doc.get("tabs", [])))
463
+ if tab_id is None:
464
+ if len(tabs) > 1:
465
+ available = [t.get("tabProperties", {}).get("tabId") for t in tabs]
466
+ raise UserInputError(
467
+ f"Document has {len(tabs)} tabs; tab_id is required. "
468
+ f"Available tab IDs: {available}"
469
+ )
470
+ tab = tabs[0] if tabs else {"documentTab": doc}
471
+ else:
472
+ tab = next(
473
+ (t for t in tabs if t.get("tabProperties", {}).get("tabId") == tab_id),
474
+ None,
475
+ )
476
+ if tab is None:
477
+ raise UserInputError(f"tab_id {tab_id!r} not found in document.")
478
+ return tab.get("documentTab", {})
479
+
480
+
481
+ def _paragraph_heading_level(paragraph: dict[str, Any]) -> Optional[int]:
482
+ """Return N for a ``HEADING_N`` paragraph, otherwise ``None``."""
483
+ style = paragraph.get("paragraphStyle", {}).get("namedStyleType", "")
484
+ return int(style[len("HEADING_") :]) if style.startswith("HEADING_") else None
485
+
486
+
487
+ def _resolve_heading_section(
488
+ content: list[dict[str, Any]],
489
+ heading: str,
490
+ heading_level: Optional[int],
491
+ tab_id: Optional[str],
492
+ ) -> tuple[int, int]:
493
+ """Return the content positions of the one matching heading and its section end.
494
+
495
+ The section ends at the next ``TITLE`` or equal-or-shallower heading, or at
496
+ ``len(content)``.
497
+ """
498
+ if not heading.strip():
499
+ raise UserInputError("'heading' must not be empty.")
500
+ if heading_level is not None and not 1 <= heading_level <= 6:
501
+ raise UserInputError("'heading_level' must be between 1 and 6.")
502
+ wanted = heading.strip().casefold()
503
+ headings = []
504
+ for idx, element in enumerate(content):
505
+ paragraph = element.get("paragraph", {})
506
+ level = _paragraph_heading_level(paragraph)
507
+ if level is not None:
508
+ headings.append((idx, level, _extract_paragraph_text(paragraph).strip()))
509
+ matches = [
510
+ (idx, level)
511
+ for idx, level, text in headings
512
+ if text.casefold() == wanted and heading_level in (None, level)
513
+ ]
514
+ if not matches:
515
+ named = [text for _, _, text in headings if text]
516
+ available = ", ".join(map(repr, named[:HEADING_LIST_LIMIT]))
517
+ if len(named) > HEADING_LIST_LIMIT:
518
+ available += f" and {len(named) - HEADING_LIST_LIMIT} more"
519
+ raise UserInputError(
520
+ f"No heading matching {heading!r} found in the document body "
521
+ f"(heading_level={heading_level!r}, tab_id={tab_id!r}). "
522
+ + (
523
+ f"Available headings: {available}. "
524
+ if available
525
+ else "The document body has no headings. "
526
+ )
527
+ + "Headings inside tables, footnotes, headers and footers are not "
528
+ "addressable by heading; use index-based editing for those."
529
+ )
530
+ if len(matches) > 1:
531
+ starts = ", ".join(str(content[idx].get("startIndex")) for idx, _ in matches)
532
+ raise UserInputError(
533
+ f"Heading {heading!r} matches {len(matches)} headings (at indices "
534
+ f"{starts}). Pass heading_level to narrow it, or use document indices."
535
+ )
536
+
537
+ match_idx, matched_level = matches[0]
538
+ for idx in range(match_idx + 1, len(content)):
539
+ paragraph = content[idx].get("paragraph")
540
+ if not paragraph:
541
+ continue
542
+ level = _paragraph_heading_level(paragraph)
543
+ style = paragraph.get("paragraphStyle", {}).get("namedStyleType")
544
+ if style == "TITLE" or (level is not None and level <= matched_level):
545
+ return match_idx, idx
546
+ return match_idx, len(content)
547
+
548
+
549
+ def find_heading_section(
550
+ doc: dict[str, Any],
551
+ heading: str,
552
+ heading_level: Optional[int] = None,
553
+ tab_id: Optional[str] = None,
554
+ ) -> dict[str, Any]:
555
+ """Locate the one body heading matching ``heading`` and the section below it.
556
+
557
+ The section runs to the next ``TITLE`` or equal-or-shallower heading, or to
558
+ the body's undeletable final newline. Returns ``body_start``,
559
+ ``section_end``, ``last_paragraph`` and ``footnote_refs``.
560
+ """
561
+ content = _document_tab(doc, tab_id).get("body", {}).get("content", [])
562
+ match_idx, end_idx = _resolve_heading_section(
563
+ content, heading, heading_level, tab_id
564
+ )
565
+ body_start = content[match_idx]["endIndex"]
566
+ last_paragraph = [e for e in content[match_idx:end_idx] if e.get("paragraph")][-1]
567
+ if end_idx < len(content):
568
+ section_end = content[end_idx]["startIndex"]
569
+ else:
570
+ # The body's final newline cannot be deleted.
571
+ section_end = last_paragraph["endIndex"] - 1
572
+
573
+ footnote_refs = sum(
574
+ 1
575
+ for element in content[match_idx + 1 :]
576
+ for run in element.get("paragraph", {}).get("elements", [])
577
+ if "footnoteReference" in run
578
+ and body_start <= run.get("startIndex", -1) < section_end
579
+ )
580
+ return {
581
+ "body_start": body_start,
582
+ "section_end": section_end,
583
+ "last_paragraph": last_paragraph,
584
+ "footnote_refs": footnote_refs,
585
+ }
586
+
587
+
588
+ def heading_section_document(
589
+ doc: dict[str, Any],
590
+ heading: str,
591
+ heading_level: Optional[int] = None,
592
+ tab_id: Optional[str] = None,
593
+ ) -> dict[str, Any]:
594
+ """Return the tab cut down to the section under ``heading``, heading included.
595
+
596
+ Headers, footers and positioned objects anchored outside the section are
597
+ dropped. An empty ``tab_id`` is treated as omitted.
598
+ """
599
+ tab_id = tab_id or None
600
+ document_tab = _document_tab(doc, tab_id)
601
+ content = document_tab.get("body", {}).get("content", [])
602
+ match_idx, end_idx = _resolve_heading_section(
603
+ content, heading, heading_level, tab_id
604
+ )
605
+ section = content[match_idx:end_idx]
606
+ anchored = {
607
+ object_id
608
+ for element in section
609
+ for object_id in element.get("paragraph", {}).get("positionedObjectIds", [])
610
+ }
611
+ return {
612
+ **document_tab,
613
+ "body": {"content": section},
614
+ "headers": {},
615
+ "footers": {},
616
+ "positionedObjects": {
617
+ object_id: obj
618
+ for object_id, obj in document_tab.get("positionedObjects", {}).items()
619
+ if object_id in anchored
620
+ },
621
+ }