gws-cli 1.0.0__py3-none-any.whl

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.
gws/services/docs.py ADDED
@@ -0,0 +1,3723 @@
1
+ """Google Docs service operations."""
2
+
3
+ import io
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from googleapiclient.errors import HttpError
8
+ from googleapiclient.http import MediaIoBaseDownload
9
+
10
+ from gws.services.base import BaseService
11
+ from gws.output import output_success, output_error, output_external_content
12
+ from gws.exceptions import ExitCode
13
+
14
+
15
+ class DocsService(BaseService):
16
+ """Google Docs operations."""
17
+
18
+ SERVICE_NAME = "docs"
19
+ VERSION = "v1"
20
+
21
+ EXPORT_FORMATS: dict[str, str] = {
22
+ "markdown": "text/markdown",
23
+ "md": "text/markdown",
24
+ "pdf": "application/pdf",
25
+ "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
26
+ "txt": "text/plain",
27
+ "text": "text/plain",
28
+ "html": "text/html",
29
+ "rtf": "application/rtf",
30
+ "epub": "application/epub+zip",
31
+ "odt": "application/vnd.oasis.opendocument.text",
32
+ }
33
+
34
+ def _extract_text(self, content: list[dict]) -> str:
35
+ """Extract plain text from document content."""
36
+ text_parts = []
37
+ for element in content:
38
+ if "paragraph" in element:
39
+ for elem in element["paragraph"].get("elements", []):
40
+ if "textRun" in elem:
41
+ text_parts.append(elem["textRun"].get("content", ""))
42
+ elif "table" in element:
43
+ for row in element["table"].get("tableRows", []):
44
+ for cell in row.get("tableCells", []):
45
+ cell_text = self._extract_text(cell.get("content", []))
46
+ text_parts.append(cell_text)
47
+ return "".join(text_parts)
48
+
49
+ def _extract_structure(self, content: list[dict]) -> list[dict]:
50
+ """Extract heading structure from document content."""
51
+ headings = []
52
+ for element in content:
53
+ if "paragraph" in element:
54
+ para = element["paragraph"]
55
+ style = para.get("paragraphStyle", {}).get("namedStyleType", "")
56
+ if style.startswith("HEADING_"):
57
+ level = int(style.replace("HEADING_", ""))
58
+ text = ""
59
+ for elem in para.get("elements", []):
60
+ if "textRun" in elem:
61
+ text += elem["textRun"].get("content", "")
62
+ headings.append({
63
+ "level": level,
64
+ "text": text.strip(),
65
+ "style": style,
66
+ })
67
+ return headings
68
+
69
+ def _get_tab_content(self, doc: dict, tab_id: str | None = None) -> list[dict]:
70
+ """Get content from a specific tab or the default (first) tab.
71
+
72
+ Args:
73
+ doc: The document response from the API.
74
+ tab_id: Optional tab ID. If None, returns content from the first tab
75
+ or falls back to the legacy body.content.
76
+
77
+ Returns:
78
+ List of content elements from the specified tab.
79
+
80
+ Raises:
81
+ ValueError: If tab_id is specified but not found.
82
+ """
83
+ tabs = doc.get("tabs", [])
84
+
85
+ if tab_id:
86
+ # Search for specific tab (including nested tabs)
87
+ tab = self._find_tab_by_id(tabs, tab_id)
88
+ if tab:
89
+ return tab.get("documentTab", {}).get("body", {}).get("content", [])
90
+ raise ValueError(f"Tab not found: {tab_id}")
91
+
92
+ # Default: use first tab if available, otherwise legacy body
93
+ if tabs:
94
+ first_tab = tabs[0]
95
+ return first_tab.get("documentTab", {}).get("body", {}).get("content", [])
96
+ return doc.get("body", {}).get("content", [])
97
+
98
+ def _find_tab_by_id(self, tabs: list[dict], tab_id: str) -> dict | None:
99
+ """Recursively find a tab by ID (tabs can be nested)."""
100
+ for tab in tabs:
101
+ props = tab.get("tabProperties", {})
102
+ if props.get("tabId") == tab_id:
103
+ return tab
104
+ # Check child tabs
105
+ child_tabs = tab.get("childTabs", [])
106
+ if child_tabs:
107
+ found = self._find_tab_by_id(child_tabs, tab_id)
108
+ if found:
109
+ return found
110
+ return None
111
+
112
+ def _extract_tabs_info(self, tabs: list[dict], parent_index: int | None = None) -> list[dict]:
113
+ """Extract tab information from tabs array (recursive for child tabs)."""
114
+ result = []
115
+ for i, tab in enumerate(tabs):
116
+ props = tab.get("tabProperties", {})
117
+ doc_tab = tab.get("documentTab", {})
118
+
119
+ # Get content length for info
120
+ body_content = doc_tab.get("body", {}).get("content", [])
121
+ content_length = len(body_content)
122
+
123
+ tab_info = {
124
+ "tab_id": props.get("tabId"),
125
+ "title": props.get("title", ""),
126
+ "index": props.get("index", i),
127
+ "parent_index": parent_index,
128
+ "content_elements": content_length,
129
+ }
130
+ result.append(tab_info)
131
+
132
+ # Process child tabs
133
+ child_tabs = tab.get("childTabs", [])
134
+ if child_tabs:
135
+ result.extend(self._extract_tabs_info(child_tabs, parent_index=i))
136
+
137
+ return result
138
+
139
+ def list_tabs(self, document_id: str) -> dict[str, Any]:
140
+ """List all tabs in a document.
141
+
142
+ Returns tab IDs, titles, and positions.
143
+ """
144
+ try:
145
+ # Include tabs content to get full tab structure
146
+ doc = self.execute(self.service.documents().get(
147
+ documentId=document_id,
148
+ includeTabsContent=True,
149
+ ))
150
+
151
+ tabs = doc.get("tabs", [])
152
+ tabs_info = self._extract_tabs_info(tabs)
153
+
154
+ output_success(
155
+ operation="docs.list_tabs",
156
+ document_id=document_id,
157
+ title=doc.get("title", ""),
158
+ tab_count=len(tabs_info),
159
+ tabs=tabs_info,
160
+ )
161
+ return {"tabs": tabs_info}
162
+ except HttpError as e:
163
+ output_error(
164
+ error_code="API_ERROR",
165
+ operation="docs.list_tabs",
166
+ message=f"Google Docs API error: {e.reason}",
167
+ )
168
+ raise SystemExit(ExitCode.API_ERROR)
169
+
170
+ def create_tab(
171
+ self,
172
+ document_id: str,
173
+ title: str,
174
+ index: int | None = None,
175
+ ) -> dict[str, Any]:
176
+ """Create a new tab in the document.
177
+
178
+ Args:
179
+ document_id: The document ID.
180
+ title: Title for the new tab.
181
+ index: Optional position (0-based). If None, appends to end.
182
+ """
183
+ try:
184
+ tab_properties: dict[str, Any] = {"title": title}
185
+ if index is not None:
186
+ tab_properties["index"] = index
187
+
188
+ requests = [{"addDocumentTab": {"tabProperties": tab_properties}}]
189
+
190
+ result = self.execute(
191
+ self.service.documents()
192
+ .batchUpdate(documentId=document_id, body={"requests": requests})
193
+ )
194
+
195
+ # Extract the created tab ID from response
196
+ replies = result.get("replies", [{}])
197
+ created_tab = replies[0].get("addDocumentTab", {})
198
+ new_tab_id = created_tab.get("tabProperties", {}).get("tabId")
199
+
200
+ output_success(
201
+ operation="docs.create_tab",
202
+ document_id=document_id,
203
+ tab_id=new_tab_id,
204
+ title=title,
205
+ index=index,
206
+ )
207
+ return {"tab_id": new_tab_id, "title": title}
208
+ except HttpError as e:
209
+ output_error(
210
+ error_code="API_ERROR",
211
+ operation="docs.create_tab",
212
+ message=f"Google Docs API error: {e.reason}",
213
+ )
214
+ raise SystemExit(ExitCode.API_ERROR)
215
+
216
+ def delete_tab(self, document_id: str, tab_id: str) -> dict[str, Any]:
217
+ """Delete a tab from the document.
218
+
219
+ Args:
220
+ document_id: The document ID.
221
+ tab_id: The tab ID to delete.
222
+
223
+ Note: Cannot delete the last remaining tab.
224
+ """
225
+ try:
226
+ requests = [{"deleteTab": {"tabId": tab_id}}]
227
+
228
+ self.execute(self.service.documents().batchUpdate(
229
+ documentId=document_id, body={"requests": requests}
230
+ ))
231
+
232
+ output_success(
233
+ operation="docs.delete_tab",
234
+ document_id=document_id,
235
+ tab_id=tab_id,
236
+ )
237
+ return {"deleted": True, "tab_id": tab_id}
238
+ except HttpError as e:
239
+ output_error(
240
+ error_code="API_ERROR",
241
+ operation="docs.delete_tab",
242
+ message=f"Google Docs API error: {e.reason}",
243
+ )
244
+ raise SystemExit(ExitCode.API_ERROR)
245
+
246
+ def rename_tab(
247
+ self,
248
+ document_id: str,
249
+ tab_id: str,
250
+ title: str,
251
+ ) -> dict[str, Any]:
252
+ """Rename a tab.
253
+
254
+ Args:
255
+ document_id: The document ID.
256
+ tab_id: The tab ID to rename.
257
+ title: New title for the tab.
258
+ """
259
+ try:
260
+ requests = [
261
+ {
262
+ "updateDocumentTabProperties": {
263
+ "tabProperties": {"tabId": tab_id, "title": title},
264
+ "fields": "title",
265
+ }
266
+ }
267
+ ]
268
+
269
+ self.execute(self.service.documents().batchUpdate(
270
+ documentId=document_id, body={"requests": requests}
271
+ ))
272
+
273
+ output_success(
274
+ operation="docs.rename_tab",
275
+ document_id=document_id,
276
+ tab_id=tab_id,
277
+ new_title=title,
278
+ )
279
+ return {"tab_id": tab_id, "title": title}
280
+ except HttpError as e:
281
+ output_error(
282
+ error_code="API_ERROR",
283
+ operation="docs.rename_tab",
284
+ message=f"Google Docs API error: {e.reason}",
285
+ )
286
+ raise SystemExit(ExitCode.API_ERROR)
287
+
288
+ def reorder_tab(
289
+ self,
290
+ document_id: str,
291
+ tab_id: str,
292
+ new_index: int,
293
+ ) -> dict[str, Any]:
294
+ """Move a tab to a new position.
295
+
296
+ Args:
297
+ document_id: The document ID.
298
+ tab_id: The tab ID to move.
299
+ new_index: New position (0-based).
300
+ """
301
+ try:
302
+ requests = [
303
+ {
304
+ "updateDocumentTabProperties": {
305
+ "tabProperties": {"tabId": tab_id, "index": new_index},
306
+ "fields": "index",
307
+ }
308
+ }
309
+ ]
310
+
311
+ self.execute(self.service.documents().batchUpdate(
312
+ documentId=document_id, body={"requests": requests}
313
+ ))
314
+
315
+ output_success(
316
+ operation="docs.reorder_tab",
317
+ document_id=document_id,
318
+ tab_id=tab_id,
319
+ new_index=new_index,
320
+ )
321
+ return {"tab_id": tab_id, "index": new_index}
322
+ except HttpError as e:
323
+ output_error(
324
+ error_code="API_ERROR",
325
+ operation="docs.reorder_tab",
326
+ message=f"Google Docs API error: {e.reason}",
327
+ )
328
+ raise SystemExit(ExitCode.API_ERROR)
329
+
330
+ def read(self, document_id: str, tab_id: str | None = None) -> dict[str, Any]:
331
+ """Read document content as plain text.
332
+
333
+ Args:
334
+ document_id: The document ID.
335
+ tab_id: Optional tab ID to read from. If None, reads the first tab.
336
+ """
337
+ try:
338
+ # Include tabs content when tab_id specified or to use new API structure
339
+ doc = self.execute(self.service.documents().get(
340
+ documentId=document_id,
341
+ includeTabsContent=True,
342
+ ))
343
+
344
+ try:
345
+ content = self._get_tab_content(doc, tab_id)
346
+ except ValueError as e:
347
+ output_error(
348
+ error_code="NOT_FOUND",
349
+ operation="docs.read",
350
+ message=str(e),
351
+ )
352
+ raise SystemExit(ExitCode.NOT_FOUND)
353
+
354
+ text = self._extract_text(content)
355
+
356
+ output_external_content(
357
+ operation="docs.read",
358
+ source_type="document",
359
+ source_id=document_id,
360
+ content_fields={
361
+ "content": text,
362
+ },
363
+ document_id=document_id,
364
+ title=doc.get("title", ""),
365
+ tab_id=tab_id,
366
+ revision_id=doc.get("revisionId"),
367
+ )
368
+ return doc
369
+ except HttpError as e:
370
+ output_error(
371
+ error_code="API_ERROR",
372
+ operation="docs.read",
373
+ message=f"Google Docs API error: {e.reason}",
374
+ )
375
+ raise SystemExit(ExitCode.API_ERROR)
376
+
377
+ def structure(self, document_id: str, tab_id: str | None = None) -> dict[str, Any]:
378
+ """Get document heading structure.
379
+
380
+ Args:
381
+ document_id: The document ID.
382
+ tab_id: Optional tab ID to get structure from. If None, uses the first tab.
383
+ """
384
+ try:
385
+ doc = self.execute(self.service.documents().get(
386
+ documentId=document_id,
387
+ includeTabsContent=True,
388
+ ))
389
+
390
+ try:
391
+ content = self._get_tab_content(doc, tab_id)
392
+ except ValueError as e:
393
+ output_error(
394
+ error_code="NOT_FOUND",
395
+ operation="docs.structure",
396
+ message=str(e),
397
+ )
398
+ raise SystemExit(ExitCode.NOT_FOUND)
399
+
400
+ headings = self._extract_structure(content)
401
+
402
+ output_success(
403
+ operation="docs.structure",
404
+ document_id=document_id,
405
+ title=doc.get("title", ""),
406
+ tab_id=tab_id,
407
+ headings=headings,
408
+ heading_count=len(headings),
409
+ )
410
+ return {"headings": headings}
411
+ except HttpError as e:
412
+ output_error(
413
+ error_code="API_ERROR",
414
+ operation="docs.structure",
415
+ message=f"Google Docs API error: {e.reason}",
416
+ )
417
+ raise SystemExit(ExitCode.API_ERROR)
418
+
419
+ def create(
420
+ self,
421
+ title: str,
422
+ content: str | None = None,
423
+ folder_id: str | None = None,
424
+ ) -> dict[str, Any]:
425
+ """Create a new document."""
426
+ try:
427
+ # Create the document
428
+ doc = self.execute(self.service.documents().create(body={"title": title}))
429
+ document_id = doc["documentId"]
430
+
431
+ # Add initial content if provided
432
+ if content:
433
+ requests = [
434
+ {
435
+ "insertText": {
436
+ "location": {"index": 1},
437
+ "text": content,
438
+ }
439
+ }
440
+ ]
441
+ self.execute(self.service.documents().batchUpdate(
442
+ documentId=document_id, body={"requests": requests}
443
+ ))
444
+
445
+ # Move to folder if specified
446
+ if folder_id:
447
+ # Get current parents
448
+ file = self.execute(self.drive_service.files().get(
449
+ fileId=document_id, fields="parents"
450
+ ))
451
+ previous_parents = ",".join(file.get("parents", []))
452
+
453
+ self.execute(self.drive_service.files().update(
454
+ fileId=document_id,
455
+ addParents=folder_id,
456
+ removeParents=previous_parents,
457
+ fields="id, parents",
458
+ ))
459
+
460
+ output_success(
461
+ operation="docs.create",
462
+ document_id=document_id,
463
+ title=title,
464
+ web_view_link=f"https://docs.google.com/document/d/{document_id}/edit",
465
+ )
466
+ return doc
467
+ except HttpError as e:
468
+ output_error(
469
+ error_code="API_ERROR",
470
+ operation="docs.create",
471
+ message=f"Google Docs API error: {e.reason}",
472
+ )
473
+ raise SystemExit(ExitCode.API_ERROR)
474
+
475
+ def insert(
476
+ self,
477
+ document_id: str,
478
+ text: str,
479
+ index: int = 1,
480
+ tab_id: str | None = None,
481
+ ) -> dict[str, Any]:
482
+ """Insert text at a specific index.
483
+
484
+ Args:
485
+ document_id: The document ID.
486
+ text: Text to insert.
487
+ index: Character index to insert at (default: 1, start of document).
488
+ tab_id: Optional tab ID to insert into.
489
+ """
490
+ try:
491
+ location: dict[str, Any] = {"index": index}
492
+ if tab_id:
493
+ location["tabId"] = tab_id
494
+
495
+ requests = [
496
+ {
497
+ "insertText": {
498
+ "location": location,
499
+ "text": text,
500
+ }
501
+ }
502
+ ]
503
+
504
+ result = self.execute(
505
+ self.service.documents()
506
+ .batchUpdate(documentId=document_id, body={"requests": requests})
507
+ )
508
+
509
+ output_success(
510
+ operation="docs.insert",
511
+ document_id=document_id,
512
+ index=index,
513
+ tab_id=tab_id,
514
+ text_length=len(text),
515
+ )
516
+ return result
517
+ except HttpError as e:
518
+ output_error(
519
+ error_code="API_ERROR",
520
+ operation="docs.insert",
521
+ message=f"Google Docs API error: {e.reason}",
522
+ )
523
+ raise SystemExit(ExitCode.API_ERROR)
524
+
525
+ def append(
526
+ self,
527
+ document_id: str,
528
+ text: str,
529
+ tab_id: str | None = None,
530
+ ) -> dict[str, Any]:
531
+ """Append text to the end of the document (or tab).
532
+
533
+ Args:
534
+ document_id: The document ID.
535
+ text: Text to append.
536
+ tab_id: Optional tab ID to append to.
537
+ """
538
+ try:
539
+ # Get document to find end index
540
+ doc = self.execute(self.service.documents().get(
541
+ documentId=document_id,
542
+ includeTabsContent=True,
543
+ ))
544
+
545
+ try:
546
+ content = self._get_tab_content(doc, tab_id)
547
+ except ValueError as e:
548
+ output_error(
549
+ error_code="NOT_FOUND",
550
+ operation="docs.append",
551
+ message=str(e),
552
+ )
553
+ raise SystemExit(ExitCode.NOT_FOUND)
554
+
555
+ # Find the end index (last element's endIndex - 1)
556
+ end_index = 1
557
+ if content:
558
+ last_element = content[-1]
559
+ end_index = last_element.get("endIndex", 1) - 1
560
+
561
+ location: dict[str, Any] = {"index": end_index}
562
+ if tab_id:
563
+ location["tabId"] = tab_id
564
+
565
+ requests = [
566
+ {
567
+ "insertText": {
568
+ "location": location,
569
+ "text": text,
570
+ }
571
+ }
572
+ ]
573
+
574
+ result = self.execute(
575
+ self.service.documents()
576
+ .batchUpdate(documentId=document_id, body={"requests": requests})
577
+ )
578
+
579
+ output_success(
580
+ operation="docs.append",
581
+ document_id=document_id,
582
+ index=end_index,
583
+ tab_id=tab_id,
584
+ text_length=len(text),
585
+ )
586
+ return result
587
+ except HttpError as e:
588
+ output_error(
589
+ error_code="API_ERROR",
590
+ operation="docs.append",
591
+ message=f"Google Docs API error: {e.reason}",
592
+ )
593
+ raise SystemExit(ExitCode.API_ERROR)
594
+
595
+ def replace(
596
+ self,
597
+ document_id: str,
598
+ find: str,
599
+ replace_with: str,
600
+ match_case: bool = False,
601
+ tab_id: str | None = None,
602
+ ) -> dict[str, Any]:
603
+ """Replace text throughout the document (or specific tab).
604
+
605
+ Args:
606
+ document_id: The document ID.
607
+ find: Text to find.
608
+ replace_with: Replacement text.
609
+ match_case: Case-sensitive matching.
610
+ tab_id: Optional tab ID to restrict replacement to.
611
+ """
612
+ try:
613
+ replace_request: dict[str, Any] = {
614
+ "containsText": {
615
+ "text": find,
616
+ "matchCase": match_case,
617
+ },
618
+ "replaceText": replace_with,
619
+ }
620
+
621
+ # Restrict to specific tab if provided
622
+ if tab_id:
623
+ replace_request["tabsCriteria"] = {"tabIds": [tab_id]}
624
+
625
+ requests = [{"replaceAllText": replace_request}]
626
+
627
+ result = self.execute(
628
+ self.service.documents()
629
+ .batchUpdate(documentId=document_id, body={"requests": requests})
630
+ )
631
+
632
+ # Get replacement count from response
633
+ replies = result.get("replies", [{}])
634
+ occurrences = replies[0].get("replaceAllText", {}).get(
635
+ "occurrencesChanged", 0
636
+ )
637
+
638
+ output_success(
639
+ operation="docs.replace",
640
+ document_id=document_id,
641
+ find=find,
642
+ replace_with=replace_with,
643
+ tab_id=tab_id,
644
+ occurrences_changed=occurrences,
645
+ )
646
+ return result
647
+ except HttpError as e:
648
+ output_error(
649
+ error_code="API_ERROR",
650
+ operation="docs.replace",
651
+ message=f"Google Docs API error: {e.reason}",
652
+ )
653
+ raise SystemExit(ExitCode.API_ERROR)
654
+
655
+ def format_text(
656
+ self,
657
+ document_id: str,
658
+ start_index: int,
659
+ end_index: int,
660
+ bold: bool | None = None,
661
+ italic: bool | None = None,
662
+ underline: bool | None = None,
663
+ font_size: int | None = None,
664
+ foreground_color: str | None = None,
665
+ tab_id: str | None = None,
666
+ ) -> dict[str, Any]:
667
+ """Apply formatting to a text range.
668
+
669
+ Args:
670
+ document_id: The document ID.
671
+ start_index: Start index of range.
672
+ end_index: End index of range.
673
+ bold: Bold formatting.
674
+ italic: Italic formatting.
675
+ underline: Underline formatting.
676
+ font_size: Font size in points.
677
+ foreground_color: Text color (hex).
678
+ tab_id: Optional tab ID.
679
+ """
680
+ try:
681
+ text_style: dict[str, Any] = {}
682
+ fields = []
683
+
684
+ if bold is not None:
685
+ text_style["bold"] = bold
686
+ fields.append("bold")
687
+ if italic is not None:
688
+ text_style["italic"] = italic
689
+ fields.append("italic")
690
+ if underline is not None:
691
+ text_style["underline"] = underline
692
+ fields.append("underline")
693
+ if font_size is not None:
694
+ text_style["fontSize"] = {"magnitude": font_size, "unit": "PT"}
695
+ fields.append("fontSize")
696
+ if foreground_color is not None:
697
+ # Parse hex color
698
+ from gws.utils.colors import parse_hex_color
699
+ rgb = parse_hex_color(foreground_color)
700
+ text_style["foregroundColor"] = {"color": {"rgbColor": rgb}}
701
+ fields.append("foregroundColor")
702
+
703
+ if not fields:
704
+ output_error(
705
+ error_code="INVALID_ARGS",
706
+ operation="docs.format",
707
+ message="At least one formatting option required",
708
+ )
709
+ raise SystemExit(ExitCode.INVALID_ARGS)
710
+
711
+ range_obj: dict[str, Any] = {
712
+ "startIndex": start_index,
713
+ "endIndex": end_index,
714
+ }
715
+ if tab_id:
716
+ range_obj["tabId"] = tab_id
717
+
718
+ requests = [
719
+ {
720
+ "updateTextStyle": {
721
+ "range": range_obj,
722
+ "textStyle": text_style,
723
+ "fields": ",".join(fields),
724
+ }
725
+ }
726
+ ]
727
+
728
+ result = self.execute(
729
+ self.service.documents()
730
+ .batchUpdate(documentId=document_id, body={"requests": requests})
731
+ )
732
+
733
+ output_success(
734
+ operation="docs.format",
735
+ document_id=document_id,
736
+ start_index=start_index,
737
+ end_index=end_index,
738
+ tab_id=tab_id,
739
+ formatting=fields,
740
+ )
741
+ return result
742
+ except HttpError as e:
743
+ output_error(
744
+ error_code="API_ERROR",
745
+ operation="docs.format",
746
+ message=f"Google Docs API error: {e.reason}",
747
+ )
748
+ raise SystemExit(ExitCode.API_ERROR)
749
+
750
+ def delete_content(
751
+ self,
752
+ document_id: str,
753
+ start_index: int,
754
+ end_index: int,
755
+ tab_id: str | None = None,
756
+ ) -> dict[str, Any]:
757
+ """Delete content in a range.
758
+
759
+ Args:
760
+ document_id: The document ID.
761
+ start_index: Start index of range.
762
+ end_index: End index of range.
763
+ tab_id: Optional tab ID.
764
+ """
765
+ try:
766
+ range_obj: dict[str, Any] = {
767
+ "startIndex": start_index,
768
+ "endIndex": end_index,
769
+ }
770
+ if tab_id:
771
+ range_obj["tabId"] = tab_id
772
+
773
+ requests = [{"deleteContentRange": {"range": range_obj}}]
774
+
775
+ result = self.execute(
776
+ self.service.documents()
777
+ .batchUpdate(documentId=document_id, body={"requests": requests})
778
+ )
779
+
780
+ output_success(
781
+ operation="docs.delete",
782
+ document_id=document_id,
783
+ start_index=start_index,
784
+ end_index=end_index,
785
+ tab_id=tab_id,
786
+ deleted_length=end_index - start_index,
787
+ )
788
+ return result
789
+ except HttpError as e:
790
+ output_error(
791
+ error_code="API_ERROR",
792
+ operation="docs.delete",
793
+ message=f"Google Docs API error: {e.reason}",
794
+ )
795
+ raise SystemExit(ExitCode.API_ERROR)
796
+
797
+ def insert_page_break(
798
+ self,
799
+ document_id: str,
800
+ index: int,
801
+ tab_id: str | None = None,
802
+ ) -> dict[str, Any]:
803
+ """Insert a page break at the specified index.
804
+
805
+ Args:
806
+ document_id: The document ID.
807
+ index: Character index to insert page break.
808
+ tab_id: Optional tab ID.
809
+ """
810
+ try:
811
+ location: dict[str, Any] = {"index": index}
812
+ if tab_id:
813
+ location["tabId"] = tab_id
814
+
815
+ requests = [{"insertPageBreak": {"location": location}}]
816
+
817
+ result = self.execute(
818
+ self.service.documents()
819
+ .batchUpdate(documentId=document_id, body={"requests": requests})
820
+ )
821
+
822
+ output_success(
823
+ operation="docs.page_break",
824
+ document_id=document_id,
825
+ index=index,
826
+ tab_id=tab_id,
827
+ )
828
+ return result
829
+ except HttpError as e:
830
+ output_error(
831
+ error_code="API_ERROR",
832
+ operation="docs.page_break",
833
+ message=f"Google Docs API error: {e.reason}",
834
+ )
835
+ raise SystemExit(ExitCode.API_ERROR)
836
+
837
+ def insert_image(
838
+ self,
839
+ document_id: str,
840
+ image_url: str,
841
+ index: int | None = None,
842
+ width: float | None = None,
843
+ height: float | None = None,
844
+ tab_id: str | None = None,
845
+ ) -> dict[str, Any]:
846
+ """Insert an image from a URL.
847
+
848
+ Args:
849
+ document_id: The document ID.
850
+ image_url: URL of the image to insert.
851
+ index: Character index (default: end of document).
852
+ width: Image width in points.
853
+ height: Image height in points.
854
+ tab_id: Optional tab ID.
855
+ """
856
+ try:
857
+ # If no index specified, append at end
858
+ if index is None:
859
+ doc = self.execute(self.service.documents().get(
860
+ documentId=document_id,
861
+ includeTabsContent=True,
862
+ ))
863
+ try:
864
+ content = self._get_tab_content(doc, tab_id)
865
+ except ValueError as e:
866
+ output_error(
867
+ error_code="NOT_FOUND",
868
+ operation="docs.insert_image",
869
+ message=str(e),
870
+ )
871
+ raise SystemExit(ExitCode.NOT_FOUND)
872
+ if content:
873
+ index = content[-1].get("endIndex", 1) - 1
874
+ else:
875
+ index = 1
876
+
877
+ location: dict[str, Any] = {"index": index}
878
+ if tab_id:
879
+ location["tabId"] = tab_id
880
+
881
+ insert_inline_image: dict[str, Any] = {
882
+ "location": location,
883
+ "uri": image_url,
884
+ }
885
+
886
+ # Add size if specified
887
+ if width is not None or height is not None:
888
+ object_size: dict[str, Any] = {}
889
+ if width is not None:
890
+ object_size["width"] = {"magnitude": width, "unit": "PT"}
891
+ if height is not None:
892
+ object_size["height"] = {"magnitude": height, "unit": "PT"}
893
+ insert_inline_image["objectSize"] = object_size
894
+
895
+ requests = [{"insertInlineImage": insert_inline_image}]
896
+
897
+ result = self.execute(
898
+ self.service.documents()
899
+ .batchUpdate(documentId=document_id, body={"requests": requests})
900
+ )
901
+
902
+ output_success(
903
+ operation="docs.insert_image",
904
+ document_id=document_id,
905
+ index=index,
906
+ tab_id=tab_id,
907
+ image_url=image_url,
908
+ )
909
+ return result
910
+ except HttpError as e:
911
+ output_error(
912
+ error_code="API_ERROR",
913
+ operation="docs.insert_image",
914
+ message=f"Google Docs API error: {e.reason}",
915
+ )
916
+ raise SystemExit(ExitCode.API_ERROR)
917
+
918
+ # =========================================================================
919
+ # TABLE OPERATIONS
920
+ # =========================================================================
921
+
922
+ def _get_tables(self, document_id: str) -> list[dict]:
923
+ """Get all tables from document with their start indices."""
924
+ doc = self.execute(self.service.documents().get(documentId=document_id))
925
+ content = doc.get("body", {}).get("content", [])
926
+ tables = []
927
+ for element in content:
928
+ if "table" in element:
929
+ tables.append({
930
+ "startIndex": element.get("startIndex"),
931
+ "endIndex": element.get("endIndex"),
932
+ "rows": len(element["table"].get("tableRows", [])),
933
+ "columns": len(
934
+ element["table"]
935
+ .get("tableRows", [{}])[0]
936
+ .get("tableCells", [])
937
+ ) if element["table"].get("tableRows") else 0,
938
+ "table": element["table"],
939
+ })
940
+ return tables
941
+
942
+ def _get_end_index(self, document_id: str) -> int:
943
+ """Get the end index of the document body."""
944
+ doc = self.execute(self.service.documents().get(documentId=document_id))
945
+ content = doc.get("body", {}).get("content", [])
946
+ if content:
947
+ return content[-1].get("endIndex", 1) - 1
948
+ return 1
949
+
950
+ def insert_table(
951
+ self,
952
+ document_id: str,
953
+ rows: int,
954
+ columns: int,
955
+ index: int | None = None,
956
+ ) -> dict[str, Any]:
957
+ """Insert a table at the specified index."""
958
+ try:
959
+ if index is None:
960
+ index = self._get_end_index(document_id)
961
+
962
+ requests = [{
963
+ "insertTable": {
964
+ "location": {"index": index},
965
+ "rows": rows,
966
+ "columns": columns,
967
+ }
968
+ }]
969
+
970
+ result = self.execute(self.service.documents().batchUpdate(
971
+ documentId=document_id, body={"requests": requests}
972
+ ))
973
+
974
+ output_success(
975
+ operation="docs.insert_table",
976
+ document_id=document_id,
977
+ rows=rows,
978
+ columns=columns,
979
+ index=index,
980
+ )
981
+ return result
982
+ except HttpError as e:
983
+ output_error(
984
+ error_code="API_ERROR",
985
+ operation="docs.insert_table",
986
+ message=f"Google Docs API error: {e.reason}",
987
+ )
988
+ raise SystemExit(ExitCode.API_ERROR)
989
+
990
+ def insert_table_row(
991
+ self,
992
+ document_id: str,
993
+ table_index: int,
994
+ row_index: int,
995
+ insert_below: bool = True,
996
+ ) -> dict[str, Any]:
997
+ """Insert a row into a table."""
998
+ try:
999
+ tables = self._get_tables(document_id)
1000
+ if table_index >= len(tables):
1001
+ output_error(
1002
+ error_code="INVALID_ARGS",
1003
+ operation="docs.insert_table_row",
1004
+ message=f"Table index {table_index} not found (document has {len(tables)} tables)",
1005
+ )
1006
+ raise SystemExit(ExitCode.INVALID_ARGS)
1007
+
1008
+ table = tables[table_index]
1009
+ requests = [{
1010
+ "insertTableRow": {
1011
+ "tableCellLocation": {
1012
+ "tableStartLocation": {"index": table["startIndex"]},
1013
+ "rowIndex": row_index,
1014
+ "columnIndex": 0,
1015
+ },
1016
+ "insertBelow": insert_below,
1017
+ }
1018
+ }]
1019
+
1020
+ result = self.execute(self.service.documents().batchUpdate(
1021
+ documentId=document_id, body={"requests": requests}
1022
+ ))
1023
+
1024
+ output_success(
1025
+ operation="docs.insert_table_row",
1026
+ document_id=document_id,
1027
+ table_index=table_index,
1028
+ row_index=row_index,
1029
+ insert_below=insert_below,
1030
+ )
1031
+ return result
1032
+ except HttpError as e:
1033
+ output_error(
1034
+ error_code="API_ERROR",
1035
+ operation="docs.insert_table_row",
1036
+ message=f"Google Docs API error: {e.reason}",
1037
+ )
1038
+ raise SystemExit(ExitCode.API_ERROR)
1039
+
1040
+ def insert_table_column(
1041
+ self,
1042
+ document_id: str,
1043
+ table_index: int,
1044
+ column_index: int,
1045
+ insert_right: bool = True,
1046
+ ) -> dict[str, Any]:
1047
+ """Insert a column into a table."""
1048
+ try:
1049
+ tables = self._get_tables(document_id)
1050
+ if table_index >= len(tables):
1051
+ output_error(
1052
+ error_code="INVALID_ARGS",
1053
+ operation="docs.insert_table_column",
1054
+ message=f"Table index {table_index} not found",
1055
+ )
1056
+ raise SystemExit(ExitCode.INVALID_ARGS)
1057
+
1058
+ table = tables[table_index]
1059
+ requests = [{
1060
+ "insertTableColumn": {
1061
+ "tableCellLocation": {
1062
+ "tableStartLocation": {"index": table["startIndex"]},
1063
+ "rowIndex": 0,
1064
+ "columnIndex": column_index,
1065
+ },
1066
+ "insertRight": insert_right,
1067
+ }
1068
+ }]
1069
+
1070
+ result = self.execute(self.service.documents().batchUpdate(
1071
+ documentId=document_id, body={"requests": requests}
1072
+ ))
1073
+
1074
+ output_success(
1075
+ operation="docs.insert_table_column",
1076
+ document_id=document_id,
1077
+ table_index=table_index,
1078
+ column_index=column_index,
1079
+ insert_right=insert_right,
1080
+ )
1081
+ return result
1082
+ except HttpError as e:
1083
+ output_error(
1084
+ error_code="API_ERROR",
1085
+ operation="docs.insert_table_column",
1086
+ message=f"Google Docs API error: {e.reason}",
1087
+ )
1088
+ raise SystemExit(ExitCode.API_ERROR)
1089
+
1090
+ def delete_table_row(
1091
+ self,
1092
+ document_id: str,
1093
+ table_index: int,
1094
+ row_index: int,
1095
+ ) -> dict[str, Any]:
1096
+ """Delete a row from a table."""
1097
+ try:
1098
+ tables = self._get_tables(document_id)
1099
+ if table_index >= len(tables):
1100
+ output_error(
1101
+ error_code="INVALID_ARGS",
1102
+ operation="docs.delete_table_row",
1103
+ message=f"Table index {table_index} not found",
1104
+ )
1105
+ raise SystemExit(ExitCode.INVALID_ARGS)
1106
+
1107
+ table = tables[table_index]
1108
+ requests = [{
1109
+ "deleteTableRow": {
1110
+ "tableCellLocation": {
1111
+ "tableStartLocation": {"index": table["startIndex"]},
1112
+ "rowIndex": row_index,
1113
+ "columnIndex": 0,
1114
+ },
1115
+ }
1116
+ }]
1117
+
1118
+ result = self.execute(self.service.documents().batchUpdate(
1119
+ documentId=document_id, body={"requests": requests}
1120
+ ))
1121
+
1122
+ output_success(
1123
+ operation="docs.delete_table_row",
1124
+ document_id=document_id,
1125
+ table_index=table_index,
1126
+ row_index=row_index,
1127
+ )
1128
+ return result
1129
+ except HttpError as e:
1130
+ output_error(
1131
+ error_code="API_ERROR",
1132
+ operation="docs.delete_table_row",
1133
+ message=f"Google Docs API error: {e.reason}",
1134
+ )
1135
+ raise SystemExit(ExitCode.API_ERROR)
1136
+
1137
+ def delete_table_column(
1138
+ self,
1139
+ document_id: str,
1140
+ table_index: int,
1141
+ column_index: int,
1142
+ ) -> dict[str, Any]:
1143
+ """Delete a column from a table."""
1144
+ try:
1145
+ tables = self._get_tables(document_id)
1146
+ if table_index >= len(tables):
1147
+ output_error(
1148
+ error_code="INVALID_ARGS",
1149
+ operation="docs.delete_table_column",
1150
+ message=f"Table index {table_index} not found",
1151
+ )
1152
+ raise SystemExit(ExitCode.INVALID_ARGS)
1153
+
1154
+ table = tables[table_index]
1155
+ requests = [{
1156
+ "deleteTableColumn": {
1157
+ "tableCellLocation": {
1158
+ "tableStartLocation": {"index": table["startIndex"]},
1159
+ "rowIndex": 0,
1160
+ "columnIndex": column_index,
1161
+ },
1162
+ }
1163
+ }]
1164
+
1165
+ result = self.execute(self.service.documents().batchUpdate(
1166
+ documentId=document_id, body={"requests": requests}
1167
+ ))
1168
+
1169
+ output_success(
1170
+ operation="docs.delete_table_column",
1171
+ document_id=document_id,
1172
+ table_index=table_index,
1173
+ column_index=column_index,
1174
+ )
1175
+ return result
1176
+ except HttpError as e:
1177
+ output_error(
1178
+ error_code="API_ERROR",
1179
+ operation="docs.delete_table_column",
1180
+ message=f"Google Docs API error: {e.reason}",
1181
+ )
1182
+ raise SystemExit(ExitCode.API_ERROR)
1183
+
1184
+ def merge_table_cells(
1185
+ self,
1186
+ document_id: str,
1187
+ table_index: int,
1188
+ start_row: int,
1189
+ start_column: int,
1190
+ end_row: int,
1191
+ end_column: int,
1192
+ ) -> dict[str, Any]:
1193
+ """Merge cells in a table."""
1194
+ try:
1195
+ tables = self._get_tables(document_id)
1196
+ if table_index >= len(tables):
1197
+ output_error(
1198
+ error_code="INVALID_ARGS",
1199
+ operation="docs.merge_table_cells",
1200
+ message=f"Table index {table_index} not found",
1201
+ )
1202
+ raise SystemExit(ExitCode.INVALID_ARGS)
1203
+
1204
+ table = tables[table_index]
1205
+ requests = [{
1206
+ "mergeTableCells": {
1207
+ "tableRange": {
1208
+ "tableCellLocation": {
1209
+ "tableStartLocation": {"index": table["startIndex"]},
1210
+ "rowIndex": start_row,
1211
+ "columnIndex": start_column,
1212
+ },
1213
+ "rowSpan": end_row - start_row + 1,
1214
+ "columnSpan": end_column - start_column + 1,
1215
+ },
1216
+ }
1217
+ }]
1218
+
1219
+ result = self.execute(self.service.documents().batchUpdate(
1220
+ documentId=document_id, body={"requests": requests}
1221
+ ))
1222
+
1223
+ output_success(
1224
+ operation="docs.merge_table_cells",
1225
+ document_id=document_id,
1226
+ table_index=table_index,
1227
+ range=f"({start_row},{start_column})-({end_row},{end_column})",
1228
+ )
1229
+ return result
1230
+ except HttpError as e:
1231
+ output_error(
1232
+ error_code="API_ERROR",
1233
+ operation="docs.merge_table_cells",
1234
+ message=f"Google Docs API error: {e.reason}",
1235
+ )
1236
+ raise SystemExit(ExitCode.API_ERROR)
1237
+
1238
+ def unmerge_table_cells(
1239
+ self,
1240
+ document_id: str,
1241
+ table_index: int,
1242
+ start_row: int,
1243
+ start_column: int,
1244
+ end_row: int,
1245
+ end_column: int,
1246
+ ) -> dict[str, Any]:
1247
+ """Unmerge previously merged cells in a table."""
1248
+ try:
1249
+ tables = self._get_tables(document_id)
1250
+ if table_index >= len(tables):
1251
+ output_error(
1252
+ error_code="INVALID_ARGS",
1253
+ operation="docs.unmerge_table_cells",
1254
+ message=f"Table index {table_index} not found",
1255
+ )
1256
+ raise SystemExit(ExitCode.INVALID_ARGS)
1257
+
1258
+ table = tables[table_index]
1259
+ requests = [{
1260
+ "unmergeTableCells": {
1261
+ "tableRange": {
1262
+ "tableCellLocation": {
1263
+ "tableStartLocation": {"index": table["startIndex"]},
1264
+ "rowIndex": start_row,
1265
+ "columnIndex": start_column,
1266
+ },
1267
+ "rowSpan": end_row - start_row + 1,
1268
+ "columnSpan": end_column - start_column + 1,
1269
+ },
1270
+ }
1271
+ }]
1272
+
1273
+ result = self.execute(self.service.documents().batchUpdate(
1274
+ documentId=document_id, body={"requests": requests}
1275
+ ))
1276
+
1277
+ output_success(
1278
+ operation="docs.unmerge_table_cells",
1279
+ document_id=document_id,
1280
+ table_index=table_index,
1281
+ range=f"({start_row},{start_column})-({end_row},{end_column})",
1282
+ )
1283
+ return result
1284
+ except HttpError as e:
1285
+ output_error(
1286
+ error_code="API_ERROR",
1287
+ operation="docs.unmerge_table_cells",
1288
+ message=f"Google Docs API error: {e.reason}",
1289
+ )
1290
+ raise SystemExit(ExitCode.API_ERROR)
1291
+
1292
+ def style_table_cell(
1293
+ self,
1294
+ document_id: str,
1295
+ table_index: int,
1296
+ start_row: int,
1297
+ start_column: int,
1298
+ end_row: int | None = None,
1299
+ end_column: int | None = None,
1300
+ background_color: str | None = None,
1301
+ border_color: str | None = None,
1302
+ border_width: float | None = None,
1303
+ padding_top: float | None = None,
1304
+ padding_bottom: float | None = None,
1305
+ padding_left: float | None = None,
1306
+ padding_right: float | None = None,
1307
+ ) -> dict[str, Any]:
1308
+ """Style table cells (background, borders, padding)."""
1309
+ try:
1310
+ from gws.utils.colors import parse_hex_color
1311
+
1312
+ tables = self._get_tables(document_id)
1313
+ if table_index >= len(tables):
1314
+ output_error(
1315
+ error_code="INVALID_ARGS",
1316
+ operation="docs.style_table_cell",
1317
+ message=f"Table index {table_index} not found",
1318
+ )
1319
+ raise SystemExit(ExitCode.INVALID_ARGS)
1320
+
1321
+ # Default to single cell if end not specified
1322
+ if end_row is None:
1323
+ end_row = start_row
1324
+ if end_column is None:
1325
+ end_column = start_column
1326
+
1327
+ table = tables[table_index]
1328
+ cell_style: dict[str, Any] = {}
1329
+ fields = []
1330
+
1331
+ if background_color is not None:
1332
+ rgb = parse_hex_color(background_color)
1333
+ cell_style["backgroundColor"] = {"color": {"rgbColor": rgb}}
1334
+ fields.append("backgroundColor")
1335
+
1336
+ if border_color is not None or border_width is not None:
1337
+ border_style: dict[str, Any] = {}
1338
+ if border_color is not None:
1339
+ rgb = parse_hex_color(border_color)
1340
+ border_style["color"] = {"color": {"rgbColor": rgb}}
1341
+ if border_width is not None:
1342
+ border_style["width"] = {"magnitude": border_width, "unit": "PT"}
1343
+ border_style["dashStyle"] = "SOLID"
1344
+
1345
+ for side in ["borderTop", "borderBottom", "borderLeft", "borderRight"]:
1346
+ cell_style[side] = border_style
1347
+ fields.append(side)
1348
+
1349
+ for pad_name, pad_val in [
1350
+ ("paddingTop", padding_top),
1351
+ ("paddingBottom", padding_bottom),
1352
+ ("paddingLeft", padding_left),
1353
+ ("paddingRight", padding_right),
1354
+ ]:
1355
+ if pad_val is not None:
1356
+ cell_style[pad_name] = {"magnitude": pad_val, "unit": "PT"}
1357
+ fields.append(pad_name)
1358
+
1359
+ if not fields:
1360
+ output_error(
1361
+ error_code="INVALID_ARGS",
1362
+ operation="docs.style_table_cell",
1363
+ message="At least one styling option required",
1364
+ )
1365
+ raise SystemExit(ExitCode.INVALID_ARGS)
1366
+
1367
+ requests = [{
1368
+ "updateTableCellStyle": {
1369
+ "tableRange": {
1370
+ "tableCellLocation": {
1371
+ "tableStartLocation": {"index": table["startIndex"]},
1372
+ "rowIndex": start_row,
1373
+ "columnIndex": start_column,
1374
+ },
1375
+ "rowSpan": end_row - start_row + 1,
1376
+ "columnSpan": end_column - start_column + 1,
1377
+ },
1378
+ "tableCellStyle": cell_style,
1379
+ "fields": ",".join(fields),
1380
+ }
1381
+ }]
1382
+
1383
+ result = self.execute(self.service.documents().batchUpdate(
1384
+ documentId=document_id, body={"requests": requests}
1385
+ ))
1386
+
1387
+ output_success(
1388
+ operation="docs.style_table_cell",
1389
+ document_id=document_id,
1390
+ table_index=table_index,
1391
+ range=f"({start_row},{start_column})-({end_row},{end_column})",
1392
+ styling=fields,
1393
+ )
1394
+ return result
1395
+ except HttpError as e:
1396
+ output_error(
1397
+ error_code="API_ERROR",
1398
+ operation="docs.style_table_cell",
1399
+ message=f"Google Docs API error: {e.reason}",
1400
+ )
1401
+ raise SystemExit(ExitCode.API_ERROR)
1402
+
1403
+ def set_column_width(
1404
+ self,
1405
+ document_id: str,
1406
+ table_index: int,
1407
+ column_index: int,
1408
+ width: float,
1409
+ ) -> dict[str, Any]:
1410
+ """Set the width of a table column."""
1411
+ try:
1412
+ tables = self._get_tables(document_id)
1413
+ if table_index >= len(tables):
1414
+ output_error(
1415
+ error_code="INVALID_ARGS",
1416
+ operation="docs.set_column_width",
1417
+ message=f"Table index {table_index} not found",
1418
+ )
1419
+ raise SystemExit(ExitCode.INVALID_ARGS)
1420
+
1421
+ table = tables[table_index]
1422
+ requests = [{
1423
+ "updateTableColumnProperties": {
1424
+ "tableStartLocation": {"index": table["startIndex"]},
1425
+ "columnIndices": [column_index],
1426
+ "tableColumnProperties": {
1427
+ "width": {"magnitude": width, "unit": "PT"},
1428
+ "widthType": "FIXED_WIDTH",
1429
+ },
1430
+ "fields": "width,widthType",
1431
+ }
1432
+ }]
1433
+
1434
+ result = self.execute(self.service.documents().batchUpdate(
1435
+ documentId=document_id, body={"requests": requests}
1436
+ ))
1437
+
1438
+ output_success(
1439
+ operation="docs.set_column_width",
1440
+ document_id=document_id,
1441
+ table_index=table_index,
1442
+ column_index=column_index,
1443
+ width=width,
1444
+ )
1445
+ return result
1446
+ except HttpError as e:
1447
+ output_error(
1448
+ error_code="API_ERROR",
1449
+ operation="docs.set_column_width",
1450
+ message=f"Google Docs API error: {e.reason}",
1451
+ )
1452
+ raise SystemExit(ExitCode.API_ERROR)
1453
+
1454
+ def set_table_column_widths(
1455
+ self,
1456
+ document_id: str,
1457
+ table_index: int,
1458
+ column_widths: dict[int, float],
1459
+ ) -> dict[str, Any]:
1460
+ """Set widths for multiple columns in a table with a single API call.
1461
+
1462
+ Args:
1463
+ document_id: The document ID.
1464
+ table_index: The table index (0-based).
1465
+ column_widths: Dict mapping column index to width in points.
1466
+ Example: {0: 70, 1: 90, 2: 170}
1467
+ """
1468
+ try:
1469
+ tables = self._get_tables(document_id)
1470
+ if table_index >= len(tables):
1471
+ output_error(
1472
+ error_code="INVALID_ARGS",
1473
+ operation="docs.set_table_column_widths",
1474
+ message=f"Table index {table_index} not found",
1475
+ )
1476
+ raise SystemExit(ExitCode.INVALID_ARGS)
1477
+
1478
+ if not column_widths:
1479
+ output_error(
1480
+ error_code="INVALID_ARGS",
1481
+ operation="docs.set_table_column_widths",
1482
+ message="No column widths provided",
1483
+ )
1484
+ raise SystemExit(ExitCode.INVALID_ARGS)
1485
+
1486
+ table = tables[table_index]
1487
+
1488
+ # Build one request per column, all in single batch
1489
+ requests = []
1490
+ for col_index, width in column_widths.items():
1491
+ requests.append({
1492
+ "updateTableColumnProperties": {
1493
+ "tableStartLocation": {"index": table["startIndex"]},
1494
+ "columnIndices": [col_index],
1495
+ "tableColumnProperties": {
1496
+ "width": {"magnitude": width, "unit": "PT"},
1497
+ "widthType": "FIXED_WIDTH",
1498
+ },
1499
+ "fields": "width,widthType",
1500
+ }
1501
+ })
1502
+
1503
+ result = self.execute(self.service.documents().batchUpdate(
1504
+ documentId=document_id, body={"requests": requests}
1505
+ ))
1506
+
1507
+ output_success(
1508
+ operation="docs.set_table_column_widths",
1509
+ document_id=document_id,
1510
+ table_index=table_index,
1511
+ columns_updated=len(column_widths),
1512
+ column_widths=column_widths,
1513
+ )
1514
+ return result
1515
+ except HttpError as e:
1516
+ output_error(
1517
+ error_code="API_ERROR",
1518
+ operation="docs.set_table_column_widths",
1519
+ message=f"Google Docs API error: {e.reason}",
1520
+ )
1521
+ raise SystemExit(ExitCode.API_ERROR)
1522
+
1523
+ def pin_table_header(
1524
+ self,
1525
+ document_id: str,
1526
+ table_index: int,
1527
+ rows_to_pin: int = 1,
1528
+ ) -> dict[str, Any]:
1529
+ """Pin header rows in a table (they repeat on each page)."""
1530
+ try:
1531
+ tables = self._get_tables(document_id)
1532
+ if table_index >= len(tables):
1533
+ output_error(
1534
+ error_code="INVALID_ARGS",
1535
+ operation="docs.pin_table_header",
1536
+ message=f"Table index {table_index} not found",
1537
+ )
1538
+ raise SystemExit(ExitCode.INVALID_ARGS)
1539
+
1540
+ table = tables[table_index]
1541
+ requests = [{
1542
+ "pinTableHeaderRows": {
1543
+ "tableStartLocation": {"index": table["startIndex"]},
1544
+ "pinnedHeaderRowsCount": rows_to_pin,
1545
+ }
1546
+ }]
1547
+
1548
+ result = self.execute(self.service.documents().batchUpdate(
1549
+ documentId=document_id, body={"requests": requests}
1550
+ ))
1551
+
1552
+ output_success(
1553
+ operation="docs.pin_table_header",
1554
+ document_id=document_id,
1555
+ table_index=table_index,
1556
+ rows_pinned=rows_to_pin,
1557
+ )
1558
+ return result
1559
+ except HttpError as e:
1560
+ output_error(
1561
+ error_code="API_ERROR",
1562
+ operation="docs.pin_table_header",
1563
+ message=f"Google Docs API error: {e.reason}",
1564
+ )
1565
+ raise SystemExit(ExitCode.API_ERROR)
1566
+
1567
+ def list_tables(self, document_id: str) -> dict[str, Any]:
1568
+ """List all tables in the document with their properties."""
1569
+ try:
1570
+ tables = self._get_tables(document_id)
1571
+ table_info = []
1572
+ for i, t in enumerate(tables):
1573
+ table_info.append({
1574
+ "index": i,
1575
+ "rows": t["rows"],
1576
+ "columns": t["columns"],
1577
+ "startIndex": t["startIndex"],
1578
+ "endIndex": t["endIndex"],
1579
+ })
1580
+
1581
+ output_success(
1582
+ operation="docs.list_tables",
1583
+ document_id=document_id,
1584
+ table_count=len(tables),
1585
+ tables=table_info,
1586
+ )
1587
+ return {"tables": table_info}
1588
+ except HttpError as e:
1589
+ output_error(
1590
+ error_code="API_ERROR",
1591
+ operation="docs.list_tables",
1592
+ message=f"Google Docs API error: {e.reason}",
1593
+ )
1594
+ raise SystemExit(ExitCode.API_ERROR)
1595
+
1596
+ # =========================================================================
1597
+ # PARAGRAPH STYLE OPERATIONS
1598
+ # =========================================================================
1599
+
1600
+ def format_paragraph(
1601
+ self,
1602
+ document_id: str,
1603
+ start_index: int,
1604
+ end_index: int,
1605
+ alignment: str | None = None,
1606
+ named_style: str | None = None,
1607
+ line_spacing: float | None = None,
1608
+ space_above: float | None = None,
1609
+ space_below: float | None = None,
1610
+ indent_first_line: float | None = None,
1611
+ indent_start: float | None = None,
1612
+ indent_end: float | None = None,
1613
+ keep_lines_together: bool | None = None,
1614
+ keep_with_next: bool | None = None,
1615
+ shading_color: str | None = None,
1616
+ ) -> dict[str, Any]:
1617
+ """Apply paragraph formatting to a range.
1618
+
1619
+ Args:
1620
+ alignment: START, CENTER, END, or JUSTIFIED
1621
+ named_style: NORMAL_TEXT, TITLE, SUBTITLE, HEADING_1 through HEADING_6
1622
+ line_spacing: Line spacing as percentage (e.g., 100 for single, 200 for double)
1623
+ space_above/below: Space in points
1624
+ indent_*: Indentation in points
1625
+ shading_color: Background color for paragraph (hex)
1626
+ """
1627
+ try:
1628
+ from gws.utils.colors import parse_hex_color
1629
+
1630
+ paragraph_style: dict[str, Any] = {}
1631
+ fields = []
1632
+
1633
+ if alignment is not None:
1634
+ paragraph_style["alignment"] = alignment.upper()
1635
+ fields.append("alignment")
1636
+
1637
+ if named_style is not None:
1638
+ paragraph_style["namedStyleType"] = named_style.upper()
1639
+ fields.append("namedStyleType")
1640
+
1641
+ if line_spacing is not None:
1642
+ paragraph_style["lineSpacing"] = line_spacing
1643
+ fields.append("lineSpacing")
1644
+
1645
+ if space_above is not None:
1646
+ paragraph_style["spaceAbove"] = {"magnitude": space_above, "unit": "PT"}
1647
+ fields.append("spaceAbove")
1648
+
1649
+ if space_below is not None:
1650
+ paragraph_style["spaceBelow"] = {"magnitude": space_below, "unit": "PT"}
1651
+ fields.append("spaceBelow")
1652
+
1653
+ if indent_first_line is not None:
1654
+ paragraph_style["indentFirstLine"] = {"magnitude": indent_first_line, "unit": "PT"}
1655
+ fields.append("indentFirstLine")
1656
+
1657
+ if indent_start is not None:
1658
+ paragraph_style["indentStart"] = {"magnitude": indent_start, "unit": "PT"}
1659
+ fields.append("indentStart")
1660
+
1661
+ if indent_end is not None:
1662
+ paragraph_style["indentEnd"] = {"magnitude": indent_end, "unit": "PT"}
1663
+ fields.append("indentEnd")
1664
+
1665
+ if keep_lines_together is not None:
1666
+ paragraph_style["keepLinesTogether"] = keep_lines_together
1667
+ fields.append("keepLinesTogether")
1668
+
1669
+ if keep_with_next is not None:
1670
+ paragraph_style["keepWithNext"] = keep_with_next
1671
+ fields.append("keepWithNext")
1672
+
1673
+ if shading_color is not None:
1674
+ rgb = parse_hex_color(shading_color)
1675
+ paragraph_style["shading"] = {"backgroundColor": {"color": {"rgbColor": rgb}}}
1676
+ fields.append("shading")
1677
+
1678
+ if not fields:
1679
+ output_error(
1680
+ error_code="INVALID_ARGS",
1681
+ operation="docs.format_paragraph",
1682
+ message="At least one formatting option required",
1683
+ )
1684
+ raise SystemExit(ExitCode.INVALID_ARGS)
1685
+
1686
+ requests = [{
1687
+ "updateParagraphStyle": {
1688
+ "range": {
1689
+ "startIndex": start_index,
1690
+ "endIndex": end_index,
1691
+ },
1692
+ "paragraphStyle": paragraph_style,
1693
+ "fields": ",".join(fields),
1694
+ }
1695
+ }]
1696
+
1697
+ result = self.execute(self.service.documents().batchUpdate(
1698
+ documentId=document_id, body={"requests": requests}
1699
+ ))
1700
+
1701
+ output_success(
1702
+ operation="docs.format_paragraph",
1703
+ document_id=document_id,
1704
+ start_index=start_index,
1705
+ end_index=end_index,
1706
+ formatting=fields,
1707
+ )
1708
+ return result
1709
+ except HttpError as e:
1710
+ output_error(
1711
+ error_code="API_ERROR",
1712
+ operation="docs.format_paragraph",
1713
+ message=f"Google Docs API error: {e.reason}",
1714
+ )
1715
+ raise SystemExit(ExitCode.API_ERROR)
1716
+
1717
+ def set_paragraph_border(
1718
+ self,
1719
+ document_id: str,
1720
+ start_index: int,
1721
+ end_index: int,
1722
+ color: str = "#000000",
1723
+ width: float = 1.0,
1724
+ top: bool = False,
1725
+ bottom: bool = False,
1726
+ left: bool = False,
1727
+ right: bool = False,
1728
+ between: bool = False,
1729
+ ) -> dict[str, Any]:
1730
+ """Add borders to paragraphs."""
1731
+ try:
1732
+ from gws.utils.colors import parse_hex_color
1733
+
1734
+ rgb = parse_hex_color(color)
1735
+ border_style = {
1736
+ "color": {"color": {"rgbColor": rgb}},
1737
+ "width": {"magnitude": width, "unit": "PT"},
1738
+ "padding": {"magnitude": 6.0, "unit": "PT"},
1739
+ "dashStyle": "SOLID",
1740
+ }
1741
+
1742
+ paragraph_style: dict[str, Any] = {}
1743
+ fields = []
1744
+
1745
+ if top:
1746
+ paragraph_style["borderTop"] = border_style
1747
+ fields.append("borderTop")
1748
+ if bottom:
1749
+ paragraph_style["borderBottom"] = border_style
1750
+ fields.append("borderBottom")
1751
+ if left:
1752
+ paragraph_style["borderLeft"] = border_style
1753
+ fields.append("borderLeft")
1754
+ if right:
1755
+ paragraph_style["borderRight"] = border_style
1756
+ fields.append("borderRight")
1757
+ if between:
1758
+ paragraph_style["borderBetween"] = border_style
1759
+ fields.append("borderBetween")
1760
+
1761
+ if not fields:
1762
+ output_error(
1763
+ error_code="INVALID_ARGS",
1764
+ operation="docs.set_paragraph_border",
1765
+ message="At least one border side must be specified",
1766
+ )
1767
+ raise SystemExit(ExitCode.INVALID_ARGS)
1768
+
1769
+ requests = [{
1770
+ "updateParagraphStyle": {
1771
+ "range": {
1772
+ "startIndex": start_index,
1773
+ "endIndex": end_index,
1774
+ },
1775
+ "paragraphStyle": paragraph_style,
1776
+ "fields": ",".join(fields),
1777
+ }
1778
+ }]
1779
+
1780
+ result = self.execute(self.service.documents().batchUpdate(
1781
+ documentId=document_id, body={"requests": requests}
1782
+ ))
1783
+
1784
+ output_success(
1785
+ operation="docs.set_paragraph_border",
1786
+ document_id=document_id,
1787
+ start_index=start_index,
1788
+ end_index=end_index,
1789
+ borders=fields,
1790
+ )
1791
+ return result
1792
+ except HttpError as e:
1793
+ output_error(
1794
+ error_code="API_ERROR",
1795
+ operation="docs.set_paragraph_border",
1796
+ message=f"Google Docs API error: {e.reason}",
1797
+ )
1798
+ raise SystemExit(ExitCode.API_ERROR)
1799
+
1800
+ # =========================================================================
1801
+ # EXTENDED TEXT STYLE OPERATIONS (Phase 3)
1802
+ # =========================================================================
1803
+
1804
+ def format_text_extended(
1805
+ self,
1806
+ document_id: str,
1807
+ start_index: int,
1808
+ end_index: int,
1809
+ bold: bool | None = None,
1810
+ italic: bool | None = None,
1811
+ underline: bool | None = None,
1812
+ strikethrough: bool | None = None,
1813
+ small_caps: bool | None = None,
1814
+ font_family: str | None = None,
1815
+ font_weight: int | None = None,
1816
+ font_size: int | None = None,
1817
+ foreground_color: str | None = None,
1818
+ background_color: str | None = None,
1819
+ baseline_offset: str | None = None,
1820
+ link_url: str | None = None,
1821
+ ) -> dict[str, Any]:
1822
+ """Apply extended text formatting.
1823
+
1824
+ Args:
1825
+ baseline_offset: NONE, SUPERSCRIPT, or SUBSCRIPT
1826
+ font_weight: 100-900 in increments of 100 (400=normal, 700=bold)
1827
+ """
1828
+ try:
1829
+ from gws.utils.colors import parse_hex_color
1830
+
1831
+ text_style: dict[str, Any] = {}
1832
+ fields = []
1833
+
1834
+ if bold is not None:
1835
+ text_style["bold"] = bold
1836
+ fields.append("bold")
1837
+ if italic is not None:
1838
+ text_style["italic"] = italic
1839
+ fields.append("italic")
1840
+ if underline is not None:
1841
+ text_style["underline"] = underline
1842
+ fields.append("underline")
1843
+ if strikethrough is not None:
1844
+ text_style["strikethrough"] = strikethrough
1845
+ fields.append("strikethrough")
1846
+ if small_caps is not None:
1847
+ text_style["smallCaps"] = small_caps
1848
+ fields.append("smallCaps")
1849
+
1850
+ if font_family is not None or font_weight is not None:
1851
+ weighted_font: dict[str, Any] = {}
1852
+ if font_family is not None:
1853
+ weighted_font["fontFamily"] = font_family
1854
+ if font_weight is not None:
1855
+ weighted_font["weight"] = font_weight
1856
+ text_style["weightedFontFamily"] = weighted_font
1857
+ fields.append("weightedFontFamily")
1858
+
1859
+ if font_size is not None:
1860
+ text_style["fontSize"] = {"magnitude": font_size, "unit": "PT"}
1861
+ fields.append("fontSize")
1862
+
1863
+ if foreground_color is not None:
1864
+ rgb = parse_hex_color(foreground_color)
1865
+ text_style["foregroundColor"] = {"color": {"rgbColor": rgb}}
1866
+ fields.append("foregroundColor")
1867
+
1868
+ if background_color is not None:
1869
+ rgb = parse_hex_color(background_color)
1870
+ text_style["backgroundColor"] = {"color": {"rgbColor": rgb}}
1871
+ fields.append("backgroundColor")
1872
+
1873
+ if baseline_offset is not None:
1874
+ text_style["baselineOffset"] = baseline_offset.upper()
1875
+ fields.append("baselineOffset")
1876
+
1877
+ if link_url is not None:
1878
+ text_style["link"] = {"url": link_url}
1879
+ fields.append("link")
1880
+
1881
+ if not fields:
1882
+ output_error(
1883
+ error_code="INVALID_ARGS",
1884
+ operation="docs.format_text_extended",
1885
+ message="At least one formatting option required",
1886
+ )
1887
+ raise SystemExit(ExitCode.INVALID_ARGS)
1888
+
1889
+ requests = [{
1890
+ "updateTextStyle": {
1891
+ "range": {
1892
+ "startIndex": start_index,
1893
+ "endIndex": end_index,
1894
+ },
1895
+ "textStyle": text_style,
1896
+ "fields": ",".join(fields),
1897
+ }
1898
+ }]
1899
+
1900
+ result = self.execute(self.service.documents().batchUpdate(
1901
+ documentId=document_id, body={"requests": requests}
1902
+ ))
1903
+
1904
+ output_success(
1905
+ operation="docs.format_text_extended",
1906
+ document_id=document_id,
1907
+ start_index=start_index,
1908
+ end_index=end_index,
1909
+ formatting=fields,
1910
+ )
1911
+ return result
1912
+ except HttpError as e:
1913
+ output_error(
1914
+ error_code="API_ERROR",
1915
+ operation="docs.format_text_extended",
1916
+ message=f"Google Docs API error: {e.reason}",
1917
+ )
1918
+ raise SystemExit(ExitCode.API_ERROR)
1919
+
1920
+ def insert_link(
1921
+ self,
1922
+ document_id: str,
1923
+ start_index: int,
1924
+ end_index: int,
1925
+ url: str,
1926
+ ) -> dict[str, Any]:
1927
+ """Add a hyperlink to existing text."""
1928
+ try:
1929
+ requests = [{
1930
+ "updateTextStyle": {
1931
+ "range": {
1932
+ "startIndex": start_index,
1933
+ "endIndex": end_index,
1934
+ },
1935
+ "textStyle": {"link": {"url": url}},
1936
+ "fields": "link",
1937
+ }
1938
+ }]
1939
+
1940
+ result = self.execute(self.service.documents().batchUpdate(
1941
+ documentId=document_id, body={"requests": requests}
1942
+ ))
1943
+
1944
+ output_success(
1945
+ operation="docs.insert_link",
1946
+ document_id=document_id,
1947
+ start_index=start_index,
1948
+ end_index=end_index,
1949
+ url=url,
1950
+ )
1951
+ return result
1952
+ except HttpError as e:
1953
+ output_error(
1954
+ error_code="API_ERROR",
1955
+ operation="docs.insert_link",
1956
+ message=f"Google Docs API error: {e.reason}",
1957
+ )
1958
+ raise SystemExit(ExitCode.API_ERROR)
1959
+
1960
+ # =========================================================================
1961
+ # HEADER/FOOTER OPERATIONS (Phase 4)
1962
+ # =========================================================================
1963
+
1964
+ def create_header(
1965
+ self,
1966
+ document_id: str,
1967
+ header_type: str = "DEFAULT",
1968
+ ) -> dict[str, Any]:
1969
+ """Create a document header.
1970
+
1971
+ Args:
1972
+ header_type: DEFAULT or FIRST_PAGE_HEADER
1973
+ """
1974
+ try:
1975
+ requests = [{
1976
+ "createHeader": {
1977
+ "type": header_type.upper(),
1978
+ "sectionBreakLocation": {"index": 0},
1979
+ }
1980
+ }]
1981
+
1982
+ result = self.execute(self.service.documents().batchUpdate(
1983
+ documentId=document_id, body={"requests": requests}
1984
+ ))
1985
+
1986
+ header_id = result.get("replies", [{}])[0].get("createHeader", {}).get("headerId")
1987
+
1988
+ output_success(
1989
+ operation="docs.create_header",
1990
+ document_id=document_id,
1991
+ header_id=header_id,
1992
+ header_type=header_type,
1993
+ )
1994
+ return result
1995
+ except HttpError as e:
1996
+ output_error(
1997
+ error_code="API_ERROR",
1998
+ operation="docs.create_header",
1999
+ message=f"Google Docs API error: {e.reason}",
2000
+ )
2001
+ raise SystemExit(ExitCode.API_ERROR)
2002
+
2003
+ def create_footer(
2004
+ self,
2005
+ document_id: str,
2006
+ footer_type: str = "DEFAULT",
2007
+ ) -> dict[str, Any]:
2008
+ """Create a document footer.
2009
+
2010
+ Args:
2011
+ footer_type: DEFAULT or FIRST_PAGE_FOOTER
2012
+ """
2013
+ try:
2014
+ requests = [{
2015
+ "createFooter": {
2016
+ "type": footer_type.upper(),
2017
+ "sectionBreakLocation": {"index": 0},
2018
+ }
2019
+ }]
2020
+
2021
+ result = self.execute(self.service.documents().batchUpdate(
2022
+ documentId=document_id, body={"requests": requests}
2023
+ ))
2024
+
2025
+ footer_id = result.get("replies", [{}])[0].get("createFooter", {}).get("footerId")
2026
+
2027
+ output_success(
2028
+ operation="docs.create_footer",
2029
+ document_id=document_id,
2030
+ footer_id=footer_id,
2031
+ footer_type=footer_type,
2032
+ )
2033
+ return result
2034
+ except HttpError as e:
2035
+ output_error(
2036
+ error_code="API_ERROR",
2037
+ operation="docs.create_footer",
2038
+ message=f"Google Docs API error: {e.reason}",
2039
+ )
2040
+ raise SystemExit(ExitCode.API_ERROR)
2041
+
2042
+ def delete_header(self, document_id: str, header_id: str) -> dict[str, Any]:
2043
+ """Delete a document header."""
2044
+ try:
2045
+ requests = [{"deleteHeader": {"headerId": header_id}}]
2046
+
2047
+ result = self.execute(self.service.documents().batchUpdate(
2048
+ documentId=document_id, body={"requests": requests}
2049
+ ))
2050
+
2051
+ output_success(
2052
+ operation="docs.delete_header",
2053
+ document_id=document_id,
2054
+ header_id=header_id,
2055
+ )
2056
+ return result
2057
+ except HttpError as e:
2058
+ output_error(
2059
+ error_code="API_ERROR",
2060
+ operation="docs.delete_header",
2061
+ message=f"Google Docs API error: {e.reason}",
2062
+ )
2063
+ raise SystemExit(ExitCode.API_ERROR)
2064
+
2065
+ def delete_footer(self, document_id: str, footer_id: str) -> dict[str, Any]:
2066
+ """Delete a document footer."""
2067
+ try:
2068
+ requests = [{"deleteFooter": {"footerId": footer_id}}]
2069
+
2070
+ result = self.execute(self.service.documents().batchUpdate(
2071
+ documentId=document_id, body={"requests": requests}
2072
+ ))
2073
+
2074
+ output_success(
2075
+ operation="docs.delete_footer",
2076
+ document_id=document_id,
2077
+ footer_id=footer_id,
2078
+ )
2079
+ return result
2080
+ except HttpError as e:
2081
+ output_error(
2082
+ error_code="API_ERROR",
2083
+ operation="docs.delete_footer",
2084
+ message=f"Google Docs API error: {e.reason}",
2085
+ )
2086
+ raise SystemExit(ExitCode.API_ERROR)
2087
+
2088
+ def get_headers_footers(self, document_id: str) -> dict[str, Any]:
2089
+ """Get all headers and footers in the document."""
2090
+ try:
2091
+ doc = self.execute(self.service.documents().get(documentId=document_id))
2092
+ headers = doc.get("headers", {})
2093
+ footers = doc.get("footers", {})
2094
+
2095
+ header_info = []
2096
+ for hid, header in headers.items():
2097
+ content = self._extract_text(header.get("content", []))
2098
+ header_info.append({
2099
+ "id": hid,
2100
+ "content": content[:200] if content else "",
2101
+ })
2102
+
2103
+ footer_info = []
2104
+ for fid, footer in footers.items():
2105
+ content = self._extract_text(footer.get("content", []))
2106
+ footer_info.append({
2107
+ "id": fid,
2108
+ "content": content[:200] if content else "",
2109
+ })
2110
+
2111
+ output_success(
2112
+ operation="docs.get_headers_footers",
2113
+ document_id=document_id,
2114
+ headers=header_info,
2115
+ footers=footer_info,
2116
+ )
2117
+ return {"headers": header_info, "footers": footer_info}
2118
+ except HttpError as e:
2119
+ output_error(
2120
+ error_code="API_ERROR",
2121
+ operation="docs.get_headers_footers",
2122
+ message=f"Google Docs API error: {e.reason}",
2123
+ )
2124
+ raise SystemExit(ExitCode.API_ERROR)
2125
+
2126
+ def insert_text_in_segment(
2127
+ self,
2128
+ document_id: str,
2129
+ segment_id: str,
2130
+ text: str,
2131
+ index: int = 0,
2132
+ ) -> dict[str, Any]:
2133
+ """Insert text into a header or footer segment."""
2134
+ try:
2135
+ requests = [{
2136
+ "insertText": {
2137
+ "location": {
2138
+ "segmentId": segment_id,
2139
+ "index": index,
2140
+ },
2141
+ "text": text,
2142
+ }
2143
+ }]
2144
+
2145
+ result = self.execute(self.service.documents().batchUpdate(
2146
+ documentId=document_id, body={"requests": requests}
2147
+ ))
2148
+
2149
+ output_success(
2150
+ operation="docs.insert_text_in_segment",
2151
+ document_id=document_id,
2152
+ segment_id=segment_id,
2153
+ index=index,
2154
+ text_length=len(text),
2155
+ )
2156
+ return result
2157
+ except HttpError as e:
2158
+ output_error(
2159
+ error_code="API_ERROR",
2160
+ operation="docs.insert_text_in_segment",
2161
+ message=f"Google Docs API error: {e.reason}",
2162
+ )
2163
+ raise SystemExit(ExitCode.API_ERROR)
2164
+
2165
+ # =========================================================================
2166
+ # LIST/BULLET OPERATIONS (Phase 5)
2167
+ # =========================================================================
2168
+
2169
+ def create_bullets(
2170
+ self,
2171
+ document_id: str,
2172
+ start_index: int,
2173
+ end_index: int,
2174
+ preset: str = "BULLET_DISC_CIRCLE_SQUARE",
2175
+ ) -> dict[str, Any]:
2176
+ """Create a bulleted list.
2177
+
2178
+ Presets: BULLET_DISC_CIRCLE_SQUARE, BULLET_DIAMONDX_ARROW3D_SQUARE,
2179
+ BULLET_CHECKBOX, BULLET_ARROW_DIAMOND_DISC,
2180
+ BULLET_STAR_CIRCLE_SQUARE, BULLET_ARROW3D_CIRCLE_SQUARE,
2181
+ BULLET_LEFTTRIANGLE_DIAMOND_DISC
2182
+ """
2183
+ try:
2184
+ requests = [{
2185
+ "createParagraphBullets": {
2186
+ "range": {
2187
+ "startIndex": start_index,
2188
+ "endIndex": end_index,
2189
+ },
2190
+ "bulletPreset": preset.upper(),
2191
+ }
2192
+ }]
2193
+
2194
+ result = self.execute(self.service.documents().batchUpdate(
2195
+ documentId=document_id, body={"requests": requests}
2196
+ ))
2197
+
2198
+ output_success(
2199
+ operation="docs.create_bullets",
2200
+ document_id=document_id,
2201
+ start_index=start_index,
2202
+ end_index=end_index,
2203
+ preset=preset,
2204
+ )
2205
+ return result
2206
+ except HttpError as e:
2207
+ output_error(
2208
+ error_code="API_ERROR",
2209
+ operation="docs.create_bullets",
2210
+ message=f"Google Docs API error: {e.reason}",
2211
+ )
2212
+ raise SystemExit(ExitCode.API_ERROR)
2213
+
2214
+ def create_numbered_list(
2215
+ self,
2216
+ document_id: str,
2217
+ start_index: int,
2218
+ end_index: int,
2219
+ preset: str = "NUMBERED_DECIMAL_NESTED",
2220
+ ) -> dict[str, Any]:
2221
+ """Create a numbered list.
2222
+
2223
+ Presets: NUMBERED_DECIMAL_NESTED, NUMBERED_DECIMAL_ALPHA_ROMAN,
2224
+ NUMBERED_DECIMAL_ALPHA_ROMAN_PARENS, NUMBERED_DECIMAL_PARENTHESIS,
2225
+ NUMBERED_UPPERALPHA_ALPHA_ROMAN, NUMBERED_UPPERROMAN_UPPERALPHA_DECIMAL,
2226
+ NUMBERED_ZERODECIMAL_ALPHA_ROMAN
2227
+ """
2228
+ try:
2229
+ requests = [{
2230
+ "createParagraphBullets": {
2231
+ "range": {
2232
+ "startIndex": start_index,
2233
+ "endIndex": end_index,
2234
+ },
2235
+ "bulletPreset": preset.upper(),
2236
+ }
2237
+ }]
2238
+
2239
+ result = self.execute(self.service.documents().batchUpdate(
2240
+ documentId=document_id, body={"requests": requests}
2241
+ ))
2242
+
2243
+ output_success(
2244
+ operation="docs.create_numbered_list",
2245
+ document_id=document_id,
2246
+ start_index=start_index,
2247
+ end_index=end_index,
2248
+ preset=preset,
2249
+ )
2250
+ return result
2251
+ except HttpError as e:
2252
+ output_error(
2253
+ error_code="API_ERROR",
2254
+ operation="docs.create_numbered_list",
2255
+ message=f"Google Docs API error: {e.reason}",
2256
+ )
2257
+ raise SystemExit(ExitCode.API_ERROR)
2258
+
2259
+ def remove_bullets(
2260
+ self,
2261
+ document_id: str,
2262
+ start_index: int,
2263
+ end_index: int,
2264
+ ) -> dict[str, Any]:
2265
+ """Remove bullets/numbering from paragraphs."""
2266
+ try:
2267
+ requests = [{
2268
+ "deleteParagraphBullets": {
2269
+ "range": {
2270
+ "startIndex": start_index,
2271
+ "endIndex": end_index,
2272
+ },
2273
+ }
2274
+ }]
2275
+
2276
+ result = self.execute(self.service.documents().batchUpdate(
2277
+ documentId=document_id, body={"requests": requests}
2278
+ ))
2279
+
2280
+ output_success(
2281
+ operation="docs.remove_bullets",
2282
+ document_id=document_id,
2283
+ start_index=start_index,
2284
+ end_index=end_index,
2285
+ )
2286
+ return result
2287
+ except HttpError as e:
2288
+ output_error(
2289
+ error_code="API_ERROR",
2290
+ operation="docs.remove_bullets",
2291
+ message=f"Google Docs API error: {e.reason}",
2292
+ )
2293
+ raise SystemExit(ExitCode.API_ERROR)
2294
+
2295
+ # =========================================================================
2296
+ # SECTION AND DOCUMENT STYLE OPERATIONS (Phase 6)
2297
+ # =========================================================================
2298
+
2299
+ def insert_section_break(
2300
+ self,
2301
+ document_id: str,
2302
+ index: int,
2303
+ break_type: str = "NEXT_PAGE",
2304
+ ) -> dict[str, Any]:
2305
+ """Insert a section break.
2306
+
2307
+ Args:
2308
+ break_type: NEXT_PAGE or CONTINUOUS
2309
+ """
2310
+ try:
2311
+ requests = [{
2312
+ "insertSectionBreak": {
2313
+ "location": {"index": index},
2314
+ "sectionType": break_type.upper(),
2315
+ }
2316
+ }]
2317
+
2318
+ result = self.execute(self.service.documents().batchUpdate(
2319
+ documentId=document_id, body={"requests": requests}
2320
+ ))
2321
+
2322
+ output_success(
2323
+ operation="docs.insert_section_break",
2324
+ document_id=document_id,
2325
+ index=index,
2326
+ break_type=break_type,
2327
+ )
2328
+ return result
2329
+ except HttpError as e:
2330
+ output_error(
2331
+ error_code="API_ERROR",
2332
+ operation="docs.insert_section_break",
2333
+ message=f"Google Docs API error: {e.reason}",
2334
+ )
2335
+ raise SystemExit(ExitCode.API_ERROR)
2336
+
2337
+ def update_document_style(
2338
+ self,
2339
+ document_id: str,
2340
+ margin_top: float | None = None,
2341
+ margin_bottom: float | None = None,
2342
+ margin_left: float | None = None,
2343
+ margin_right: float | None = None,
2344
+ page_width: float | None = None,
2345
+ page_height: float | None = None,
2346
+ use_first_page_header_footer: bool | None = None,
2347
+ ) -> dict[str, Any]:
2348
+ """Update document-level style (margins, page size).
2349
+
2350
+ All measurements in points (72 points = 1 inch).
2351
+ Default US Letter: 612 x 792 points.
2352
+ """
2353
+ try:
2354
+ doc_style: dict[str, Any] = {}
2355
+ fields = []
2356
+
2357
+ if margin_top is not None:
2358
+ doc_style["marginTop"] = {"magnitude": margin_top, "unit": "PT"}
2359
+ fields.append("marginTop")
2360
+ if margin_bottom is not None:
2361
+ doc_style["marginBottom"] = {"magnitude": margin_bottom, "unit": "PT"}
2362
+ fields.append("marginBottom")
2363
+ if margin_left is not None:
2364
+ doc_style["marginLeft"] = {"magnitude": margin_left, "unit": "PT"}
2365
+ fields.append("marginLeft")
2366
+ if margin_right is not None:
2367
+ doc_style["marginRight"] = {"magnitude": margin_right, "unit": "PT"}
2368
+ fields.append("marginRight")
2369
+
2370
+ if page_width is not None or page_height is not None:
2371
+ page_size: dict[str, Any] = {}
2372
+ if page_width is not None:
2373
+ page_size["width"] = {"magnitude": page_width, "unit": "PT"}
2374
+ if page_height is not None:
2375
+ page_size["height"] = {"magnitude": page_height, "unit": "PT"}
2376
+ doc_style["pageSize"] = page_size
2377
+ fields.append("pageSize")
2378
+
2379
+ if use_first_page_header_footer is not None:
2380
+ doc_style["useFirstPageHeaderFooter"] = use_first_page_header_footer
2381
+ fields.append("useFirstPageHeaderFooter")
2382
+
2383
+ if not fields:
2384
+ output_error(
2385
+ error_code="INVALID_ARGS",
2386
+ operation="docs.update_document_style",
2387
+ message="At least one style option required",
2388
+ )
2389
+ raise SystemExit(ExitCode.INVALID_ARGS)
2390
+
2391
+ requests = [{
2392
+ "updateDocumentStyle": {
2393
+ "documentStyle": doc_style,
2394
+ "fields": ",".join(fields),
2395
+ }
2396
+ }]
2397
+
2398
+ result = self.execute(self.service.documents().batchUpdate(
2399
+ documentId=document_id, body={"requests": requests}
2400
+ ))
2401
+
2402
+ output_success(
2403
+ operation="docs.update_document_style",
2404
+ document_id=document_id,
2405
+ updated_fields=fields,
2406
+ )
2407
+ return result
2408
+ except HttpError as e:
2409
+ output_error(
2410
+ error_code="API_ERROR",
2411
+ operation="docs.update_document_style",
2412
+ message=f"Google Docs API error: {e.reason}",
2413
+ )
2414
+ raise SystemExit(ExitCode.API_ERROR)
2415
+
2416
+ def get_page_format(self, document_id: str) -> dict[str, Any]:
2417
+ """Get the document's page format (PAGES or PAGELESS).
2418
+
2419
+ Args:
2420
+ document_id: The document ID.
2421
+
2422
+ Returns:
2423
+ Dict with page_format and related info.
2424
+ """
2425
+ try:
2426
+ doc = self.execute(self.service.documents().get(documentId=document_id))
2427
+ doc_style = doc.get("documentStyle", {})
2428
+ doc_format = doc_style.get("documentFormat", {})
2429
+ mode = doc_format.get("documentMode", "PAGES")
2430
+
2431
+ result = {
2432
+ "document_id": document_id,
2433
+ "page_format": mode,
2434
+ "is_pageless": mode == "PAGELESS",
2435
+ }
2436
+
2437
+ output_success(operation="docs.get_page_format", **result)
2438
+ return result
2439
+ except HttpError as e:
2440
+ output_error(
2441
+ error_code="API_ERROR",
2442
+ operation="docs.get_page_format",
2443
+ message=f"Google Docs API error: {e.reason}",
2444
+ )
2445
+ raise SystemExit(ExitCode.API_ERROR)
2446
+
2447
+ def set_page_format(
2448
+ self,
2449
+ document_id: str,
2450
+ mode: str,
2451
+ ) -> dict[str, Any]:
2452
+ """Set the document's page format to PAGES or PAGELESS.
2453
+
2454
+ Args:
2455
+ document_id: The document ID.
2456
+ mode: Either "PAGES" or "PAGELESS".
2457
+
2458
+ Note:
2459
+ Switching to PAGELESS will disable headers, footers, page numbers,
2460
+ and other page-specific features. Content remains but these elements
2461
+ become invisible.
2462
+ """
2463
+ mode = mode.upper()
2464
+ if mode not in ("PAGES", "PAGELESS"):
2465
+ output_error(
2466
+ error_code="INVALID_ARGS",
2467
+ operation="docs.set_page_format",
2468
+ message=f"Invalid mode '{mode}'. Must be 'PAGES' or 'PAGELESS'.",
2469
+ )
2470
+ raise SystemExit(ExitCode.INVALID_ARGS)
2471
+
2472
+ try:
2473
+ requests = [{
2474
+ "updateDocumentStyle": {
2475
+ "documentStyle": {
2476
+ "documentFormat": {
2477
+ "documentMode": mode,
2478
+ }
2479
+ },
2480
+ "fields": "documentFormat",
2481
+ }
2482
+ }]
2483
+
2484
+ self.execute(self.service.documents().batchUpdate(
2485
+ documentId=document_id, body={"requests": requests}
2486
+ ))
2487
+
2488
+ result = {
2489
+ "document_id": document_id,
2490
+ "page_format": mode,
2491
+ "is_pageless": mode == "PAGELESS",
2492
+ }
2493
+
2494
+ output_success(operation="docs.set_page_format", **result)
2495
+ return result
2496
+ except HttpError as e:
2497
+ output_error(
2498
+ error_code="API_ERROR",
2499
+ operation="docs.set_page_format",
2500
+ message=f"Google Docs API error: {e.reason}",
2501
+ )
2502
+ raise SystemExit(ExitCode.API_ERROR)
2503
+
2504
+ # =========================================================================
2505
+ # NAMED RANGE OPERATIONS (Phase 7)
2506
+ # =========================================================================
2507
+
2508
+ def create_named_range(
2509
+ self,
2510
+ document_id: str,
2511
+ name: str,
2512
+ start_index: int,
2513
+ end_index: int,
2514
+ ) -> dict[str, Any]:
2515
+ """Create a named range (bookmark) in the document.
2516
+
2517
+ Args:
2518
+ document_id: The document ID.
2519
+ name: Name for the range (must be unique).
2520
+ start_index: Start character index.
2521
+ end_index: End character index.
2522
+ """
2523
+ try:
2524
+ requests = [{
2525
+ "createNamedRange": {
2526
+ "name": name,
2527
+ "range": {
2528
+ "startIndex": start_index,
2529
+ "endIndex": end_index,
2530
+ },
2531
+ }
2532
+ }]
2533
+
2534
+ result = self.execute(self.service.documents().batchUpdate(
2535
+ documentId=document_id, body={"requests": requests}
2536
+ ))
2537
+
2538
+ named_range_id = (
2539
+ result.get("replies", [{}])[0]
2540
+ .get("createNamedRange", {})
2541
+ .get("namedRangeId")
2542
+ )
2543
+
2544
+ output_success(
2545
+ operation="docs.create_named_range",
2546
+ document_id=document_id,
2547
+ name=name,
2548
+ named_range_id=named_range_id,
2549
+ start_index=start_index,
2550
+ end_index=end_index,
2551
+ )
2552
+ return result
2553
+ except HttpError as e:
2554
+ output_error(
2555
+ error_code="API_ERROR",
2556
+ operation="docs.create_named_range",
2557
+ message=f"Google Docs API error: {e.reason}",
2558
+ )
2559
+ raise SystemExit(ExitCode.API_ERROR)
2560
+
2561
+ def delete_named_range(
2562
+ self,
2563
+ document_id: str,
2564
+ name: str | None = None,
2565
+ named_range_id: str | None = None,
2566
+ ) -> dict[str, Any]:
2567
+ """Delete a named range by name or ID.
2568
+
2569
+ Args:
2570
+ document_id: The document ID.
2571
+ name: Name of the range to delete.
2572
+ named_range_id: ID of the range to delete.
2573
+ """
2574
+ try:
2575
+ if not name and not named_range_id:
2576
+ output_error(
2577
+ error_code="INVALID_ARGS",
2578
+ operation="docs.delete_named_range",
2579
+ message="Either name or named_range_id must be provided",
2580
+ )
2581
+ raise SystemExit(ExitCode.INVALID_ARGS)
2582
+
2583
+ request: dict[str, Any] = {"deleteNamedRange": {}}
2584
+ if name:
2585
+ request["deleteNamedRange"]["name"] = name
2586
+ else:
2587
+ request["deleteNamedRange"]["namedRangeId"] = named_range_id
2588
+
2589
+ result = self.execute(self.service.documents().batchUpdate(
2590
+ documentId=document_id, body={"requests": [request]}
2591
+ ))
2592
+
2593
+ output_success(
2594
+ operation="docs.delete_named_range",
2595
+ document_id=document_id,
2596
+ name=name,
2597
+ named_range_id=named_range_id,
2598
+ )
2599
+ return result
2600
+ except HttpError as e:
2601
+ output_error(
2602
+ error_code="API_ERROR",
2603
+ operation="docs.delete_named_range",
2604
+ message=f"Google Docs API error: {e.reason}",
2605
+ )
2606
+ raise SystemExit(ExitCode.API_ERROR)
2607
+
2608
+ def list_named_ranges(self, document_id: str) -> dict[str, Any]:
2609
+ """List all named ranges in the document."""
2610
+ try:
2611
+ doc = self.execute(self.service.documents().get(documentId=document_id))
2612
+ named_ranges = doc.get("namedRanges", {})
2613
+
2614
+ range_info = []
2615
+ for name, data in named_ranges.items():
2616
+ for nr in data.get("namedRanges", []):
2617
+ ranges = nr.get("ranges", [])
2618
+ for r in ranges:
2619
+ range_info.append({
2620
+ "name": name,
2621
+ "id": nr.get("namedRangeId"),
2622
+ "start_index": r.get("startIndex"),
2623
+ "end_index": r.get("endIndex"),
2624
+ })
2625
+
2626
+ output_success(
2627
+ operation="docs.list_named_ranges",
2628
+ document_id=document_id,
2629
+ count=len(range_info),
2630
+ named_ranges=range_info,
2631
+ )
2632
+ return {"named_ranges": range_info}
2633
+ except HttpError as e:
2634
+ output_error(
2635
+ error_code="API_ERROR",
2636
+ operation="docs.list_named_ranges",
2637
+ message=f"Google Docs API error: {e.reason}",
2638
+ )
2639
+ raise SystemExit(ExitCode.API_ERROR)
2640
+
2641
+ # =========================================================================
2642
+ # FOOTNOTE OPERATIONS (Phase 7)
2643
+ # =========================================================================
2644
+
2645
+ def insert_footnote(
2646
+ self,
2647
+ document_id: str,
2648
+ index: int,
2649
+ ) -> dict[str, Any]:
2650
+ """Insert a footnote reference at the specified index.
2651
+
2652
+ Args:
2653
+ document_id: The document ID.
2654
+ index: Character index where to insert the footnote reference.
2655
+ """
2656
+ try:
2657
+ requests = [{
2658
+ "createFootnote": {
2659
+ "location": {"index": index},
2660
+ }
2661
+ }]
2662
+
2663
+ result = self.execute(self.service.documents().batchUpdate(
2664
+ documentId=document_id, body={"requests": requests}
2665
+ ))
2666
+
2667
+ footnote_id = (
2668
+ result.get("replies", [{}])[0]
2669
+ .get("createFootnote", {})
2670
+ .get("footnoteId")
2671
+ )
2672
+
2673
+ output_success(
2674
+ operation="docs.insert_footnote",
2675
+ document_id=document_id,
2676
+ index=index,
2677
+ footnote_id=footnote_id,
2678
+ )
2679
+ return result
2680
+ except HttpError as e:
2681
+ output_error(
2682
+ error_code="API_ERROR",
2683
+ operation="docs.insert_footnote",
2684
+ message=f"Google Docs API error: {e.reason}",
2685
+ )
2686
+ raise SystemExit(ExitCode.API_ERROR)
2687
+
2688
+ def list_footnotes(self, document_id: str) -> dict[str, Any]:
2689
+ """List all footnotes in the document."""
2690
+ try:
2691
+ doc = self.execute(self.service.documents().get(documentId=document_id))
2692
+ footnotes = doc.get("footnotes", {})
2693
+
2694
+ footnote_info = []
2695
+ for fid, footnote in footnotes.items():
2696
+ content = self._extract_text(footnote.get("content", []))
2697
+ footnote_info.append({
2698
+ "id": fid,
2699
+ "content": content[:500] if content else "",
2700
+ })
2701
+
2702
+ output_success(
2703
+ operation="docs.list_footnotes",
2704
+ document_id=document_id,
2705
+ count=len(footnote_info),
2706
+ footnotes=footnote_info,
2707
+ )
2708
+ return {"footnotes": footnote_info}
2709
+ except HttpError as e:
2710
+ output_error(
2711
+ error_code="API_ERROR",
2712
+ operation="docs.list_footnotes",
2713
+ message=f"Google Docs API error: {e.reason}",
2714
+ )
2715
+ raise SystemExit(ExitCode.API_ERROR)
2716
+
2717
+ def delete_footnote_content(
2718
+ self,
2719
+ document_id: str,
2720
+ footnote_id: str,
2721
+ start_index: int,
2722
+ end_index: int,
2723
+ ) -> dict[str, Any]:
2724
+ """Delete content from a footnote.
2725
+
2726
+ Note: Footnotes cannot be entirely deleted, only their content can be modified.
2727
+ """
2728
+ try:
2729
+ requests = [{
2730
+ "deleteContentRange": {
2731
+ "range": {
2732
+ "segmentId": footnote_id,
2733
+ "startIndex": start_index,
2734
+ "endIndex": end_index,
2735
+ }
2736
+ }
2737
+ }]
2738
+
2739
+ result = self.execute(self.service.documents().batchUpdate(
2740
+ documentId=document_id, body={"requests": requests}
2741
+ ))
2742
+
2743
+ output_success(
2744
+ operation="docs.delete_footnote_content",
2745
+ document_id=document_id,
2746
+ footnote_id=footnote_id,
2747
+ start_index=start_index,
2748
+ end_index=end_index,
2749
+ )
2750
+ return result
2751
+ except HttpError as e:
2752
+ output_error(
2753
+ error_code="API_ERROR",
2754
+ operation="docs.delete_footnote_content",
2755
+ message=f"Google Docs API error: {e.reason}",
2756
+ )
2757
+ raise SystemExit(ExitCode.API_ERROR)
2758
+
2759
+ # =========================================================================
2760
+ # SUGGESTION OPERATIONS (Phase 8)
2761
+ # =========================================================================
2762
+
2763
+ def _extract_suggestions_from_content(
2764
+ self, content: list[dict], suggestions: list[dict]
2765
+ ) -> None:
2766
+ """Recursively extract suggestions from document content."""
2767
+ for element in content:
2768
+ if "paragraph" in element:
2769
+ for elem in element["paragraph"].get("elements", []):
2770
+ if "textRun" in elem:
2771
+ text_run = elem["textRun"]
2772
+ text = text_run.get("content", "")
2773
+
2774
+ # Check for suggested insertions
2775
+ insertion_ids = text_run.get("suggestedInsertionIds", [])
2776
+ for sid in insertion_ids:
2777
+ suggestions.append({
2778
+ "type": "insertion",
2779
+ "suggestion_id": sid,
2780
+ "text": text,
2781
+ "start_index": elem.get("startIndex"),
2782
+ "end_index": elem.get("endIndex"),
2783
+ })
2784
+
2785
+ # Check for suggested deletions
2786
+ deletion_ids = text_run.get("suggestedDeletionIds", [])
2787
+ for sid in deletion_ids:
2788
+ suggestions.append({
2789
+ "type": "deletion",
2790
+ "suggestion_id": sid,
2791
+ "text": text,
2792
+ "start_index": elem.get("startIndex"),
2793
+ "end_index": elem.get("endIndex"),
2794
+ })
2795
+
2796
+ # Check for suggested text style changes
2797
+ style_changes = text_run.get("suggestedTextStyleChanges", {})
2798
+ for sid, change in style_changes.items():
2799
+ suggestions.append({
2800
+ "type": "style_change",
2801
+ "suggestion_id": sid,
2802
+ "text": text,
2803
+ "start_index": elem.get("startIndex"),
2804
+ "end_index": elem.get("endIndex"),
2805
+ "style_change": change.get("textStyle", {}),
2806
+ })
2807
+
2808
+ elif "table" in element:
2809
+ for row in element["table"].get("tableRows", []):
2810
+ for cell in row.get("tableCells", []):
2811
+ self._extract_suggestions_from_content(
2812
+ cell.get("content", []), suggestions
2813
+ )
2814
+
2815
+ def get_suggestions(self, document_id: str) -> dict[str, Any]:
2816
+ """Get all pending suggestions (tracked changes) in the document.
2817
+
2818
+ Returns suggestions including insertions, deletions, and style changes
2819
+ made while in "Suggesting" mode.
2820
+ """
2821
+ try:
2822
+ # Get document with suggestions visible to see what's pending
2823
+ doc_with_suggestions = self.execute(self.service.documents().get(
2824
+ documentId=document_id,
2825
+ suggestionsViewMode="SUGGESTIONS_INLINE"
2826
+ ))
2827
+
2828
+ content = doc_with_suggestions.get("body", {}).get("content", [])
2829
+ suggestions: list[dict] = []
2830
+ self._extract_suggestions_from_content(content, suggestions)
2831
+
2832
+ # Group by suggestion ID to consolidate fragments
2833
+ grouped: dict[str, dict] = {}
2834
+ for s in suggestions:
2835
+ sid = s["suggestion_id"]
2836
+ if sid not in grouped:
2837
+ grouped[sid] = {
2838
+ "suggestion_id": sid,
2839
+ "type": s["type"],
2840
+ "fragments": [],
2841
+ }
2842
+ grouped[sid]["fragments"].append({
2843
+ "text": s["text"],
2844
+ "start_index": s["start_index"],
2845
+ "end_index": s["end_index"],
2846
+ "style_change": s.get("style_change"),
2847
+ })
2848
+
2849
+ suggestion_list = list(grouped.values())
2850
+
2851
+ output_success(
2852
+ operation="docs.get_suggestions",
2853
+ document_id=document_id,
2854
+ suggestion_count=len(suggestion_list),
2855
+ suggestions=suggestion_list,
2856
+ )
2857
+ return {"suggestions": suggestion_list}
2858
+ except HttpError as e:
2859
+ output_error(
2860
+ error_code="API_ERROR",
2861
+ operation="docs.get_suggestions",
2862
+ message=f"Google Docs API error: {e.reason}",
2863
+ )
2864
+ raise SystemExit(ExitCode.API_ERROR)
2865
+
2866
+ def get_document_mode(self, document_id: str) -> dict[str, Any]:
2867
+ """Get document's current revision mode and suggestion state.
2868
+
2869
+ Returns information about whether the document has pending suggestions
2870
+ and metadata about the document state.
2871
+ """
2872
+ try:
2873
+ doc = self.execute(self.service.documents().get(documentId=document_id))
2874
+
2875
+ # Check for any suggestions in the document
2876
+ content = doc.get("body", {}).get("content", [])
2877
+ suggestions: list[dict] = []
2878
+ self._extract_suggestions_from_content(content, suggestions)
2879
+
2880
+ has_suggestions = len(suggestions) > 0
2881
+ suggestion_ids = list(set(s["suggestion_id"] for s in suggestions))
2882
+
2883
+ output_success(
2884
+ operation="docs.get_document_mode",
2885
+ document_id=document_id,
2886
+ title=doc.get("title", ""),
2887
+ revision_id=doc.get("revisionId"),
2888
+ has_pending_suggestions=has_suggestions,
2889
+ pending_suggestion_count=len(suggestion_ids),
2890
+ suggestion_ids=suggestion_ids[:10], # Limit output
2891
+ )
2892
+ return {
2893
+ "has_suggestions": has_suggestions,
2894
+ "suggestion_count": len(suggestion_ids),
2895
+ }
2896
+ except HttpError as e:
2897
+ output_error(
2898
+ error_code="API_ERROR",
2899
+ operation="docs.get_document_mode",
2900
+ message=f"Google Docs API error: {e.reason}",
2901
+ )
2902
+ raise SystemExit(ExitCode.API_ERROR)
2903
+
2904
+ def accept_suggestion(
2905
+ self,
2906
+ document_id: str,
2907
+ suggestion_id: str,
2908
+ ) -> dict[str, Any]:
2909
+ """Accept a suggestion (tracked change) in the document.
2910
+
2911
+ Args:
2912
+ document_id: The document ID.
2913
+ suggestion_id: The suggestion ID to accept.
2914
+ """
2915
+ try:
2916
+ requests = [
2917
+ {
2918
+ "acceptSuggestion": {
2919
+ "suggestionId": suggestion_id,
2920
+ }
2921
+ }
2922
+ ]
2923
+
2924
+ result = self.execute(
2925
+ self.service.documents()
2926
+ .batchUpdate(documentId=document_id, body={"requests": requests})
2927
+ )
2928
+
2929
+ output_success(
2930
+ operation="docs.accept_suggestion",
2931
+ document_id=document_id,
2932
+ suggestion_id=suggestion_id,
2933
+ accepted=True,
2934
+ )
2935
+ return result
2936
+ except HttpError as e:
2937
+ if "not found" in str(e.reason).lower():
2938
+ output_error(
2939
+ error_code="NOT_FOUND",
2940
+ operation="docs.accept_suggestion",
2941
+ message=f"Suggestion not found: {suggestion_id}",
2942
+ )
2943
+ raise SystemExit(ExitCode.NOT_FOUND)
2944
+ output_error(
2945
+ error_code="API_ERROR",
2946
+ operation="docs.accept_suggestion",
2947
+ message=f"Google Docs API error: {e.reason}",
2948
+ )
2949
+ raise SystemExit(ExitCode.API_ERROR)
2950
+
2951
+ def reject_suggestion(
2952
+ self,
2953
+ document_id: str,
2954
+ suggestion_id: str,
2955
+ ) -> dict[str, Any]:
2956
+ """Reject a suggestion (tracked change) in the document.
2957
+
2958
+ Args:
2959
+ document_id: The document ID.
2960
+ suggestion_id: The suggestion ID to reject.
2961
+ """
2962
+ try:
2963
+ requests = [
2964
+ {
2965
+ "rejectSuggestion": {
2966
+ "suggestionId": suggestion_id,
2967
+ }
2968
+ }
2969
+ ]
2970
+
2971
+ result = self.execute(
2972
+ self.service.documents()
2973
+ .batchUpdate(documentId=document_id, body={"requests": requests})
2974
+ )
2975
+
2976
+ output_success(
2977
+ operation="docs.reject_suggestion",
2978
+ document_id=document_id,
2979
+ suggestion_id=suggestion_id,
2980
+ rejected=True,
2981
+ )
2982
+ return result
2983
+ except HttpError as e:
2984
+ if "not found" in str(e.reason).lower():
2985
+ output_error(
2986
+ error_code="NOT_FOUND",
2987
+ operation="docs.reject_suggestion",
2988
+ message=f"Suggestion not found: {suggestion_id}",
2989
+ )
2990
+ raise SystemExit(ExitCode.NOT_FOUND)
2991
+ output_error(
2992
+ error_code="API_ERROR",
2993
+ operation="docs.reject_suggestion",
2994
+ message=f"Google Docs API error: {e.reason}",
2995
+ )
2996
+ raise SystemExit(ExitCode.API_ERROR)
2997
+
2998
+ def accept_all_suggestions(
2999
+ self,
3000
+ document_id: str,
3001
+ ) -> dict[str, Any]:
3002
+ """Accept all pending suggestions in the document.
3003
+
3004
+ Args:
3005
+ document_id: The document ID.
3006
+ """
3007
+ try:
3008
+ # First get all suggestions
3009
+ suggestions_result = self.get_suggestions(document_id)
3010
+ suggestions = suggestions_result.get("suggestions", [])
3011
+
3012
+ if not suggestions:
3013
+ output_success(
3014
+ operation="docs.accept_all_suggestions",
3015
+ document_id=document_id,
3016
+ accepted_count=0,
3017
+ message="No pending suggestions to accept",
3018
+ )
3019
+ return {"accepted_count": 0}
3020
+
3021
+ # Build batch request
3022
+ requests = [
3023
+ {"acceptSuggestion": {"suggestionId": s["suggestion_id"]}}
3024
+ for s in suggestions
3025
+ ]
3026
+
3027
+ self.execute(
3028
+ self.service.documents()
3029
+ .batchUpdate(documentId=document_id, body={"requests": requests})
3030
+ )
3031
+
3032
+ output_success(
3033
+ operation="docs.accept_all_suggestions",
3034
+ document_id=document_id,
3035
+ accepted_count=len(suggestions),
3036
+ )
3037
+ return {"accepted_count": len(suggestions)}
3038
+ except HttpError as e:
3039
+ output_error(
3040
+ error_code="API_ERROR",
3041
+ operation="docs.accept_all_suggestions",
3042
+ message=f"Google Docs API error: {e.reason}",
3043
+ )
3044
+ raise SystemExit(ExitCode.API_ERROR)
3045
+
3046
+ def reject_all_suggestions(
3047
+ self,
3048
+ document_id: str,
3049
+ ) -> dict[str, Any]:
3050
+ """Reject all pending suggestions in the document.
3051
+
3052
+ Args:
3053
+ document_id: The document ID.
3054
+ """
3055
+ try:
3056
+ # First get all suggestions
3057
+ suggestions_result = self.get_suggestions(document_id)
3058
+ suggestions = suggestions_result.get("suggestions", [])
3059
+
3060
+ if not suggestions:
3061
+ output_success(
3062
+ operation="docs.reject_all_suggestions",
3063
+ document_id=document_id,
3064
+ rejected_count=0,
3065
+ message="No pending suggestions to reject",
3066
+ )
3067
+ return {"rejected_count": 0}
3068
+
3069
+ # Build batch request
3070
+ requests = [
3071
+ {"rejectSuggestion": {"suggestionId": s["suggestion_id"]}}
3072
+ for s in suggestions
3073
+ ]
3074
+
3075
+ self.execute(
3076
+ self.service.documents()
3077
+ .batchUpdate(documentId=document_id, body={"requests": requests})
3078
+ )
3079
+
3080
+ output_success(
3081
+ operation="docs.reject_all_suggestions",
3082
+ document_id=document_id,
3083
+ rejected_count=len(suggestions),
3084
+ )
3085
+ return {"rejected_count": len(suggestions)}
3086
+ except HttpError as e:
3087
+ output_error(
3088
+ error_code="API_ERROR",
3089
+ operation="docs.reject_all_suggestions",
3090
+ message=f"Google Docs API error: {e.reason}",
3091
+ )
3092
+ raise SystemExit(ExitCode.API_ERROR)
3093
+
3094
+ # =========================================================================
3095
+ # MARKDOWN INSERTION OPERATIONS
3096
+ # =========================================================================
3097
+
3098
+ def insert_markdown(
3099
+ self,
3100
+ document_id: str,
3101
+ markdown_content: str,
3102
+ index: int = 1,
3103
+ tab_id: str | None = None,
3104
+ ) -> dict[str, Any]:
3105
+ """Insert markdown content into an existing document.
3106
+
3107
+ Leverages Google's native markdown parsing by:
3108
+ 1. Creating a temporary document from the markdown
3109
+ 2. Reading its formatted content
3110
+ 3. Inserting the content (with formatting) at the specified position
3111
+ 4. Deleting the temporary document
3112
+
3113
+ Args:
3114
+ document_id: The target document ID.
3115
+ markdown_content: Markdown text to insert.
3116
+ index: Character index where to insert (default: 1, start of document).
3117
+ tab_id: Optional tab ID for documents with multiple tabs.
3118
+
3119
+ Returns:
3120
+ Dict with insertion details.
3121
+ """
3122
+ from googleapiclient.http import MediaIoBaseUpload
3123
+ import io
3124
+
3125
+ temp_doc_id = None
3126
+
3127
+ try:
3128
+ # Step 1: Create a temporary Google Doc from the markdown
3129
+ markdown_bytes = markdown_content.encode("utf-8")
3130
+ media = MediaIoBaseUpload(
3131
+ io.BytesIO(markdown_bytes),
3132
+ mimetype="text/markdown",
3133
+ resumable=True,
3134
+ )
3135
+
3136
+ temp_file = self.execute(
3137
+ self.drive_service.files()
3138
+ .create(
3139
+ body={
3140
+ "name": "_temp_markdown_insert",
3141
+ "mimeType": "application/vnd.google-apps.document",
3142
+ },
3143
+ media_body=media,
3144
+ fields="id",
3145
+ )
3146
+ )
3147
+ temp_doc_id = temp_file["id"]
3148
+
3149
+ # Step 2: Read the structured content from the temp doc
3150
+ temp_doc = self.execute(
3151
+ self.service.documents()
3152
+ .get(documentId=temp_doc_id, includeTabsContent=True)
3153
+ )
3154
+
3155
+ # Get the body content from the temp doc
3156
+ temp_content = self._get_tab_content(temp_doc, None)
3157
+
3158
+ # Step 3: Build insert requests from the temp doc content
3159
+ requests = self._build_insert_requests_from_content(
3160
+ temp_content, index, tab_id
3161
+ )
3162
+
3163
+ if not requests:
3164
+ output_error(
3165
+ error_code="EMPTY_CONTENT",
3166
+ operation="docs.insert_markdown",
3167
+ message="No content to insert from markdown.",
3168
+ )
3169
+ raise SystemExit(ExitCode.INVALID_ARGS)
3170
+
3171
+ # Step 4: Execute the insert requests on the target document
3172
+ self.execute(self.service.documents().batchUpdate(
3173
+ documentId=document_id, body={"requests": requests}
3174
+ ))
3175
+
3176
+ # Calculate inserted length for reporting
3177
+ inserted_text = self._extract_text_from_content(temp_content)
3178
+ inserted_length = len(inserted_text)
3179
+
3180
+ result = {
3181
+ "document_id": document_id,
3182
+ "inserted_at_index": index,
3183
+ "inserted_length": inserted_length,
3184
+ }
3185
+ if tab_id:
3186
+ result["tab_id"] = tab_id
3187
+
3188
+ output_success(operation="docs.insert_markdown", **result)
3189
+ return result
3190
+
3191
+ except HttpError as e:
3192
+ output_error(
3193
+ error_code="API_ERROR",
3194
+ operation="docs.insert_markdown",
3195
+ message=f"Google Docs API error: {e.reason}",
3196
+ )
3197
+ raise SystemExit(ExitCode.API_ERROR)
3198
+ finally:
3199
+ # Step 5: Clean up - delete the temporary document
3200
+ if temp_doc_id:
3201
+ try:
3202
+ self.execute(self.drive_service.files().delete(fileId=temp_doc_id))
3203
+ except Exception:
3204
+ pass # Ignore cleanup errors
3205
+
3206
+ def _build_insert_requests_from_content(
3207
+ self,
3208
+ content: list[dict],
3209
+ target_index: int,
3210
+ tab_id: str | None = None,
3211
+ ) -> list[dict]:
3212
+ """Build batchUpdate requests to insert content at a target position.
3213
+
3214
+ Processes content elements and generates insertText and formatting requests.
3215
+ """
3216
+ requests: list[dict] = []
3217
+
3218
+ # Extract all text and formatting info
3219
+ text_parts: list[dict] = []
3220
+
3221
+ for element in content:
3222
+ if "paragraph" not in element:
3223
+ continue
3224
+
3225
+ para = element["paragraph"]
3226
+ para_elements = para.get("elements", [])
3227
+
3228
+ for pe in para_elements:
3229
+ if "textRun" not in pe:
3230
+ continue
3231
+
3232
+ text_run = pe["textRun"]
3233
+ text = text_run.get("content", "")
3234
+ style = text_run.get("textStyle", {})
3235
+
3236
+ if text:
3237
+ text_parts.append({
3238
+ "text": text,
3239
+ "style": style,
3240
+ })
3241
+
3242
+ if not text_parts:
3243
+ return []
3244
+
3245
+ # Combine all text for a single insert
3246
+ full_text = "".join(tp["text"] for tp in text_parts)
3247
+
3248
+ # Don't insert if it's just a single newline (empty doc)
3249
+ if full_text.strip() == "":
3250
+ return []
3251
+
3252
+ # Build the insert location
3253
+ location: dict[str, Any] = {"index": target_index}
3254
+ if tab_id:
3255
+ location["tabId"] = tab_id
3256
+
3257
+ # Insert all the text at once
3258
+ requests.append({
3259
+ "insertText": {
3260
+ "location": location,
3261
+ "text": full_text,
3262
+ }
3263
+ })
3264
+
3265
+ # Now apply formatting for each text part
3266
+ current_index = target_index
3267
+ for tp in text_parts:
3268
+ text = tp["text"]
3269
+ style = tp["style"]
3270
+ text_len = len(text)
3271
+
3272
+ if text_len == 0:
3273
+ continue
3274
+
3275
+ # Build text style update if there's any formatting
3276
+ style_updates: dict[str, Any] = {}
3277
+ fields: list[str] = []
3278
+
3279
+ if style.get("bold"):
3280
+ style_updates["bold"] = True
3281
+ fields.append("bold")
3282
+
3283
+ if style.get("italic"):
3284
+ style_updates["italic"] = True
3285
+ fields.append("italic")
3286
+
3287
+ if style.get("underline"):
3288
+ style_updates["underline"] = True
3289
+ fields.append("underline")
3290
+
3291
+ if style.get("strikethrough"):
3292
+ style_updates["strikethrough"] = True
3293
+ fields.append("strikethrough")
3294
+
3295
+ if style.get("link"):
3296
+ style_updates["link"] = style["link"]
3297
+ fields.append("link")
3298
+
3299
+ if style.get("foregroundColor"):
3300
+ style_updates["foregroundColor"] = style["foregroundColor"]
3301
+ fields.append("foregroundColor")
3302
+
3303
+ if style.get("backgroundColor"):
3304
+ style_updates["backgroundColor"] = style["backgroundColor"]
3305
+ fields.append("backgroundColor")
3306
+
3307
+ if style.get("fontSize"):
3308
+ style_updates["fontSize"] = style["fontSize"]
3309
+ fields.append("fontSize")
3310
+
3311
+ if style.get("weightedFontFamily"):
3312
+ style_updates["weightedFontFamily"] = style["weightedFontFamily"]
3313
+ fields.append("weightedFontFamily")
3314
+
3315
+ if style.get("baselineOffset"):
3316
+ style_updates["baselineOffset"] = style["baselineOffset"]
3317
+ fields.append("baselineOffset")
3318
+
3319
+ if style.get("smallCaps"):
3320
+ style_updates["smallCaps"] = True
3321
+ fields.append("smallCaps")
3322
+
3323
+ # Only add formatting request if there's something to format
3324
+ if fields:
3325
+ range_spec: dict[str, Any] = {
3326
+ "startIndex": current_index,
3327
+ "endIndex": current_index + text_len,
3328
+ }
3329
+ if tab_id:
3330
+ range_spec["tabId"] = tab_id
3331
+
3332
+ requests.append({
3333
+ "updateTextStyle": {
3334
+ "range": range_spec,
3335
+ "textStyle": style_updates,
3336
+ "fields": ",".join(fields),
3337
+ }
3338
+ })
3339
+
3340
+ current_index += text_len
3341
+
3342
+ return requests
3343
+
3344
+ def _extract_text_from_content(self, content: list[dict]) -> str:
3345
+ """Extract plain text from document content elements."""
3346
+ text_parts = []
3347
+ for element in content:
3348
+ if "paragraph" in element:
3349
+ para = element["paragraph"]
3350
+ for pe in para.get("elements", []):
3351
+ if "textRun" in pe:
3352
+ text_parts.append(pe["textRun"].get("content", ""))
3353
+ return "".join(text_parts)
3354
+
3355
+ def find_text(
3356
+ self,
3357
+ document_id: str,
3358
+ search_text: str,
3359
+ tab_id: str | None = None,
3360
+ occurrence: int = 1,
3361
+ ) -> dict[str, Any]:
3362
+ """Find text in document and return its position.
3363
+
3364
+ Args:
3365
+ document_id: The document ID.
3366
+ search_text: Text to search for.
3367
+ tab_id: Optional tab ID to search in.
3368
+ occurrence: Which occurrence to find (1-based, default: 1).
3369
+
3370
+ Returns:
3371
+ Dict with index, end_index, length, and total_occurrences.
3372
+ """
3373
+ try:
3374
+ doc = self.execute(self.service.documents().get(
3375
+ documentId=document_id,
3376
+ includeTabsContent=True,
3377
+ ))
3378
+
3379
+ try:
3380
+ content = self._get_tab_content(doc, tab_id)
3381
+ except ValueError as e:
3382
+ output_error(
3383
+ error_code="NOT_FOUND",
3384
+ operation="docs.find_text",
3385
+ message=str(e),
3386
+ )
3387
+ raise SystemExit(ExitCode.NOT_FOUND)
3388
+
3389
+ # Build text with position tracking
3390
+ text_positions: list[tuple[str, int]] = [] # (text, start_index)
3391
+ for element in content:
3392
+ if "paragraph" in element:
3393
+ para = element["paragraph"]
3394
+ for pe in para.get("elements", []):
3395
+ if "textRun" in pe:
3396
+ start_idx = pe.get("startIndex", 0)
3397
+ text_content = pe["textRun"].get("content", "")
3398
+ text_positions.append((text_content, start_idx))
3399
+
3400
+ # Concatenate all text
3401
+ full_text = "".join(t[0] for t in text_positions)
3402
+
3403
+ # Find all occurrences
3404
+ occurrences = []
3405
+ start = 0
3406
+ while True:
3407
+ idx = full_text.find(search_text, start)
3408
+ if idx == -1:
3409
+ break
3410
+ occurrences.append(idx)
3411
+ start = idx + 1
3412
+
3413
+ if not occurrences:
3414
+ output_error(
3415
+ error_code="NOT_FOUND",
3416
+ operation="docs.find_text",
3417
+ message=f"Text not found: '{search_text}'",
3418
+ )
3419
+ raise SystemExit(ExitCode.NOT_FOUND)
3420
+
3421
+ if occurrence < 1 or occurrence > len(occurrences):
3422
+ output_error(
3423
+ error_code="INVALID_ARGS",
3424
+ operation="docs.find_text",
3425
+ message=f"Occurrence {occurrence} out of range (found {len(occurrences)})",
3426
+ )
3427
+ raise SystemExit(ExitCode.INVALID_ARGS)
3428
+
3429
+ text_offset = occurrences[occurrence - 1]
3430
+
3431
+ # Map text offset to document index
3432
+ # Need to find which element contains this offset and calculate real index
3433
+ current_offset = 0
3434
+ doc_index = 1 # Default to start
3435
+ for text, start_idx in text_positions:
3436
+ if current_offset + len(text) > text_offset:
3437
+ # This element contains our target
3438
+ char_offset = text_offset - current_offset
3439
+ doc_index = start_idx + char_offset
3440
+ break
3441
+ current_offset += len(text)
3442
+
3443
+ result = {
3444
+ "index": doc_index,
3445
+ "end_index": doc_index + len(search_text),
3446
+ "length": len(search_text),
3447
+ "occurrence": occurrence,
3448
+ "total_occurrences": len(occurrences),
3449
+ }
3450
+
3451
+ output_success(
3452
+ operation="docs.find_text",
3453
+ document_id=document_id,
3454
+ search_text=search_text,
3455
+ **result,
3456
+ )
3457
+ return result
3458
+
3459
+ except HttpError as e:
3460
+ output_error(
3461
+ error_code="API_ERROR",
3462
+ operation="docs.find_text",
3463
+ message=f"Google Docs API error: {e.reason}",
3464
+ )
3465
+ raise SystemExit(ExitCode.API_ERROR)
3466
+
3467
+ def insert_image_at_text(
3468
+ self,
3469
+ document_id: str,
3470
+ image_url: str,
3471
+ after_text: str,
3472
+ width: float | None = None,
3473
+ height: float | None = None,
3474
+ tab_id: str | None = None,
3475
+ occurrence: int = 1,
3476
+ ) -> dict[str, Any]:
3477
+ """Insert an image after specified text.
3478
+
3479
+ This is a convenience method that finds the text and inserts
3480
+ the image immediately after it, avoiding paragraph boundary issues.
3481
+
3482
+ Args:
3483
+ document_id: The document ID.
3484
+ image_url: URL of the image to insert.
3485
+ after_text: Text to insert image after.
3486
+ width: Image width in points.
3487
+ height: Image height in points.
3488
+ tab_id: Optional tab ID.
3489
+ occurrence: Which occurrence of text (1-based, default: 1).
3490
+ """
3491
+ # First, find the text position
3492
+ try:
3493
+ position = self.find_text(
3494
+ document_id=document_id,
3495
+ search_text=after_text,
3496
+ tab_id=tab_id,
3497
+ occurrence=occurrence,
3498
+ )
3499
+ except SystemExit:
3500
+ # find_text already output the error
3501
+ raise
3502
+
3503
+ # Insert image at the end of the found text
3504
+ insert_index = position["end_index"]
3505
+
3506
+ # Now insert the image at that position
3507
+ return self.insert_image(
3508
+ document_id=document_id,
3509
+ image_url=image_url,
3510
+ index=insert_index,
3511
+ width=width,
3512
+ height=height,
3513
+ tab_id=tab_id,
3514
+ )
3515
+
3516
+ # =========================================================================
3517
+ # NAMED RANGE CONTENT
3518
+ # =========================================================================
3519
+
3520
+ def replace_named_range_content(
3521
+ self,
3522
+ document_id: str,
3523
+ text: str,
3524
+ named_range_name: str | None = None,
3525
+ named_range_id: str | None = None,
3526
+ ) -> dict[str, Any]:
3527
+ """Replace content within a named range.
3528
+
3529
+ Args:
3530
+ document_id: The document ID.
3531
+ text: The new text to insert.
3532
+ named_range_name: Name of the named range (alternative to ID).
3533
+ named_range_id: ID of the named range (alternative to name).
3534
+ """
3535
+ try:
3536
+ if not named_range_name and not named_range_id:
3537
+ output_error(
3538
+ error_code="INVALID_ARGUMENT",
3539
+ operation="docs.replace_named_range_content",
3540
+ message="Either named_range_name or named_range_id required",
3541
+ )
3542
+ raise SystemExit(ExitCode.INVALID_ARGS)
3543
+
3544
+ request: dict[str, Any] = {
3545
+ "replaceNamedRangeContent": {
3546
+ "text": text,
3547
+ }
3548
+ }
3549
+
3550
+ if named_range_name:
3551
+ request["replaceNamedRangeContent"]["namedRangeName"] = named_range_name
3552
+ elif named_range_id:
3553
+ request["replaceNamedRangeContent"]["namedRangeId"] = named_range_id
3554
+
3555
+ result = self.execute(
3556
+ self.service.documents()
3557
+ .batchUpdate(documentId=document_id, body={"requests": [request]})
3558
+ )
3559
+
3560
+ output_success(
3561
+ operation="docs.replace_named_range_content",
3562
+ document_id=document_id,
3563
+ named_range_name=named_range_name,
3564
+ named_range_id=named_range_id,
3565
+ )
3566
+ return result
3567
+ except HttpError as e:
3568
+ output_error(
3569
+ error_code="API_ERROR",
3570
+ operation="docs.replace_named_range_content",
3571
+ message=f"Google Docs API error: {e.reason}",
3572
+ )
3573
+ raise SystemExit(ExitCode.API_ERROR)
3574
+
3575
+ # =========================================================================
3576
+ # IMAGE REPLACEMENT
3577
+ # =========================================================================
3578
+
3579
+ def replace_image(
3580
+ self,
3581
+ document_id: str,
3582
+ image_object_id: str,
3583
+ uri: str,
3584
+ image_replace_method: str = "CENTER_CROP",
3585
+ ) -> dict[str, Any]:
3586
+ """Replace an existing image with a new one.
3587
+
3588
+ Args:
3589
+ document_id: The document ID.
3590
+ image_object_id: The object ID of the image to replace.
3591
+ uri: URL of the new image.
3592
+ image_replace_method: 'CENTER_CROP' or other replacement method.
3593
+ """
3594
+ try:
3595
+ request = {
3596
+ "replaceImage": {
3597
+ "imageObjectId": image_object_id,
3598
+ "uri": uri,
3599
+ "imageReplaceMethod": image_replace_method,
3600
+ }
3601
+ }
3602
+
3603
+ result = self.execute(
3604
+ self.service.documents()
3605
+ .batchUpdate(documentId=document_id, body={"requests": [request]})
3606
+ )
3607
+
3608
+ output_success(
3609
+ operation="docs.replace_image",
3610
+ document_id=document_id,
3611
+ image_object_id=image_object_id,
3612
+ )
3613
+ return result
3614
+ except HttpError as e:
3615
+ output_error(
3616
+ error_code="API_ERROR",
3617
+ operation="docs.replace_image",
3618
+ message=f"Google Docs API error: {e.reason}",
3619
+ )
3620
+ raise SystemExit(ExitCode.API_ERROR)
3621
+
3622
+ # =========================================================================
3623
+ # POSITIONED OBJECTS
3624
+ # =========================================================================
3625
+
3626
+ def delete_positioned_object(
3627
+ self,
3628
+ document_id: str,
3629
+ object_id: str,
3630
+ tab_id: str | None = None,
3631
+ ) -> dict[str, Any]:
3632
+ """Delete a positioned object (floating image, drawing, etc.).
3633
+
3634
+ Args:
3635
+ document_id: The document ID.
3636
+ object_id: The positioned object ID to delete.
3637
+ tab_id: Optional tab ID for multi-tab documents.
3638
+ """
3639
+ try:
3640
+ request: dict[str, Any] = {
3641
+ "deletePositionedObject": {
3642
+ "objectId": object_id,
3643
+ }
3644
+ }
3645
+
3646
+ if tab_id:
3647
+ request["deletePositionedObject"]["tabId"] = tab_id
3648
+
3649
+ result = self.execute(
3650
+ self.service.documents()
3651
+ .batchUpdate(documentId=document_id, body={"requests": [request]})
3652
+ )
3653
+
3654
+ output_success(
3655
+ operation="docs.delete_positioned_object",
3656
+ document_id=document_id,
3657
+ object_id=object_id,
3658
+ )
3659
+ return result
3660
+ except HttpError as e:
3661
+ if e.resp.status == 404:
3662
+ output_error(
3663
+ error_code="NOT_FOUND",
3664
+ operation="docs.delete_positioned_object",
3665
+ message=f"Positioned object not found: {object_id}",
3666
+ )
3667
+ raise SystemExit(ExitCode.NOT_FOUND)
3668
+ output_error(
3669
+ error_code="API_ERROR",
3670
+ operation="docs.delete_positioned_object",
3671
+ message=f"Google Docs API error: {e.reason}",
3672
+ )
3673
+ raise SystemExit(ExitCode.API_ERROR)
3674
+
3675
+ # =========================================================================
3676
+ # EXPORT OPERATIONS
3677
+ # =========================================================================
3678
+
3679
+ def export(
3680
+ self,
3681
+ document_id: str,
3682
+ output_path: str,
3683
+ fmt: str = "markdown",
3684
+ ) -> dict[str, Any]:
3685
+ """Export a Google Doc to a file.
3686
+
3687
+ Args:
3688
+ document_id: The document ID.
3689
+ output_path: Local path to save the exported file.
3690
+ fmt: Export format name (markdown, pdf, docx, txt, html, rtf, epub, odt)
3691
+ or a raw MIME type.
3692
+ """
3693
+ # Resolve format name to MIME type
3694
+ mime_type = self.EXPORT_FORMATS.get(fmt.lower(), fmt)
3695
+
3696
+ try:
3697
+ request = self.drive_service.files().export_media(
3698
+ fileId=document_id, mimeType=mime_type
3699
+ )
3700
+ fh = io.BytesIO()
3701
+ downloader = MediaIoBaseDownload(fh, request)
3702
+
3703
+ done = False
3704
+ while not done:
3705
+ _, done = downloader.next_chunk()
3706
+
3707
+ Path(output_path).write_bytes(fh.getvalue())
3708
+
3709
+ output_success(
3710
+ operation="docs.export",
3711
+ document_id=document_id,
3712
+ output_path=output_path,
3713
+ format=fmt,
3714
+ mime_type=mime_type,
3715
+ )
3716
+ return {"document_id": document_id, "output_path": output_path}
3717
+ except HttpError as e:
3718
+ output_error(
3719
+ error_code="API_ERROR",
3720
+ operation="docs.export",
3721
+ message=f"Export failed: {e.reason}",
3722
+ )
3723
+ raise SystemExit(ExitCode.API_ERROR)