Coverage for C:\leo.repo\leo-editor\leo\core\leoUndo.py: 72%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1322 statements  

1#@+leo-ver=5-thin 

2#@+node:ekr.20031218072017.3603: * @file leoUndo.py 

3# Suppress all mypy errors (mypy doesn't like g.Bunch). 

4# type: ignore 

5"""Leo's undo/redo manager.""" 

6#@+<< How Leo implements unlimited undo >> 

7#@+node:ekr.20031218072017.2413: ** << How Leo implements unlimited undo >> 

8#@@language rest 

9#@+at 

10# Think of the actions that may be Undone or Redone as a string of beads 

11# (g.Bunches) containing all information needed to undo _and_ redo an operation. 

12# 

13# A bead pointer points to the present bead. Undoing an operation moves the bead 

14# pointer backwards; redoing an operation moves the bead pointer forwards. The 

15# bead pointer points in front of the first bead when Undo is disabled. The bead 

16# pointer points at the last bead when Redo is disabled. 

17# 

18# The Undo command uses the present bead to undo the action, then moves the bead 

19# pointer backwards. The Redo command uses the bead after the present bead to redo 

20# the action, then moves the bead pointer forwards. The list of beads does not 

21# branch; all undoable operations (except the Undo and Redo commands themselves) 

22# delete any beads following the newly created bead. 

23# 

24# New in Leo 4.3: User (client) code should call u.beforeX and u.afterX methods to 

25# create a bead describing the operation that is being performed. (By convention, 

26# the code sets u = c.undoer for undoable operations.) Most u.beforeX methods 

27# return 'undoData' that the client code merely passes to the corresponding 

28# u.afterX method. This data contains the 'before' snapshot. The u.afterX methods 

29# then create a bead containing both the 'before' and 'after' snapshots. 

30# 

31# New in Leo 4.3: u.beforeChangeGroup and u.afterChangeGroup allow multiple calls 

32# to u.beforeX and u.afterX methods to be treated as a single undoable entry. See 

33# the code for the Replace All, Sort, Promote and Demote commands for examples. 

34# u.before/afterChangeGroup substantially reduce the number of u.before/afterX 

35# methods needed. 

36# 

37# New in Leo 4.3: It would be possible for plugins or other code to define their 

38# own u.before/afterX methods. Indeed, u.afterX merely needs to set the 

39# bunch.undoHelper and bunch.redoHelper ivars to the methods used to undo and redo 

40# the operation. See the code for the various u.before/afterX methods for 

41# guidance. 

42# 

43# I first saw this model of unlimited undo in the documentation for Apple's Yellow Box classes. 

44#@-<< How Leo implements unlimited undo >> 

45from leo.core import leoGlobals as g 

46# pylint: disable=unpacking-non-sequence 

47#@+others 

48#@+node:ekr.20150509193222.1: ** u.cmd (decorator) 

49def cmd(name): 

50 """Command decorator for the Undoer class.""" 

51 return g.new_cmd_decorator(name, ['c', 'undoer',]) 

52#@+node:ekr.20031218072017.3605: ** class Undoer 

53class Undoer: 

54 """A class that implements unlimited undo and redo.""" 

55 # pylint: disable=not-an-iterable 

56 # pylint: disable=unsubscriptable-object 

57 # So that ivars can be inited to None rather thatn []. 

58 #@+others 

59 #@+node:ekr.20150509193307.1: *3* u.Birth 

60 #@+node:ekr.20031218072017.3606: *4* u.__init__ 

61 def __init__(self, c): 

62 self.c = c 

63 self.granularity = None # Set in reloadSettings. 

64 self.max_undo_stack_size = c.config.getInt('max-undo-stack-size') or 0 

65 # State ivars... 

66 self.beads = [] # List of undo nodes. 

67 self.bead = -1 # Index of the present bead: -1:len(beads) 

68 self.undoType = "Can't Undo" 

69 # These must be set here, _not_ in clearUndoState. 

70 self.redoMenuLabel = "Can't Redo" 

71 self.undoMenuLabel = "Can't Undo" 

72 self.realRedoMenuLabel = "Can't Redo" 

73 self.realUndoMenuLabel = "Can't Undo" 

74 self.undoing = False # True if executing an Undo command. 

75 self.redoing = False # True if executing a Redo command. 

76 self.per_node_undo = False # True: v may contain undo_info ivar. 

77 # New in 4.2... 

78 self.optionalIvars = [] 

79 # Set the following ivars to keep pylint happy. 

80 self.afterTree = None 

81 self.beforeTree = None 

82 self.children = None 

83 self.deleteMarkedNodesData = None 

84 self.followingSibs = None 

85 self.inHead = None 

86 self.kind = None 

87 self.newBack = None 

88 self.newBody = None 

89 self.newChildren = None 

90 self.newHead = None 

91 self.newIns = None 

92 self.newMarked = None 

93 self.newN = None 

94 self.newP = None 

95 self.newParent = None 

96 self.newParent_v = None 

97 self.newRecentFiles = None 

98 self.newSel = None 

99 self.newTree = None 

100 self.newYScroll = None 

101 self.oldBack = None 

102 self.oldBody = None 

103 self.oldChildren = None 

104 self.oldHead = None 

105 self.oldIns = None 

106 self.oldMarked = None 

107 self.oldN = None 

108 self.oldParent = None 

109 self.oldParent_v = None 

110 self.oldRecentFiles = None 

111 self.oldSel = None 

112 self.oldTree = None 

113 self.oldYScroll = None 

114 self.pasteAsClone = None 

115 self.prevSel = None 

116 self.sortChildren = None 

117 self.verboseUndoGroup = None 

118 self.reloadSettings() 

119 #@+node:ekr.20191213085126.1: *4* u.reloadSettings 

120 def reloadSettings(self): 

121 """Undoer.reloadSettings.""" 

122 c = self.c 

123 self.granularity = c.config.getString('undo-granularity') 

124 if self.granularity: 

125 self.granularity = self.granularity.lower() 

126 if self.granularity not in ('node', 'line', 'word', 'char'): 

127 self.granularity = 'line' 

128 #@+node:ekr.20050416092908.1: *3* u.Internal helpers 

129 #@+node:ekr.20031218072017.3607: *4* u.clearOptionalIvars 

130 def clearOptionalIvars(self): 

131 u = self 

132 u.p = None # The position/node being operated upon for undo and redo. 

133 for ivar in u.optionalIvars: 

134 setattr(u, ivar, None) 

135 #@+node:ekr.20060127052111.1: *4* u.cutStack 

136 def cutStack(self): 

137 u = self 

138 n = u.max_undo_stack_size 

139 if u.bead >= n > 0 and not g.unitTesting: 

140 # Do nothing if we are in the middle of creating a group. 

141 i = len(u.beads) - 1 

142 while i >= 0: 

143 bunch = u.beads[i] 

144 if hasattr(bunch, 'kind') and bunch.kind == 'beforeGroup': 

145 return 

146 i -= 1 

147 # This work regardless of how many items appear after bead n. 

148 # g.trace('Cutting undo stack to %d entries' % (n)) 

149 u.beads = u.beads[-n :] 

150 u.bead = n - 1 

151 if 'undo' in g.app.debug and 'verbose' in g.app.debug: # pragma: no cover 

152 print(f"u.cutStack: {len(u.beads):3}") 

153 #@+node:ekr.20080623083646.10: *4* u.dumpBead 

154 def dumpBead(self, n): # pragma: no cover 

155 u = self 

156 if n < 0 or n >= len(u.beads): 

157 return 'no bead: n = ', n 

158 # bunch = u.beads[n] 

159 result = [] 

160 result.append('-' * 10) 

161 result.append(f"len(u.beads): {len(u.beads)}, n: {n}") 

162 for ivar in ('kind', 'newP', 'newN', 'p', 'oldN', 'undoHelper'): 

163 result.append(f"{ivar} = {getattr(self, ivar)}") 

164 return '\n'.join(result) 

165 

166 def dumpTopBead(self): # pragma: no cover 

167 u = self 

168 n = len(u.beads) 

169 if n > 0: 

170 return self.dumpBead(n - 1) 

171 return '<no top bead>' 

172 #@+node:EKR.20040526150818: *4* u.getBead 

173 def getBead(self, n): 

174 """Set Undoer ivars from the bunch at the top of the undo stack.""" 

175 u = self 

176 if n < 0 or n >= len(u.beads): 

177 return None # pragma: no cover 

178 bunch = u.beads[n] 

179 self.setIvarsFromBunch(bunch) 

180 if 'undo' in g.app.debug: # pragma: no cover 

181 print(f" u.getBead: {n:3} of {len(u.beads)}") 

182 return bunch 

183 #@+node:EKR.20040526150818.1: *4* u.peekBead 

184 def peekBead(self, n): 

185 

186 u = self 

187 if n < 0 or n >= len(u.beads): 

188 return None 

189 return u.beads[n] 

190 #@+node:ekr.20060127113243: *4* u.pushBead 

191 def pushBead(self, bunch): 

192 u = self 

193 # New in 4.4b2: Add this to the group if it is being accumulated. 

194 bunch2 = u.bead >= 0 and u.bead < len(u.beads) and u.beads[u.bead] 

195 if bunch2 and hasattr(bunch2, 'kind') and bunch2.kind == 'beforeGroup': 

196 # Just append the new bunch the group's items. 

197 bunch2.items.append(bunch) 

198 else: 

199 # Push the bunch. 

200 u.bead += 1 

201 u.beads[u.bead:] = [bunch] 

202 # Recalculate the menu labels. 

203 u.setUndoTypes() 

204 if 'undo' in g.app.debug: # pragma: no cover 

205 print(f"u.pushBead: {len(u.beads):3} {bunch.undoType}") 

206 #@+node:ekr.20031218072017.3613: *4* u.redoMenuName, undoMenuName 

207 def redoMenuName(self, name): 

208 if name == "Can't Redo": 

209 return name 

210 return "Redo " + name 

211 

212 def undoMenuName(self, name): 

213 if name == "Can't Undo": 

214 return name 

215 return "Undo " + name 

216 #@+node:ekr.20060127070008: *4* u.setIvarsFromBunch 

217 def setIvarsFromBunch(self, bunch): 

218 u = self 

219 u.clearOptionalIvars() 

220 if False and not g.unitTesting: # Debugging. # pragma: no cover 

221 print('-' * 40) 

222 for key in list(bunch.keys()): 

223 g.trace(f"{key:20} {bunch.get(key)!r}") 

224 print('-' * 20) 

225 if g.unitTesting: # #1694: An ever-present unit test. 

226 val = bunch.get('oldMarked') 

227 assert val in (True, False), f"{val!r} {g.callers()!s}" 

228 # bunch is not a dict, so bunch.keys() is required. 

229 for key in list(bunch.keys()): 

230 val = bunch.get(key) 

231 setattr(u, key, val) 

232 if key not in u.optionalIvars: 

233 u.optionalIvars.append(key) 

234 #@+node:ekr.20031218072017.3614: *4* u.setRedoType 

235 # These routines update both the ivar and the menu label. 

236 

237 def setRedoType(self, theType): 

238 

239 u = self 

240 frame = u.c.frame 

241 if not isinstance(theType, str): # pragma: no cover 

242 g.trace(f"oops: expected string for command, got {theType!r}") 

243 g.trace(g.callers()) 

244 theType = '<unknown>' 

245 menu = frame.menu.getMenu("Edit") 

246 name = u.redoMenuName(theType) 

247 if name != u.redoMenuLabel: 

248 # Update menu using old name. 

249 realLabel = frame.menu.getRealMenuName(name) 

250 if realLabel == name: 

251 underline = -1 if g.match(name, 0, "Can't") else 0 

252 else: 

253 underline = realLabel.find("&") 

254 realLabel = realLabel.replace("&", "") 

255 frame.menu.setMenuLabel( 

256 menu, u.realRedoMenuLabel, realLabel, underline=underline) 

257 u.redoMenuLabel = name 

258 u.realRedoMenuLabel = realLabel 

259 #@+node:ekr.20091221145433.6381: *4* u.setUndoType 

260 def setUndoType(self, theType): 

261 

262 u = self 

263 frame = u.c.frame 

264 if not isinstance(theType, str): 

265 g.trace(f"oops: expected string for command, got {repr(theType)}") 

266 g.trace(g.callers()) 

267 theType = '<unknown>' 

268 menu = frame.menu.getMenu("Edit") 

269 name = u.undoMenuName(theType) 

270 if name != u.undoMenuLabel: 

271 # Update menu using old name. 

272 realLabel = frame.menu.getRealMenuName(name) 

273 if realLabel == name: 

274 underline = -1 if g.match(name, 0, "Can't") else 0 

275 else: 

276 underline = realLabel.find("&") 

277 realLabel = realLabel.replace("&", "") 

278 frame.menu.setMenuLabel( 

279 menu, u.realUndoMenuLabel, realLabel, underline=underline) 

280 u.undoType = theType 

281 u.undoMenuLabel = name 

282 u.realUndoMenuLabel = realLabel 

283 #@+node:ekr.20031218072017.3616: *4* u.setUndoTypes 

284 def setUndoTypes(self): 

285 

286 u = self 

287 # Set the undo type and undo menu label. 

288 bunch = u.peekBead(u.bead) 

289 if bunch: 

290 u.setUndoType(bunch.undoType) 

291 else: 

292 u.setUndoType("Can't Undo") 

293 # Set only the redo menu label. 

294 bunch = u.peekBead(u.bead + 1) 

295 if bunch: 

296 u.setRedoType(bunch.undoType) 

297 else: 

298 u.setRedoType("Can't Redo") 

299 u.cutStack() 

300 #@+node:EKR.20040530121329: *4* u.restoreTree & helpers 

301 def restoreTree(self, treeInfo): 

302 """Use the tree info to restore all VNode data, 

303 including all links.""" 

304 u = self 

305 # This effectively relinks all vnodes. 

306 for v, vInfo in treeInfo: 

307 u.restoreVnodeUndoInfo(vInfo) 

308 #@+node:ekr.20050415170737.2: *5* u.restoreVnodeUndoInfo 

309 def restoreVnodeUndoInfo(self, bunch): 

310 """Restore all ivars saved in the bunch.""" 

311 v = bunch.v 

312 v.statusBits = bunch.statusBits 

313 v.children = bunch.children 

314 v.parents = bunch.parents 

315 uA = bunch.get('unknownAttributes') 

316 if uA is not None: 

317 v.unknownAttributes = uA 

318 v._p_changed = True 

319 #@+node:ekr.20050415170812.2: *5* u.restoreTnodeUndoInfo 

320 def restoreTnodeUndoInfo(self, bunch): 

321 v = bunch.v 

322 v.h = bunch.headString 

323 v.b = bunch.bodyString 

324 v.statusBits = bunch.statusBits 

325 uA = bunch.get('unknownAttributes') 

326 if uA is not None: 

327 v.unknownAttributes = uA 

328 v._p_changed = True 

329 #@+node:EKR.20040528075307: *4* u.saveTree & helpers 

330 def saveTree(self, p, treeInfo=None): 

331 """Return a list of tuples with all info needed to handle a general undo operation.""" 

332 # WARNING: read this before doing anything "clever" 

333 #@+<< about u.saveTree >> 

334 #@+node:EKR.20040530114124: *5* << about u.saveTree >> 

335 #@@language rest 

336 #@+at 

337 # The old code made a free-standing copy of the tree using v.copy and 

338 # t.copy. This looks "elegant" and is WRONG. The problem is that it can 

339 # not handle clones properly, especially when some clones were in the 

340 # "undo" tree and some were not. Moreover, it required complex 

341 # adjustments to t.vnodeLists. 

342 # 

343 # Instead of creating new nodes, the new code creates all information needed 

344 # to properly restore the vnodes. It creates a list of tuples, on tuple for 

345 # each VNode in the tree. Each tuple has the form (v, vnodeInfo), where 

346 # vnodeInfo is a dict containing all info needed to recreate the nodes. The 

347 # v.createUndoInfoDict method corresponds to the old v.copy method. 

348 # 

349 # Aside: Prior to 4.2 Leo used a scheme that was equivalent to the 

350 # createUndoInfoDict info, but quite a bit uglier. 

351 #@-<< about u.saveTree >> 

352 u = self 

353 topLevel = (treeInfo is None) 

354 if topLevel: 

355 treeInfo = [] 

356 # Add info for p.v. Duplicate info is harmless. 

357 data = (p.v, u.createVnodeUndoInfo(p.v)) 

358 treeInfo.append(data) 

359 # Recursively add info for the subtree. 

360 child = p.firstChild() 

361 while child: 

362 self.saveTree(child, treeInfo) 

363 child = child.next() 

364 return treeInfo 

365 #@+node:ekr.20050415170737.1: *5* u.createVnodeUndoInfo 

366 def createVnodeUndoInfo(self, v): 

367 """Create a bunch containing all info needed to recreate a VNode for undo.""" 

368 bunch = g.Bunch( 

369 v=v, 

370 statusBits=v.statusBits, 

371 parents=v.parents[:], 

372 children=v.children[:], 

373 ) 

374 if hasattr(v, 'unknownAttributes'): 

375 bunch.unknownAttributes = v.unknownAttributes 

376 return bunch 

377 #@+node:ekr.20050525151449: *4* u.trace 

378 def trace(self): # pragma: no cover 

379 ivars = ('kind', 'undoType') 

380 for ivar in ivars: 

381 g.pr(ivar, getattr(self, ivar)) 

382 #@+node:ekr.20050410095424: *4* u.updateMarks 

383 def updateMarks(self, oldOrNew): 

384 """Update dirty and marked bits.""" 

385 u = self 

386 c = u.c 

387 if oldOrNew not in ('new', 'old'): # pragma: no cover 

388 g.trace("can't happen") 

389 return 

390 isOld = oldOrNew == 'old' 

391 marked = u.oldMarked if isOld else u.newMarked 

392 # Note: c.set/clearMarked call a hook. 

393 if marked: 

394 c.setMarked(u.p) 

395 else: 

396 c.clearMarked(u.p) 

397 # Undo/redo always set changed/dirty bits because the file may have been saved. 

398 u.p.setDirty() 

399 u.c.setChanged() 

400 #@+node:ekr.20031218072017.3608: *3* u.Externally visible entries 

401 #@+node:ekr.20050318085432.4: *4* u.afterX... 

402 #@+node:ekr.20201109075104.1: *5* u.afterChangeBody 

403 def afterChangeBody(self, p, command, bunch): 

404 """ 

405 Create an undo node using d created by beforeChangeNode. 

406 

407 *Important*: Before calling this method, caller must: 

408 - Set p.v.b. (Setting p.b would cause a redraw). 

409 - Set the desired selection range and insert point. 

410 - Set the y-scroll position, if desired. 

411 """ 

412 c = self.c 

413 u, w = self, c.frame.body.wrapper 

414 if u.redoing or u.undoing: 

415 return # pragma: no cover 

416 # Set the type & helpers. 

417 bunch.kind = 'body' 

418 bunch.undoType = command 

419 bunch.undoHelper = u.undoChangeBody 

420 bunch.redoHelper = u.redoChangeBody 

421 bunch.newBody = p.b 

422 bunch.newHead = p.h 

423 bunch.newIns = w.getInsertPoint() 

424 bunch.newMarked = p.isMarked() 

425 # Careful: don't use ternary operator. 

426 if w: 

427 bunch.newSel = w.getSelectionRange() 

428 else: 

429 bunch.newSel = 0, 0 # pragma: no cover 

430 bunch.newYScroll = w.getYScrollPosition() if w else 0 

431 u.pushBead(bunch) 

432 # 

433 if g.unitTesting: 

434 assert command.lower() != 'typing', g.callers() 

435 elif command.lower() == 'typing': # pragma: no cover 

436 g.trace( 

437 'Error: undoType should not be "Typing"\n' 

438 'Call u.doTyping instead') 

439 u.updateAfterTyping(p, w) 

440 #@+node:ekr.20050315134017.4: *5* u.afterChangeGroup 

441 def afterChangeGroup(self, p, undoType, reportFlag=False): 

442 """ 

443 Create an undo node for general tree operations using d created by 

444 beforeChangeGroup 

445 """ 

446 u = self 

447 c = self.c 

448 w = c.frame.body.wrapper 

449 if u.redoing or u.undoing: 

450 return # pragma: no cover 

451 bunch = u.beads[u.bead] 

452 if not u.beads: # pragma: no cover 

453 g.trace('oops: empty undo stack.') 

454 return 

455 if bunch.kind == 'beforeGroup': 

456 bunch.kind = 'afterGroup' 

457 else: # pragma: no cover 

458 g.trace(f"oops: expecting beforeGroup, got {bunch.kind}") 

459 # Set the types & helpers. 

460 bunch.kind = 'afterGroup' 

461 bunch.undoType = undoType 

462 # Set helper only for undo: 

463 # The bead pointer will point to an 'beforeGroup' bead for redo. 

464 bunch.undoHelper = u.undoGroup 

465 bunch.redoHelper = u.redoGroup 

466 bunch.newP = p.copy() 

467 bunch.newSel = w.getSelectionRange() 

468 # Tells whether to report the number of separate changes undone/redone. 

469 bunch.reportFlag = reportFlag 

470 if 0: 

471 # Push the bunch. 

472 u.bead += 1 

473 u.beads[u.bead:] = [bunch] 

474 # Recalculate the menu labels. 

475 u.setUndoTypes() 

476 #@+node:ekr.20050315134017.2: *5* u.afterChangeNodeContents 

477 def afterChangeNodeContents(self, p, command, bunch): 

478 """Create an undo node using d created by beforeChangeNode.""" 

479 u = self 

480 c = self.c 

481 w = c.frame.body.wrapper 

482 if u.redoing or u.undoing: 

483 return 

484 # Set the type & helpers. 

485 bunch.kind = 'node' 

486 bunch.undoType = command 

487 bunch.undoHelper = u.undoNodeContents 

488 bunch.redoHelper = u.redoNodeContents 

489 bunch.inHead = False # 2013/08/26 

490 bunch.newBody = p.b 

491 bunch.newHead = p.h 

492 bunch.newMarked = p.isMarked() 

493 # Bug fix 2017/11/12: don't use ternary operator. 

494 if w: 

495 bunch.newSel = w.getSelectionRange() 

496 else: 

497 bunch.newSel = 0, 0 # pragma: no cover 

498 bunch.newYScroll = w.getYScrollPosition() if w else 0 

499 u.pushBead(bunch) 

500 #@+node:ekr.20201107145642.1: *5* u.afterChangeHeadline 

501 def afterChangeHeadline(self, p, command, bunch): 

502 """Create an undo node using d created by beforeChangeHeadline.""" 

503 u = self 

504 if u.redoing or u.undoing: 

505 return # pragma: no cover 

506 # Set the type & helpers. 

507 bunch.kind = 'headline' 

508 bunch.undoType = command 

509 bunch.undoHelper = u.undoChangeHeadline 

510 bunch.redoHelper = u.redoChangeHeadline 

511 bunch.newHead = p.h 

512 u.pushBead(bunch) 

513 

514 afterChangeHead = afterChangeHeadline 

515 #@+node:ekr.20050315134017.3: *5* u.afterChangeTree 

516 def afterChangeTree(self, p, command, bunch): 

517 """Create an undo node for general tree operations using d created by beforeChangeTree""" 

518 u = self 

519 c = self.c 

520 w = c.frame.body.wrapper 

521 if u.redoing or u.undoing: 

522 return # pragma: no cover 

523 # Set the types & helpers. 

524 bunch.kind = 'tree' 

525 bunch.undoType = command 

526 bunch.undoHelper = u.undoTree 

527 bunch.redoHelper = u.redoTree 

528 # Set by beforeChangeTree: changed, oldSel, oldText, oldTree, p 

529 bunch.newSel = w.getSelectionRange() 

530 bunch.newText = w.getAllText() 

531 bunch.newTree = u.saveTree(p) 

532 u.pushBead(bunch) 

533 #@+node:ekr.20050424161505: *5* u.afterClearRecentFiles 

534 def afterClearRecentFiles(self, bunch): 

535 u = self 

536 bunch.newRecentFiles = g.app.config.recentFiles[:] 

537 bunch.undoType = 'Clear Recent Files' 

538 bunch.undoHelper = u.undoClearRecentFiles 

539 bunch.redoHelper = u.redoClearRecentFiles 

540 u.pushBead(bunch) 

541 return bunch 

542 #@+node:ekr.20111006060936.15639: *5* u.afterCloneMarkedNodes 

543 def afterCloneMarkedNodes(self, p): 

544 u = self 

545 if u.redoing or u.undoing: 

546 return 

547 # createCommonBunch sets: 

548 # oldDirty = p.isDirty() 

549 # oldMarked = p.isMarked() 

550 # oldSel = w and w.getSelectionRange() or None 

551 # p = p.copy() 

552 bunch = u.createCommonBunch(p) 

553 # Set types. 

554 bunch.kind = 'clone-marked-nodes' 

555 bunch.undoType = 'clone-marked-nodes' 

556 # Set helpers. 

557 bunch.undoHelper = u.undoCloneMarkedNodes 

558 bunch.redoHelper = u.redoCloneMarkedNodes 

559 bunch.newP = p.next() 

560 bunch.newMarked = p.isMarked() 

561 u.pushBead(bunch) 

562 #@+node:ekr.20160502175451.1: *5* u.afterCopyMarkedNodes 

563 def afterCopyMarkedNodes(self, p): 

564 u = self 

565 if u.redoing or u.undoing: 

566 return 

567 # createCommonBunch sets: 

568 # oldDirty = p.isDirty() 

569 # oldMarked = p.isMarked() 

570 # oldSel = w and w.getSelectionRange() or None 

571 # p = p.copy() 

572 bunch = u.createCommonBunch(p) 

573 # Set types. 

574 bunch.kind = 'copy-marked-nodes' 

575 bunch.undoType = 'copy-marked-nodes' 

576 # Set helpers. 

577 bunch.undoHelper = u.undoCopyMarkedNodes 

578 bunch.redoHelper = u.redoCopyMarkedNodes 

579 bunch.newP = p.next() 

580 bunch.newMarked = p.isMarked() 

581 u.pushBead(bunch) 

582 #@+node:ekr.20050411193627.5: *5* u.afterCloneNode 

583 def afterCloneNode(self, p, command, bunch): 

584 u = self 

585 if u.redoing or u.undoing: 

586 return # pragma: no cover 

587 # Set types & helpers 

588 bunch.kind = 'clone' 

589 bunch.undoType = command 

590 # Set helpers 

591 bunch.undoHelper = u.undoCloneNode 

592 bunch.redoHelper = u.redoCloneNode 

593 bunch.newBack = p.back() # 6/15/05 

594 bunch.newParent = p.parent() # 6/15/05 

595 bunch.newP = p.copy() 

596 bunch.newMarked = p.isMarked() 

597 u.pushBead(bunch) 

598 #@+node:ekr.20050411193627.6: *5* u.afterDehoist 

599 def afterDehoist(self, p, command): 

600 u = self 

601 if u.redoing or u.undoing: 

602 return 

603 bunch = u.createCommonBunch(p) 

604 # Set types & helpers 

605 bunch.kind = 'dehoist' 

606 bunch.undoType = command 

607 # Set helpers 

608 bunch.undoHelper = u.undoDehoistNode 

609 bunch.redoHelper = u.redoDehoistNode 

610 u.pushBead(bunch) 

611 #@+node:ekr.20050411193627.8: *5* u.afterDeleteNode 

612 def afterDeleteNode(self, p, command, bunch): 

613 u = self 

614 if u.redoing or u.undoing: 

615 return 

616 # Set types & helpers 

617 bunch.kind = 'delete' 

618 bunch.undoType = command 

619 # Set helpers 

620 bunch.undoHelper = u.undoDeleteNode 

621 bunch.redoHelper = u.redoDeleteNode 

622 bunch.newP = p.copy() 

623 bunch.newMarked = p.isMarked() 

624 u.pushBead(bunch) 

625 #@+node:ekr.20111005152227.15555: *5* u.afterDeleteMarkedNodes 

626 def afterDeleteMarkedNodes(self, data, p): 

627 u = self 

628 if u.redoing or u.undoing: 

629 return 

630 bunch = u.createCommonBunch(p) 

631 # Set types & helpers 

632 bunch.kind = 'delete-marked-nodes' 

633 bunch.undoType = 'delete-marked-nodes' 

634 # Set helpers 

635 bunch.undoHelper = u.undoDeleteMarkedNodes 

636 bunch.redoHelper = u.redoDeleteMarkedNodes 

637 bunch.newP = p.copy() 

638 bunch.deleteMarkedNodesData = data 

639 bunch.newMarked = p.isMarked() 

640 u.pushBead(bunch) 

641 #@+node:ekr.20080425060424.8: *5* u.afterDemote 

642 def afterDemote(self, p, followingSibs): 

643 """Create an undo node for demote operations.""" 

644 u = self 

645 bunch = u.createCommonBunch(p) 

646 # Set types. 

647 bunch.kind = 'demote' 

648 bunch.undoType = 'Demote' 

649 bunch.undoHelper = u.undoDemote 

650 bunch.redoHelper = u.redoDemote 

651 bunch.followingSibs = followingSibs 

652 # Push the bunch. 

653 u.bead += 1 

654 u.beads[u.bead:] = [bunch] 

655 # Recalculate the menu labels. 

656 u.setUndoTypes() 

657 #@+node:ekr.20050411193627.7: *5* u.afterHoist 

658 def afterHoist(self, p, command): 

659 u = self 

660 if u.redoing or u.undoing: 

661 return # pragma: no cover 

662 bunch = u.createCommonBunch(p) 

663 # Set types & helpers 

664 bunch.kind = 'hoist' 

665 bunch.undoType = command 

666 # Set helpers 

667 bunch.undoHelper = u.undoHoistNode 

668 bunch.redoHelper = u.redoHoistNode 

669 u.pushBead(bunch) 

670 #@+node:ekr.20050411193627.9: *5* u.afterInsertNode 

671 def afterInsertNode(self, p, command, bunch): 

672 u = self 

673 if u.redoing or u.undoing: 

674 return 

675 # Set types & helpers 

676 bunch.kind = 'insert' 

677 bunch.undoType = command 

678 # Set helpers 

679 bunch.undoHelper = u.undoInsertNode 

680 bunch.redoHelper = u.redoInsertNode 

681 bunch.newP = p.copy() 

682 bunch.newBack = p.back() 

683 bunch.newParent = p.parent() 

684 bunch.newMarked = p.isMarked() 

685 if bunch.pasteAsClone: 

686 beforeTree = bunch.beforeTree 

687 afterTree = [] 

688 for bunch2 in beforeTree: 

689 v = bunch2.v 

690 afterTree.append(g.Bunch(v=v, head=v.h[:], body=v.b[:])) 

691 bunch.afterTree = afterTree 

692 u.pushBead(bunch) 

693 #@+node:ekr.20050526124257: *5* u.afterMark 

694 def afterMark(self, p, command, bunch): 

695 """Create an undo node for mark and unmark commands.""" 

696 # 'command' unused, but present for compatibility with similar methods. 

697 u = self 

698 if u.redoing or u.undoing: 

699 return # pragma: no cover 

700 # Set the type & helpers. 

701 bunch.undoHelper = u.undoMark 

702 bunch.redoHelper = u.redoMark 

703 bunch.newMarked = p.isMarked() 

704 u.pushBead(bunch) 

705 #@+node:ekr.20050410110343: *5* u.afterMoveNode 

706 def afterMoveNode(self, p, command, bunch): 

707 u = self 

708 if u.redoing or u.undoing: 

709 return 

710 # Set the types & helpers. 

711 bunch.kind = 'move' 

712 bunch.undoType = command 

713 # Set helper only for undo: 

714 # The bead pointer will point to an 'beforeGroup' bead for redo. 

715 bunch.undoHelper = u.undoMove 

716 bunch.redoHelper = u.redoMove 

717 bunch.newMarked = p.isMarked() 

718 bunch.newN = p.childIndex() 

719 bunch.newParent_v = p._parentVnode() 

720 bunch.newP = p.copy() 

721 u.pushBead(bunch) 

722 #@+node:ekr.20080425060424.12: *5* u.afterPromote 

723 def afterPromote(self, p, children): 

724 """Create an undo node for demote operations.""" 

725 u = self 

726 bunch = u.createCommonBunch(p) 

727 # Set types. 

728 bunch.kind = 'promote' 

729 bunch.undoType = 'Promote' 

730 bunch.undoHelper = u.undoPromote 

731 bunch.redoHelper = u.redoPromote 

732 bunch.children = children 

733 # Push the bunch. 

734 u.bead += 1 

735 u.beads[u.bead:] = [bunch] 

736 # Recalculate the menu labels. 

737 u.setUndoTypes() 

738 #@+node:ekr.20080425060424.2: *5* u.afterSort 

739 def afterSort(self, p, bunch): 

740 """Create an undo node for sort operations""" 

741 u = self 

742 # c = self.c 

743 if u.redoing or u.undoing: 

744 return # pragma: no cover 

745 # Recalculate the menu labels. 

746 u.setUndoTypes() 

747 #@+node:ekr.20050318085432.3: *4* u.beforeX... 

748 #@+node:ekr.20201109074740.1: *5* u.beforeChangeBody 

749 def beforeChangeBody(self, p): 

750 """Return data that gets passed to afterChangeBody.""" 

751 w = self.c.frame.body.wrapper 

752 bunch = self.createCommonBunch(p) # Sets u.oldMarked, u.oldSel, u.p 

753 bunch.oldBody = p.b 

754 bunch.oldHead = p.h 

755 bunch.oldIns = w.getInsertPoint() 

756 bunch.oldYScroll = w.getYScrollPosition() 

757 return bunch 

758 #@+node:ekr.20050315134017.7: *5* u.beforeChangeGroup 

759 def beforeChangeGroup(self, p, command, verboseUndoGroup=True): 

760 """Prepare to undo a group of undoable operations.""" 

761 u = self 

762 bunch = u.createCommonBunch(p) 

763 # Set types. 

764 bunch.kind = 'beforeGroup' 

765 bunch.undoType = command 

766 bunch.verboseUndoGroup = verboseUndoGroup 

767 # Set helper only for redo: 

768 # The bead pointer will point to an 'afterGroup' bead for undo. 

769 bunch.undoHelper = u.undoGroup 

770 bunch.redoHelper = u.redoGroup 

771 bunch.items = [] 

772 # Push the bunch. 

773 u.bead += 1 

774 u.beads[u.bead:] = [bunch] 

775 #@+node:ekr.20201107145859.1: *5* u.beforeChangeHeadline 

776 def beforeChangeHeadline(self, p): 

777 """ 

778 Return data that gets passed to afterChangeNode. 

779 

780 The oldHead kwarg works around a Qt difficulty when changing headlines. 

781 """ 

782 u = self 

783 bunch = u.createCommonBunch(p) 

784 bunch.oldHead = p.h 

785 return bunch 

786 

787 beforeChangeHead = beforeChangeHeadline 

788 #@+node:ekr.20050315133212.2: *5* u.beforeChangeNodeContents 

789 def beforeChangeNodeContents(self, p): 

790 """Return data that gets passed to afterChangeNode.""" 

791 c, u = self.c, self 

792 w = c.frame.body.wrapper 

793 bunch = u.createCommonBunch(p) 

794 bunch.oldBody = p.b 

795 bunch.oldHead = p.h 

796 # #1413: Always restore yScroll if possible. 

797 bunch.oldYScroll = w.getYScrollPosition() if w else 0 

798 return bunch 

799 #@+node:ekr.20050315134017.6: *5* u.beforeChangeTree 

800 def beforeChangeTree(self, p): 

801 u = self 

802 c = u.c 

803 w = c.frame.body.wrapper 

804 bunch = u.createCommonBunch(p) 

805 bunch.oldSel = w.getSelectionRange() 

806 bunch.oldText = w.getAllText() 

807 bunch.oldTree = u.saveTree(p) 

808 return bunch 

809 #@+node:ekr.20050424161505.1: *5* u.beforeClearRecentFiles 

810 def beforeClearRecentFiles(self): 

811 u = self 

812 p = u.c.p 

813 bunch = u.createCommonBunch(p) 

814 bunch.oldRecentFiles = g.app.config.recentFiles[:] 

815 return bunch 

816 #@+node:ekr.20050412080354: *5* u.beforeCloneNode 

817 def beforeCloneNode(self, p): 

818 u = self 

819 bunch = u.createCommonBunch(p) 

820 return bunch 

821 #@+node:ekr.20050411193627.3: *5* u.beforeDeleteNode 

822 def beforeDeleteNode(self, p): 

823 u = self 

824 bunch = u.createCommonBunch(p) 

825 bunch.oldBack = p.back() 

826 bunch.oldParent = p.parent() 

827 return bunch 

828 #@+node:ekr.20050411193627.4: *5* u.beforeInsertNode 

829 def beforeInsertNode(self, p, pasteAsClone=False, copiedBunchList=None): 

830 u = self 

831 if copiedBunchList is None: 

832 copiedBunchList = [] 

833 bunch = u.createCommonBunch(p) 

834 bunch.pasteAsClone = pasteAsClone 

835 if pasteAsClone: 

836 # Save the list of bunched. 

837 bunch.beforeTree = copiedBunchList 

838 return bunch 

839 #@+node:ekr.20050526131252: *5* u.beforeMark 

840 def beforeMark(self, p, command): 

841 u = self 

842 bunch = u.createCommonBunch(p) 

843 bunch.kind = 'mark' 

844 bunch.undoType = command 

845 return bunch 

846 #@+node:ekr.20050410110215: *5* u.beforeMoveNode 

847 def beforeMoveNode(self, p): 

848 u = self 

849 bunch = u.createCommonBunch(p) 

850 bunch.oldN = p.childIndex() 

851 bunch.oldParent_v = p._parentVnode() 

852 return bunch 

853 #@+node:ekr.20080425060424.3: *5* u.beforeSort 

854 def beforeSort(self, p, undoType, oldChildren, newChildren, sortChildren): 

855 """Create an undo node for sort operations.""" 

856 u = self 

857 bunch = u.createCommonBunch(p) 

858 # Set types. 

859 bunch.kind = 'sort' 

860 bunch.undoType = undoType 

861 bunch.undoHelper = u.undoSort 

862 bunch.redoHelper = u.redoSort 

863 bunch.oldChildren = oldChildren 

864 bunch.newChildren = newChildren 

865 bunch.sortChildren = sortChildren # A bool 

866 # Push the bunch. 

867 u.bead += 1 

868 u.beads[u.bead:] = [bunch] 

869 return bunch 

870 #@+node:ekr.20050318085432.2: *5* u.createCommonBunch 

871 def createCommonBunch(self, p): 

872 """Return a bunch containing all common undo info. 

873 This is mostly the info for recreating an empty node at position p.""" 

874 u = self 

875 c = u.c 

876 w = c.frame.body.wrapper 

877 return g.Bunch( 

878 oldMarked=p and p.isMarked(), 

879 oldSel=w and w.getSelectionRange() or None, 

880 p=p and p.copy(), 

881 ) 

882 #@+node:ekr.20031218072017.3610: *4* u.canRedo & canUndo 

883 # Translation does not affect these routines. 

884 

885 def canRedo(self): 

886 u = self 

887 return u.redoMenuLabel != "Can't Redo" 

888 

889 def canUndo(self): 

890 u = self 

891 return u.undoMenuLabel != "Can't Undo" 

892 #@+node:ekr.20031218072017.3609: *4* u.clearUndoState 

893 def clearUndoState(self): 

894 """Clears then entire Undo state. 

895 

896 All non-undoable commands should call this method.""" 

897 u = self 

898 u.clearOptionalIvars() # Do this first. 

899 u.setRedoType("Can't Redo") 

900 u.setUndoType("Can't Undo") 

901 u.beads = [] # List of undo nodes. 

902 u.bead = -1 # Index of the present bead: -1:len(beads) 

903 #@+node:ekr.20031218072017.1490: *4* u.doTyping & helper 

904 def doTyping(self, p, undo_type, oldText, newText, 

905 newInsert=None, oldSel=None, newSel=None, oldYview=None, 

906 ): 

907 """ 

908 Save enough information to undo or redo a typing operation efficiently, 

909 that is, with the proper granularity. 

910 

911 Do nothing when called from the undo/redo logic because the Undo 

912 and Redo commands merely reset the bead pointer. 

913 

914 **Important**: Code should call this method *only* when the user has 

915 actually typed something. Commands should use u.beforeChangeBody and 

916 u.afterChangeBody. 

917 

918 Only qtm.onTextChanged and ec.selfInsertCommand now call this method. 

919 """ 

920 c, u, w = self.c, self, self.c.frame.body.wrapper 

921 # Leo 6.4: undo_type must be 'Typing'. 

922 undo_type = undo_type.capitalize() 

923 assert undo_type == 'Typing', (repr(undo_type), g.callers()) 

924 #@+<< return if there is nothing to do >> 

925 #@+node:ekr.20040324061854: *5* << return if there is nothing to do >> 

926 if u.redoing or u.undoing: 

927 return None # pragma: no cover 

928 if undo_type is None: 

929 return None # pragma: no cover 

930 if undo_type == "Can't Undo": 

931 u.clearUndoState() 

932 u.setUndoTypes() # Must still recalculate the menu labels. 

933 return None # pragma: no cover 

934 if oldText == newText: 

935 u.setUndoTypes() # Must still recalculate the menu labels. 

936 return None # pragma: no cover 

937 #@-<< return if there is nothing to do >> 

938 #@+<< init the undo params >> 

939 #@+node:ekr.20040324061854.1: *5* << init the undo params >> 

940 u.clearOptionalIvars() 

941 # Set the params. 

942 u.undoType = undo_type 

943 u.p = p.copy() 

944 #@-<< init the undo params >> 

945 #@+<< compute leading, middle & trailing lines >> 

946 #@+node:ekr.20031218072017.1491: *5* << compute leading, middle & trailing lines >> 

947 #@+at Incremental undo typing is similar to incremental syntax coloring. We compute 

948 # the number of leading and trailing lines that match, and save both the old and 

949 # new middle lines. NB: the number of old and new middle lines may be different. 

950 #@@c 

951 old_lines = oldText.split('\n') 

952 new_lines = newText.split('\n') 

953 new_len = len(new_lines) 

954 old_len = len(old_lines) 

955 min_len = min(old_len, new_len) 

956 i = 0 

957 while i < min_len: 

958 if old_lines[i] != new_lines[i]: 

959 break 

960 i += 1 

961 leading = i 

962 if leading == new_len: 

963 # This happens when we remove lines from the end. 

964 # The new text is simply the leading lines from the old text. 

965 trailing = 0 

966 else: 

967 i = 0 

968 while i < min_len - leading: 

969 if old_lines[old_len - i - 1] != new_lines[new_len - i - 1]: 

970 break 

971 i += 1 

972 trailing = i 

973 # NB: the number of old and new middle lines may be different. 

974 if trailing == 0: 

975 old_middle_lines = old_lines[leading:] 

976 new_middle_lines = new_lines[leading:] 

977 else: 

978 old_middle_lines = old_lines[leading : -trailing] 

979 new_middle_lines = new_lines[leading : -trailing] 

980 # Remember how many trailing newlines in the old and new text. 

981 i = len(oldText) - 1 

982 old_newlines = 0 

983 while i >= 0 and oldText[i] == '\n': 

984 old_newlines += 1 

985 i -= 1 

986 i = len(newText) - 1 

987 new_newlines = 0 

988 while i >= 0 and newText[i] == '\n': 

989 new_newlines += 1 

990 i -= 1 

991 #@-<< compute leading, middle & trailing lines >> 

992 #@+<< save undo text info >> 

993 #@+node:ekr.20031218072017.1492: *5* << save undo text info >> 

994 u.oldText = None 

995 u.newText = None 

996 u.leading = leading 

997 u.trailing = trailing 

998 u.oldMiddleLines = old_middle_lines 

999 u.newMiddleLines = new_middle_lines 

1000 u.oldNewlines = old_newlines 

1001 u.newNewlines = new_newlines 

1002 #@-<< save undo text info >> 

1003 #@+<< save the selection and scrolling position >> 

1004 #@+node:ekr.20040324061854.2: *5* << save the selection and scrolling position >> 

1005 # Remember the selection. 

1006 u.oldSel = oldSel 

1007 u.newSel = newSel 

1008 # Remember the scrolling position. 

1009 if oldYview: 

1010 u.yview = oldYview 

1011 else: 

1012 u.yview = c.frame.body.wrapper.getYScrollPosition() 

1013 #@-<< save the selection and scrolling position >> 

1014 #@+<< adjust the undo stack, clearing all forward entries >> 

1015 #@+node:ekr.20040324061854.3: *5* << adjust the undo stack, clearing all forward entries >> 

1016 #@+at 

1017 # New in Leo 4.3. Instead of creating a new bead on every character, we 

1018 # may adjust the top bead: 

1019 # word granularity: adjust the top bead if the typing would continue the word. 

1020 # line granularity: adjust the top bead if the typing is on the same line. 

1021 # node granularity: adjust the top bead if the typing is anywhere on the same node. 

1022 #@@c 

1023 granularity = u.granularity 

1024 old_d = u.peekBead(u.bead) 

1025 old_p = old_d and old_d.get('p') 

1026 #@+<< set newBead if we can't share the previous bead >> 

1027 #@+node:ekr.20050125220613: *6* << set newBead if we can't share the previous bead >> 

1028 # Set newBead to True if undo_type is not 'Typing' so that commands that 

1029 # get treated like typing don't get lumped with 'real' typing. 

1030 if ( 

1031 not old_d or not old_p or 

1032 old_p.v != p.v or 

1033 old_d.get('kind') != 'typing' or 

1034 old_d.get('undoType') != 'Typing' or 

1035 undo_type != 'Typing' 

1036 ): 

1037 newBead = True # We can't share the previous node. 

1038 elif granularity == 'char': 

1039 newBead = True # This was the old way. 

1040 elif granularity == 'node': 

1041 newBead = False # Always replace previous bead. 

1042 else: 

1043 assert granularity in ('line', 'word') 

1044 # Replace the previous bead if only the middle lines have changed. 

1045 newBead = ( 

1046 old_d.get('leading', 0) != u.leading or 

1047 old_d.get('trailing', 0) != u.trailing 

1048 ) 

1049 if granularity == 'word' and not newBead: 

1050 # Protect the method that may be changed by the user 

1051 try: 

1052 #@+<< set newBead if the change does not continue a word >> 

1053 #@+node:ekr.20050125203937: *7* << set newBead if the change does not continue a word >> 

1054 # Fix #653: undoer problem: be wary of the ternary operator here. 

1055 old_start = old_end = new_start = new_end = 0 

1056 if oldSel is not None: 

1057 old_start, old_end = oldSel 

1058 if newSel is not None: 

1059 new_start, new_end = newSel 

1060 if u.prevSel is None: 

1061 prev_start, prev_end = 0, 0 

1062 else: 

1063 prev_start, prev_end = u.prevSel 

1064 if old_start != old_end or new_start != new_end: 

1065 # The new and old characters are not contiguous. 

1066 newBead = True 

1067 else: 

1068 # 2011/04/01: Patch by Sam Hartsfield 

1069 old_row, old_col = g.convertPythonIndexToRowCol( 

1070 oldText, old_start) 

1071 new_row, new_col = g.convertPythonIndexToRowCol( 

1072 newText, new_start) 

1073 prev_row, prev_col = g.convertPythonIndexToRowCol( 

1074 oldText, prev_start) 

1075 old_lines = g.splitLines(oldText) 

1076 new_lines = g.splitLines(newText) 

1077 # Recognize backspace, del, etc. as contiguous. 

1078 if old_row != new_row or abs(old_col - new_col) != 1: 

1079 # The new and old characters are not contiguous. 

1080 newBead = True 

1081 elif old_col == 0 or new_col == 0: 

1082 # py-lint: disable=W0511 

1083 # W0511:1362: TODO 

1084 # TODO this is not true, we might as well just have entered a 

1085 # char at the beginning of an existing line 

1086 pass # We have just inserted a line. 

1087 else: 

1088 # 2011/04/01: Patch by Sam Hartsfield 

1089 old_s = old_lines[old_row] 

1090 new_s = new_lines[new_row] 

1091 # New in 4.3b2: 

1092 # Guard against invalid oldSel or newSel params. 

1093 if old_col - 1 >= len(old_s) or new_col - 1 >= len(new_s): 

1094 newBead = True 

1095 else: 

1096 old_ch = old_s[old_col - 1] 

1097 new_ch = new_s[new_col - 1] 

1098 newBead = self.recognizeStartOfTypingWord( 

1099 old_lines, old_row, old_col, old_ch, 

1100 new_lines, new_row, new_col, new_ch, 

1101 prev_row, prev_col) 

1102 #@-<< set newBead if the change does not continue a word >> 

1103 except Exception: 

1104 g.error('Unexpected exception...') 

1105 g.es_exception() 

1106 newBead = True 

1107 #@-<< set newBead if we can't share the previous bead >> 

1108 # Save end selection as new "previous" selection 

1109 u.prevSel = u.newSel 

1110 if newBead: 

1111 # Push params on undo stack, clearing all forward entries. 

1112 bunch = g.Bunch( 

1113 p=p.copy(), 

1114 kind='typing', # lowercase. 

1115 undoType=undo_type, # capitalized. 

1116 undoHelper=u.undoTyping, 

1117 redoHelper=u.redoTyping, 

1118 oldMarked=old_p.isMarked() if old_p else p.isMarked(), # #1694 

1119 oldText=u.oldText, 

1120 oldSel=u.oldSel, 

1121 oldNewlines=u.oldNewlines, 

1122 oldMiddleLines=u.oldMiddleLines, 

1123 ) 

1124 u.pushBead(bunch) 

1125 else: 

1126 bunch = old_d 

1127 bunch.leading = u.leading 

1128 bunch.trailing = u.trailing 

1129 bunch.newMarked = p.isMarked() # #1694 

1130 bunch.newNewlines = u.newNewlines 

1131 bunch.newMiddleLines = u.newMiddleLines 

1132 bunch.newSel = u.newSel 

1133 bunch.newText = u.newText 

1134 bunch.yview = u.yview 

1135 #@-<< adjust the undo stack, clearing all forward entries >> 

1136 if 'undo' in g.app.debug and 'verbose' in g.app.debug: 

1137 print(f"u.doTyping: {len(oldText)} => {len(newText)}") 

1138 if u.per_node_undo: 

1139 u.putIvarsToVnode(p) 

1140 # 

1141 # Finish updating the text. 

1142 p.v.setBodyString(newText) 

1143 u.updateAfterTyping(p, w) 

1144 

1145 # Compatibility 

1146 

1147 setUndoTypingParams = doTyping 

1148 #@+node:ekr.20050126081529: *5* u.recognizeStartOfTypingWord 

1149 def recognizeStartOfTypingWord(self, 

1150 old_lines, old_row, old_col, old_ch, 

1151 new_lines, new_row, new_col, new_ch, 

1152 prev_row, prev_col 

1153 ): 

1154 """ 

1155 A potentially user-modifiable method that should return True if the 

1156 typing indicated by the params starts a new 'word' for the purposes of 

1157 undo with 'word' granularity. 

1158 

1159 u.doTyping calls this method only when the typing could possibly 

1160 continue a previous word. In other words, undo will work safely regardless 

1161 of the value returned here. 

1162 

1163 old_ch is the char at the given (Tk) row, col of old_lines. 

1164 new_ch is the char at the given (Tk) row, col of new_lines. 

1165 

1166 The present code uses only old_ch and new_ch. The other arguments are given 

1167 for use by more sophisticated algorithms. 

1168 """ 

1169 # Start a word if new_ch begins whitespace + word 

1170 new_word_started = not old_ch.isspace() and new_ch.isspace() 

1171 # Start a word if the cursor has been moved since the last change 

1172 moved_cursor = new_row != prev_row or new_col != prev_col + 1 

1173 return new_word_started or moved_cursor 

1174 #@+node:ekr.20031218072017.3611: *4* u.enableMenuItems 

1175 def enableMenuItems(self): 

1176 u = self 

1177 frame = u.c.frame 

1178 menu = frame.menu.getMenu("Edit") 

1179 if menu: 

1180 frame.menu.enableMenu(menu, u.redoMenuLabel, u.canRedo()) 

1181 frame.menu.enableMenu(menu, u.undoMenuLabel, u.canUndo()) 

1182 #@+node:ekr.20110519074734.6094: *4* u.onSelect & helpers 

1183 def onSelect(self, old_p, p): 

1184 

1185 u = self 

1186 if u.per_node_undo: 

1187 if old_p and u.beads: 

1188 u.putIvarsToVnode(old_p) 

1189 u.setIvarsFromVnode(p) 

1190 u.setUndoTypes() 

1191 #@+node:ekr.20110519074734.6096: *5* u.putIvarsToVnode 

1192 def putIvarsToVnode(self, p): 

1193 

1194 u, v = self, p.v 

1195 assert self.per_node_undo 

1196 bunch = g.bunch() 

1197 for key in self.optionalIvars: 

1198 bunch[key] = getattr(u, key) 

1199 # Put these ivars by hand. 

1200 for key in ('bead', 'beads', 'undoType',): 

1201 bunch[key] = getattr(u, key) 

1202 v.undo_info = bunch 

1203 #@+node:ekr.20110519074734.6095: *5* u.setIvarsFromVnode 

1204 def setIvarsFromVnode(self, p): 

1205 u = self 

1206 v = p.v 

1207 assert self.per_node_undo 

1208 u.clearUndoState() 

1209 if hasattr(v, 'undo_info'): 

1210 u.setIvarsFromBunch(v.undo_info) 

1211 #@+node:ekr.20201127035748.1: *4* u.updateAfterTyping 

1212 def updateAfterTyping(self, p, w): 

1213 """ 

1214 Perform all update tasks after changing body text. 

1215 

1216 This is ugly, ad-hoc code, but should be done uniformly. 

1217 """ 

1218 c = self.c 

1219 if g.isTextWrapper(w): 

1220 # An important, ever-present unit test. 

1221 all = w.getAllText() 

1222 if g.unitTesting: 

1223 assert p.b == all, (w, g.callers()) 

1224 elif p.b != all: 

1225 g.trace( 

1226 f"\np.b != w.getAllText() p: {p.h} \n" 

1227 f"w: {w!r} \n{g.callers()}\n") 

1228 # g.printObj(g.splitLines(p.b), tag='p.b') 

1229 # g.printObj(g.splitLines(all), tag='getAllText') 

1230 p.v.insertSpot = ins = w.getInsertPoint() 

1231 # From u.doTyping. 

1232 newSel = w.getSelectionRange() 

1233 if newSel is None: 

1234 p.v.selectionStart, p.v.selectionLength = (ins, 0) 

1235 else: 

1236 i, j = newSel 

1237 p.v.selectionStart, p.v.selectionLength = (i, j - i) 

1238 else: 

1239 if g.unitTesting: 

1240 assert False, f"Not a text wrapper: {g.callers()}" 

1241 g.trace('Not a text wrapper') 

1242 p.v.insertSpot = 0 

1243 p.v.selectionStart, p.v.selectionLength = (0, 0) 

1244 # 

1245 # #1749. 

1246 if p.isDirty(): 

1247 redraw_flag = False 

1248 else: 

1249 p.setDirty() # Do not call p.v.setDirty! 

1250 redraw_flag = True 

1251 if not c.isChanged(): 

1252 c.setChanged() 

1253 # Update editors. 

1254 c.frame.body.updateEditors() 

1255 # Update icons. 

1256 val = p.computeIcon() 

1257 if not hasattr(p.v, "iconVal") or val != p.v.iconVal: 

1258 p.v.iconVal = val 

1259 redraw_flag = True 

1260 # 

1261 # Recolor the body. 

1262 c.frame.scanForTabWidth(p) # Calls frame.setTabWidth() 

1263 c.recolor() 

1264 if redraw_flag: 

1265 c.redraw_after_icons_changed() 

1266 w.setFocus() 

1267 #@+node:ekr.20031218072017.2030: *3* u.redo 

1268 @cmd('redo') 

1269 def redo(self, event=None): 

1270 """Redo the operation undone by the last undo.""" 

1271 c, u = self.c, self 

1272 if not c.p: 

1273 return 

1274 # End editing *before* getting state. 

1275 c.endEditing() 

1276 if not u.canRedo(): 

1277 return 

1278 if not u.getBead(u.bead + 1): 

1279 return 

1280 # 

1281 # Init status. 

1282 u.redoing = True 

1283 u.groupCount = 0 

1284 if u.redoHelper: 

1285 u.redoHelper() 

1286 else: 

1287 g.trace(f"no redo helper for {u.kind} {u.undoType}") 

1288 # 

1289 # Finish. 

1290 c.checkOutline() 

1291 u.update_status() 

1292 u.redoing = False 

1293 u.bead += 1 

1294 u.setUndoTypes() 

1295 #@+node:ekr.20110519074734.6092: *3* u.redo helpers 

1296 #@+node:ekr.20191213085226.1: *4* u.reloadHelper (do nothing) 

1297 def redoHelper(self): 

1298 """The default do-nothing redo helper.""" 

1299 pass 

1300 #@+node:ekr.20201109080732.1: *4* u.redoChangeBody 

1301 def redoChangeBody(self): 

1302 c, u, w = self.c, self, self.c.frame.body.wrapper 

1303 # selectPosition causes recoloring, so don't do this unless needed. 

1304 if c.p != u.p: # #1333. 

1305 c.selectPosition(u.p) 

1306 u.p.setDirty() 

1307 u.p.b = u.newBody 

1308 u.p.h = u.newHead 

1309 # This is required so. Otherwise redraw will revert the change! 

1310 c.frame.tree.setHeadline(u.p, u.newHead) 

1311 if u.newMarked: 

1312 u.p.setMarked() 

1313 else: 

1314 u.p.clearMarked() 

1315 if u.groupCount == 0: 

1316 w.setAllText(u.newBody) 

1317 i, j = u.newSel 

1318 w.setSelectionRange(i, j, insert=u.newIns) 

1319 w.setYScrollPosition(u.newYScroll) 

1320 c.frame.body.recolor(u.p) 

1321 u.updateMarks('new') 

1322 u.p.setDirty() 

1323 #@+node:ekr.20201107150619.1: *4* u.redoChangeHeadline 

1324 def redoChangeHeadline(self): 

1325 c, u = self.c, self 

1326 # selectPosition causes recoloring, so don't do this unless needed. 

1327 if c.p != u.p: # #1333. 

1328 c.selectPosition(u.p) 

1329 u.p.setDirty() 

1330 c.frame.body.recolor(u.p) 

1331 # Restore the headline. 

1332 u.p.initHeadString(u.newHead) 

1333 # This is required so. Otherwise redraw will revert the change! 

1334 c.frame.tree.setHeadline(u.p, u.newHead) 

1335 #@+node:ekr.20050424170219: *4* u.redoClearRecentFiles 

1336 def redoClearRecentFiles(self): 

1337 u = self 

1338 c = u.c 

1339 rf = g.app.recentFilesManager 

1340 rf.setRecentFiles(u.newRecentFiles[:]) 

1341 rf.createRecentFilesMenuItems(c) 

1342 #@+node:ekr.20111005152227.15558: *4* u.redoCloneMarkedNodes 

1343 def redoCloneMarkedNodes(self): 

1344 u = self 

1345 c = u.c 

1346 c.selectPosition(u.p) 

1347 c.cloneMarked() 

1348 u.newP = c.p 

1349 #@+node:ekr.20160502175557.1: *4* u.redoCopyMarkedNodes 

1350 def redoCopyMarkedNodes(self): 

1351 u = self 

1352 c = u.c 

1353 c.selectPosition(u.p) 

1354 c.copyMarked() 

1355 u.newP = c.p 

1356 #@+node:ekr.20050412083057: *4* u.redoCloneNode 

1357 def redoCloneNode(self): 

1358 u = self 

1359 c = u.c 

1360 cc = c.chapterController 

1361 if cc: 

1362 cc.selectChapterByName('main') 

1363 if u.newBack: 

1364 u.newP._linkAfter(u.newBack) 

1365 elif u.newParent: 

1366 u.newP._linkAsNthChild(u.newParent, 0) 

1367 else: 

1368 u.newP._linkAsRoot() 

1369 c.selectPosition(u.newP) 

1370 u.newP.setDirty() 

1371 #@+node:ekr.20111005152227.15559: *4* u.redoDeleteMarkedNodes 

1372 def redoDeleteMarkedNodes(self): 

1373 u = self 

1374 c = u.c 

1375 c.selectPosition(u.p) 

1376 c.deleteMarked() 

1377 c.selectPosition(u.newP) 

1378 #@+node:EKR.20040526072519.2: *4* u.redoDeleteNode 

1379 def redoDeleteNode(self): 

1380 u = self 

1381 c = u.c 

1382 c.selectPosition(u.p) 

1383 c.deleteOutline() 

1384 c.selectPosition(u.newP) 

1385 #@+node:ekr.20080425060424.9: *4* u.redoDemote 

1386 def redoDemote(self): 

1387 u = self 

1388 c = u.c 

1389 parent_v = u.p._parentVnode() 

1390 n = u.p.childIndex() 

1391 # Move the demoted nodes from the old parent to the new parent. 

1392 parent_v.children = parent_v.children[: n + 1] 

1393 u.p.v.children.extend(u.followingSibs) 

1394 # Adjust the parent links of the moved nodes. 

1395 # There is no need to adjust descendant links. 

1396 for v in u.followingSibs: 

1397 v.parents.remove(parent_v) 

1398 v.parents.append(u.p.v) 

1399 u.p.setDirty() 

1400 c.setCurrentPosition(u.p) 

1401 #@+node:ekr.20050318085432.6: *4* u.redoGroup 

1402 def redoGroup(self): 

1403 """Process beads until the matching 'afterGroup' bead is seen.""" 

1404 u = self 

1405 # Remember these values. 

1406 c = u.c 

1407 newSel = u.newSel 

1408 p = u.p.copy() 

1409 u.groupCount += 1 

1410 bunch = u.beads[u.bead + 1] 

1411 count = 0 

1412 if not hasattr(bunch, 'items'): 

1413 g.trace(f"oops: expecting bunch.items. got bunch.kind = {bunch.kind}") 

1414 g.trace(bunch) 

1415 else: 

1416 for z in bunch.items: 

1417 self.setIvarsFromBunch(z) 

1418 if z.redoHelper: 

1419 z.redoHelper() 

1420 count += 1 

1421 else: 

1422 g.trace(f"oops: no redo helper for {u.undoType} {p.h}") 

1423 u.groupCount -= 1 

1424 u.updateMarks('new') # Bug fix: Leo 4.4.6. 

1425 if not g.unitTesting and u.verboseUndoGroup: 

1426 g.es("redo", count, "instances") 

1427 p.setDirty() 

1428 c.selectPosition(p) 

1429 if newSel: 

1430 i, j = newSel 

1431 c.frame.body.wrapper.setSelectionRange(i, j) 

1432 #@+node:ekr.20050412085138.1: *4* u.redoHoistNode & redoDehoistNode 

1433 def redoHoistNode(self): 

1434 c, u = self.c, self 

1435 u.p.setDirty() 

1436 c.selectPosition(u.p) 

1437 c.hoist() 

1438 

1439 def redoDehoistNode(self): 

1440 c, u = self.c, self 

1441 u.p.setDirty() 

1442 c.selectPosition(u.p) 

1443 c.dehoist() 

1444 #@+node:ekr.20050412084532: *4* u.redoInsertNode 

1445 def redoInsertNode(self): 

1446 u = self 

1447 c = u.c 

1448 cc = c.chapterController 

1449 if cc: 

1450 cc.selectChapterByName('main') 

1451 if u.newBack: 

1452 u.newP._linkAfter(u.newBack) 

1453 elif u.newParent: 

1454 u.newP._linkAsNthChild(u.newParent, 0) 

1455 else: 

1456 u.newP._linkAsRoot() 

1457 if u.pasteAsClone: 

1458 for bunch in u.afterTree: 

1459 v = bunch.v 

1460 if u.newP.v == v: 

1461 u.newP.b = bunch.body 

1462 u.newP.h = bunch.head 

1463 else: 

1464 v.setBodyString(bunch.body) 

1465 v.setHeadString(bunch.head) 

1466 u.newP.setDirty() 

1467 c.selectPosition(u.newP) 

1468 #@+node:ekr.20050526125801: *4* u.redoMark 

1469 def redoMark(self): 

1470 u = self 

1471 c = u.c 

1472 u.updateMarks('new') 

1473 if u.groupCount == 0: 

1474 u.p.setDirty() 

1475 c.selectPosition(u.p) 

1476 #@+node:ekr.20050411111847: *4* u.redoMove 

1477 def redoMove(self): 

1478 u = self 

1479 c = u.c 

1480 cc = c.chapterController 

1481 v = u.p.v 

1482 assert u.oldParent_v 

1483 assert u.newParent_v 

1484 assert v 

1485 if cc: 

1486 cc.selectChapterByName('main') 

1487 # Adjust the children arrays of the old parent. 

1488 assert u.oldParent_v.children[u.oldN] == v 

1489 del u.oldParent_v.children[u.oldN] 

1490 u.oldParent_v.setDirty() 

1491 # Adjust the children array of the new parent. 

1492 parent_v = u.newParent_v 

1493 parent_v.children.insert(u.newN, v) 

1494 v.parents.append(u.newParent_v) 

1495 v.parents.remove(u.oldParent_v) 

1496 u.newParent_v.setDirty() 

1497 # 

1498 u.updateMarks('new') 

1499 u.newP.setDirty() 

1500 c.selectPosition(u.newP) 

1501 #@+node:ekr.20050318085432.7: *4* u.redoNodeContents 

1502 def redoNodeContents(self): 

1503 c, u = self.c, self 

1504 w = c.frame.body.wrapper 

1505 # selectPosition causes recoloring, so don't do this unless needed. 

1506 if c.p != u.p: # #1333. 

1507 c.selectPosition(u.p) 

1508 u.p.setDirty() 

1509 # Restore the body. 

1510 u.p.setBodyString(u.newBody) 

1511 w.setAllText(u.newBody) 

1512 c.frame.body.recolor(u.p) 

1513 # Restore the headline. 

1514 u.p.initHeadString(u.newHead) 

1515 # This is required so. Otherwise redraw will revert the change! 

1516 c.frame.tree.setHeadline(u.p, u.newHead) # New in 4.4b2. 

1517 if u.groupCount == 0 and u.newSel: 

1518 i, j = u.newSel 

1519 w.setSelectionRange(i, j) 

1520 if u.groupCount == 0 and u.newYScroll is not None: 

1521 w.setYScrollPosition(u.newYScroll) 

1522 u.updateMarks('new') 

1523 u.p.setDirty() 

1524 #@+node:ekr.20080425060424.13: *4* u.redoPromote 

1525 def redoPromote(self): 

1526 u = self 

1527 c = u.c 

1528 parent_v = u.p._parentVnode() 

1529 # Add the children to parent_v's children. 

1530 n = u.p.childIndex() + 1 

1531 old_children = parent_v.children[:] 

1532 # Add children up to the promoted nodes. 

1533 parent_v.children = old_children[:n] 

1534 # Add the promoted nodes. 

1535 parent_v.children.extend(u.children) 

1536 # Add the children up to the promoted nodes. 

1537 parent_v.children.extend(old_children[n:]) 

1538 # Remove the old children. 

1539 u.p.v.children = [] 

1540 # Adjust the parent links in the moved children. 

1541 # There is no need to adjust descendant links. 

1542 for child in u.children: 

1543 child.parents.remove(u.p.v) 

1544 child.parents.append(parent_v) 

1545 u.p.setDirty() 

1546 c.setCurrentPosition(u.p) 

1547 #@+node:ekr.20080425060424.4: *4* u.redoSort 

1548 def redoSort(self): 

1549 u = self 

1550 c = u.c 

1551 parent_v = u.p._parentVnode() 

1552 parent_v.children = u.newChildren 

1553 p = c.setPositionAfterSort(u.sortChildren) 

1554 p.setAllAncestorAtFileNodesDirty() 

1555 c.setCurrentPosition(p) 

1556 #@+node:ekr.20050318085432.8: *4* u.redoTree 

1557 def redoTree(self): 

1558 """Redo replacement of an entire tree.""" 

1559 u = self 

1560 c = u.c 

1561 u.p = self.undoRedoTree(u.p, u.oldTree, u.newTree) 

1562 u.p.setDirty() 

1563 c.selectPosition(u.p) # Does full recolor. 

1564 if u.newSel: 

1565 i, j = u.newSel 

1566 c.frame.body.wrapper.setSelectionRange(i, j) 

1567 #@+node:EKR.20040526075238.5: *4* u.redoTyping 

1568 def redoTyping(self): 

1569 u = self 

1570 c = u.c 

1571 current = c.p 

1572 w = c.frame.body.wrapper 

1573 # selectPosition causes recoloring, so avoid if possible. 

1574 if current != u.p: 

1575 c.selectPosition(u.p) 

1576 u.p.setDirty() 

1577 self.undoRedoText( 

1578 u.p, u.leading, u.trailing, 

1579 u.newMiddleLines, u.oldMiddleLines, 

1580 u.newNewlines, u.oldNewlines, 

1581 tag="redo", undoType=u.undoType) 

1582 u.updateMarks('new') 

1583 if u.newSel: 

1584 c.bodyWantsFocus() 

1585 i, j = u.newSel 

1586 w.setSelectionRange(i, j, insert=j) 

1587 if u.yview: 

1588 c.bodyWantsFocus() 

1589 w.setYScrollPosition(u.yview) 

1590 #@+node:ekr.20031218072017.2039: *3* u.undo 

1591 @cmd('undo') 

1592 def undo(self, event=None): 

1593 """Undo the operation described by the undo parameters.""" 

1594 u = self 

1595 c = u.c 

1596 if not c.p: 

1597 g.trace('no current position') 

1598 return 

1599 # End editing *before* getting state. 

1600 c.endEditing() 

1601 if u.per_node_undo: # 2011/05/19 

1602 u.setIvarsFromVnode(c.p) 

1603 if not u.canUndo(): 

1604 return 

1605 if not u.getBead(u.bead): 

1606 return 

1607 # 

1608 # Init status. 

1609 u.undoing = True 

1610 u.groupCount = 0 

1611 # 

1612 # Dispatch. 

1613 if u.undoHelper: 

1614 u.undoHelper() 

1615 else: 

1616 g.trace(f"no undo helper for {u.kind} {u.undoType}") 

1617 # 

1618 # Finish. 

1619 c.checkOutline() 

1620 u.update_status() 

1621 u.undoing = False 

1622 u.bead -= 1 

1623 u.setUndoTypes() 

1624 #@+node:ekr.20110519074734.6093: *3* u.undo helpers 

1625 #@+node:ekr.20191213085246.1: *4* u.undoHelper 

1626 def undoHelper(self): 

1627 """The default do-nothing undo helper.""" 

1628 pass 

1629 #@+node:ekr.20201109080631.1: *4* u.undoChangeBody 

1630 def undoChangeBody(self): 

1631 """ 

1632 Undo all changes to the contents of a node, 

1633 including headline and body text, and marked bits. 

1634 """ 

1635 c, u, w = self.c, self, self.c.frame.body.wrapper 

1636 # selectPosition causes recoloring, so don't do this unless needed. 

1637 if c.p != u.p: 

1638 c.selectPosition(u.p) 

1639 u.p.setDirty() 

1640 u.p.b = u.oldBody 

1641 u.p.h = u.oldHead 

1642 # This is required. Otherwise c.redraw will revert the change! 

1643 c.frame.tree.setHeadline(u.p, u.oldHead) 

1644 if u.oldMarked: 

1645 u.p.setMarked() 

1646 else: 

1647 u.p.clearMarked() 

1648 if u.groupCount == 0: 

1649 w.setAllText(u.oldBody) 

1650 i, j = u.oldSel 

1651 w.setSelectionRange(i, j, insert=u.oldIns) 

1652 w.setYScrollPosition(u.oldYScroll) 

1653 c.frame.body.recolor(u.p) 

1654 u.updateMarks('old') 

1655 #@+node:ekr.20201107150041.1: *4* u.undoChangeHeadline 

1656 def undoChangeHeadline(self): 

1657 """Undo a change to a node's headline.""" 

1658 c, u = self.c, self 

1659 # selectPosition causes recoloring, so don't do this unless needed. 

1660 if c.p != u.p: # #1333. 

1661 c.selectPosition(u.p) 

1662 u.p.setDirty() 

1663 c.frame.body.recolor(u.p) 

1664 u.p.initHeadString(u.oldHead) 

1665 # This is required. Otherwise c.redraw will revert the change! 

1666 c.frame.tree.setHeadline(u.p, u.oldHead) 

1667 #@+node:ekr.20050424170219.1: *4* u.undoClearRecentFiles 

1668 def undoClearRecentFiles(self): 

1669 u = self 

1670 c = u.c 

1671 rf = g.app.recentFilesManager 

1672 rf.setRecentFiles(u.oldRecentFiles[:]) 

1673 rf.createRecentFilesMenuItems(c) 

1674 #@+node:ekr.20111005152227.15560: *4* u.undoCloneMarkedNodes 

1675 def undoCloneMarkedNodes(self): 

1676 u = self 

1677 next = u.p.next() 

1678 assert next.h == 'Clones of marked nodes', (u.p, next.h) 

1679 next.doDelete() 

1680 u.p.setAllAncestorAtFileNodesDirty() 

1681 u.c.selectPosition(u.p) 

1682 #@+node:ekr.20050412083057.1: *4* u.undoCloneNode 

1683 def undoCloneNode(self): 

1684 u = self 

1685 c = u.c 

1686 cc = c.chapterController 

1687 if cc: 

1688 cc.selectChapterByName('main') 

1689 c.selectPosition(u.newP) 

1690 c.deleteOutline() 

1691 u.p.setDirty() 

1692 c.selectPosition(u.p) 

1693 #@+node:ekr.20160502175653.1: *4* u.undoCopyMarkedNodes 

1694 def undoCopyMarkedNodes(self): 

1695 u = self 

1696 next = u.p.next() 

1697 assert next.h == 'Copies of marked nodes', (u.p.h, next.h) 

1698 next.doDelete() 

1699 u.p.setAllAncestorAtFileNodesDirty() 

1700 u.c.selectPosition(u.p) 

1701 #@+node:ekr.20111005152227.15557: *4* u.undoDeleteMarkedNodes 

1702 def undoDeleteMarkedNodes(self): 

1703 u = self 

1704 c = u.c 

1705 # Undo the deletes in reverse order 

1706 aList = u.deleteMarkedNodesData[:] 

1707 aList.reverse() 

1708 for p in aList: 

1709 if p.stack: 

1710 parent_v, junk = p.stack[-1] 

1711 else: 

1712 parent_v = c.hiddenRootNode 

1713 p.v._addLink(p._childIndex, parent_v) 

1714 p.v.setDirty() 

1715 u.p.setAllAncestorAtFileNodesDirty() 

1716 c.selectPosition(u.p) 

1717 #@+node:ekr.20050412084055: *4* u.undoDeleteNode 

1718 def undoDeleteNode(self): 

1719 u = self 

1720 c = u.c 

1721 if u.oldBack: 

1722 u.p._linkAfter(u.oldBack) 

1723 elif u.oldParent: 

1724 u.p._linkAsNthChild(u.oldParent, 0) 

1725 else: 

1726 u.p._linkAsRoot() 

1727 u.p.setDirty() 

1728 c.selectPosition(u.p) 

1729 #@+node:ekr.20080425060424.10: *4* u.undoDemote 

1730 def undoDemote(self): 

1731 u = self 

1732 c = u.c 

1733 parent_v = u.p._parentVnode() 

1734 n = len(u.followingSibs) 

1735 # Remove the demoted nodes from p's children. 

1736 u.p.v.children = u.p.v.children[: -n] 

1737 # Add the demoted nodes to the parent's children. 

1738 parent_v.children.extend(u.followingSibs) 

1739 # Adjust the parent links. 

1740 # There is no need to adjust descendant links. 

1741 parent_v.setDirty() 

1742 for sib in u.followingSibs: 

1743 sib.parents.remove(u.p.v) 

1744 sib.parents.append(parent_v) 

1745 u.p.setAllAncestorAtFileNodesDirty() 

1746 c.setCurrentPosition(u.p) 

1747 #@+node:ekr.20050318085713: *4* u.undoGroup 

1748 def undoGroup(self): 

1749 """Process beads until the matching 'beforeGroup' bead is seen.""" 

1750 u = self 

1751 # Remember these values. 

1752 c = u.c 

1753 oldSel = u.oldSel 

1754 p = u.p.copy() 

1755 u.groupCount += 1 

1756 bunch = u.beads[u.bead] 

1757 count = 0 

1758 if not hasattr(bunch, 'items'): 

1759 g.trace(f"oops: expecting bunch.items. got bunch.kind = {bunch.kind}") 

1760 g.trace(bunch) 

1761 else: 

1762 # Important bug fix: 9/8/06: reverse the items first. 

1763 reversedItems = bunch.items[:] 

1764 reversedItems.reverse() 

1765 for z in reversedItems: 

1766 self.setIvarsFromBunch(z) 

1767 if z.undoHelper: 

1768 z.undoHelper() 

1769 count += 1 

1770 else: 

1771 g.trace(f"oops: no undo helper for {u.undoType} {p.v}") 

1772 u.groupCount -= 1 

1773 u.updateMarks('old') # Bug fix: Leo 4.4.6. 

1774 if not g.unitTesting and u.verboseUndoGroup: 

1775 g.es("undo", count, "instances") 

1776 p.setDirty() 

1777 c.selectPosition(p) 

1778 if oldSel: 

1779 i, j = oldSel 

1780 c.frame.body.wrapper.setSelectionRange(i, j) 

1781 #@+node:ekr.20050412083244: *4* u.undoHoistNode & undoDehoistNode 

1782 def undoHoistNode(self): 

1783 u = self 

1784 c = u.c 

1785 u.p.setDirty() 

1786 c.selectPosition(u.p) 

1787 c.dehoist() 

1788 

1789 def undoDehoistNode(self): 

1790 u = self 

1791 c = u.c 

1792 u.p.setDirty() 

1793 c.selectPosition(u.p) 

1794 c.hoist() 

1795 #@+node:ekr.20050412085112: *4* u.undoInsertNode 

1796 def undoInsertNode(self): 

1797 u = self 

1798 c = u.c 

1799 cc = c.chapterController 

1800 if cc: 

1801 cc.selectChapterByName('main') 

1802 u.newP.setAllAncestorAtFileNodesDirty() 

1803 c.selectPosition(u.newP) 

1804 c.deleteOutline() 

1805 # Bug fix: 2016/03/30. 

1806 # This always selects the proper new position. 

1807 # c.selectPosition(u.p) 

1808 if u.pasteAsClone: 

1809 for bunch in u.beforeTree: 

1810 v = bunch.v 

1811 if u.p.v == v: 

1812 u.p.b = bunch.body 

1813 u.p.h = bunch.head 

1814 else: 

1815 v.setBodyString(bunch.body) 

1816 v.setHeadString(bunch.head) 

1817 #@+node:ekr.20050526124906: *4* u.undoMark 

1818 def undoMark(self): 

1819 u = self 

1820 c = u.c 

1821 u.updateMarks('old') 

1822 if u.groupCount == 0: 

1823 u.p.setDirty() 

1824 c.selectPosition(u.p) 

1825 #@+node:ekr.20050411112033: *4* u.undoMove 

1826 def undoMove(self): 

1827 

1828 u = self 

1829 c = u.c 

1830 cc = c.chapterController 

1831 if cc: 

1832 cc.selectChapterByName('main') 

1833 v = u.p.v 

1834 assert u.oldParent_v 

1835 assert u.newParent_v 

1836 assert v 

1837 # Adjust the children arrays. 

1838 assert u.newParent_v.children[u.newN] == v 

1839 del u.newParent_v.children[u.newN] 

1840 u.oldParent_v.children.insert(u.oldN, v) 

1841 # Recompute the parent links. 

1842 v.parents.append(u.oldParent_v) 

1843 v.parents.remove(u.newParent_v) 

1844 u.updateMarks('old') 

1845 u.p.setDirty() 

1846 c.selectPosition(u.p) 

1847 #@+node:ekr.20050318085713.1: *4* u.undoNodeContents 

1848 def undoNodeContents(self): 

1849 """ 

1850 Undo all changes to the contents of a node, 

1851 including headline and body text, and marked bits. 

1852 """ 

1853 c, u = self.c, self 

1854 w = c.frame.body.wrapper 

1855 # selectPosition causes recoloring, so don't do this unless needed. 

1856 if c.p != u.p: # #1333. 

1857 c.selectPosition(u.p) 

1858 u.p.setDirty() 

1859 u.p.b = u.oldBody 

1860 w.setAllText(u.oldBody) 

1861 c.frame.body.recolor(u.p) 

1862 u.p.h = u.oldHead 

1863 # This is required. Otherwise c.redraw will revert the change! 

1864 c.frame.tree.setHeadline(u.p, u.oldHead) 

1865 if u.groupCount == 0 and u.oldSel: 

1866 i, j = u.oldSel 

1867 w.setSelectionRange(i, j) 

1868 if u.groupCount == 0 and u.oldYScroll is not None: 

1869 w.setYScrollPosition(u.oldYScroll) 

1870 u.updateMarks('old') 

1871 #@+node:ekr.20080425060424.14: *4* u.undoPromote 

1872 def undoPromote(self): 

1873 u = self 

1874 c = u.c 

1875 parent_v = u.p._parentVnode() # The parent of the all the *promoted* nodes. 

1876 # Remove the promoted nodes from parent_v's children. 

1877 n = u.p.childIndex() + 1 

1878 # Adjust the old parents children 

1879 old_children = parent_v.children 

1880 # Add the nodes before the promoted nodes. 

1881 parent_v.children = old_children[:n] 

1882 # Add the nodes after the promoted nodes. 

1883 parent_v.children.extend(old_children[n + len(u.children) :]) 

1884 # Add the demoted nodes to v's children. 

1885 u.p.v.children = u.children[:] 

1886 # Adjust the parent links. 

1887 # There is no need to adjust descendant links. 

1888 parent_v.setDirty() 

1889 for child in u.children: 

1890 child.parents.remove(parent_v) 

1891 child.parents.append(u.p.v) 

1892 u.p.setAllAncestorAtFileNodesDirty() 

1893 c.setCurrentPosition(u.p) 

1894 #@+node:ekr.20031218072017.1493: *4* u.undoRedoText 

1895 def undoRedoText(self, p, 

1896 leading, trailing, # Number of matching leading & trailing lines. 

1897 oldMidLines, newMidLines, # Lists of unmatched lines. 

1898 oldNewlines, newNewlines, # Number of trailing newlines. 

1899 tag="undo", # "undo" or "redo" 

1900 undoType=None 

1901 ): 

1902 """Handle text undo and redo: converts _new_ text into _old_ text.""" 

1903 # newNewlines is unused, but it has symmetry. 

1904 u = self 

1905 c = u.c 

1906 w = c.frame.body.wrapper 

1907 #@+<< Compute the result using p's body text >> 

1908 #@+node:ekr.20061106105812.1: *5* << Compute the result using p's body text >> 

1909 # Recreate the text using the present body text. 

1910 body = p.b 

1911 body = g.checkUnicode(body) 

1912 body_lines = body.split('\n') 

1913 s = [] 

1914 if leading > 0: 

1915 s.extend(body_lines[:leading]) 

1916 if oldMidLines: 

1917 s.extend(oldMidLines) 

1918 if trailing > 0: 

1919 s.extend(body_lines[-trailing :]) 

1920 s = '\n'.join(s) 

1921 # Remove trailing newlines in s. 

1922 while s and s[-1] == '\n': 

1923 s = s[:-1] 

1924 # Add oldNewlines newlines. 

1925 if oldNewlines > 0: 

1926 s = s + '\n' * oldNewlines 

1927 result = s 

1928 #@-<< Compute the result using p's body text >> 

1929 p.setBodyString(result) 

1930 p.setDirty() 

1931 w.setAllText(result) 

1932 sel = u.oldSel if tag == 'undo' else u.newSel 

1933 if sel: 

1934 i, j = sel 

1935 w.setSelectionRange(i, j, insert=j) 

1936 c.frame.body.recolor(p) 

1937 w.seeInsertPoint() # 2009/12/21 

1938 #@+node:ekr.20050408100042: *4* u.undoRedoTree 

1939 def undoRedoTree(self, p, new_data, old_data): 

1940 """Replace p and its subtree using old_data during undo.""" 

1941 # Same as undoReplace except uses g.Bunch. 

1942 u = self 

1943 c = u.c 

1944 if new_data is None: 

1945 # This is the first time we have undone the operation. 

1946 # Put the new data in the bead. 

1947 bunch = u.beads[u.bead] 

1948 bunch.newTree = u.saveTree(p.copy()) 

1949 u.beads[u.bead] = bunch 

1950 # Replace data in tree with old data. 

1951 u.restoreTree(old_data) 

1952 c.setBodyString(p, p.b) # This is not a do-nothing. 

1953 return p # Nothing really changes. 

1954 #@+node:ekr.20080425060424.5: *4* u.undoSort 

1955 def undoSort(self): 

1956 u = self 

1957 c = u.c 

1958 parent_v = u.p._parentVnode() 

1959 parent_v.children = u.oldChildren 

1960 p = c.setPositionAfterSort(u.sortChildren) 

1961 p.setAllAncestorAtFileNodesDirty() 

1962 c.setCurrentPosition(p) 

1963 #@+node:ekr.20050318085713.2: *4* u.undoTree 

1964 def undoTree(self): 

1965 """Redo replacement of an entire tree.""" 

1966 u = self 

1967 c = u.c 

1968 u.p = self.undoRedoTree(u.p, u.newTree, u.oldTree) 

1969 u.p.setAllAncestorAtFileNodesDirty() 

1970 c.selectPosition(u.p) # Does full recolor. 

1971 if u.oldSel: 

1972 i, j = u.oldSel 

1973 c.frame.body.wrapper.setSelectionRange(i, j) 

1974 #@+node:EKR.20040526090701.4: *4* u.undoTyping 

1975 def undoTyping(self): 

1976 c, u = self.c, self 

1977 w = c.frame.body.wrapper 

1978 # selectPosition causes recoloring, so don't do this unless needed. 

1979 if c.p != u.p: 

1980 c.selectPosition(u.p) 

1981 u.p.setDirty() 

1982 u.undoRedoText( 

1983 u.p, u.leading, u.trailing, 

1984 u.oldMiddleLines, u.newMiddleLines, 

1985 u.oldNewlines, u.newNewlines, 

1986 tag="undo", undoType=u.undoType) 

1987 u.updateMarks('old') 

1988 if u.oldSel: 

1989 c.bodyWantsFocus() 

1990 i, j = u.oldSel 

1991 w.setSelectionRange(i, j, insert=j) 

1992 if u.yview: 

1993 c.bodyWantsFocus() 

1994 w.setYScrollPosition(u.yview) 

1995 #@+node:ekr.20191213092304.1: *3* u.update_status 

1996 def update_status(self): 

1997 """ 

1998 Update status after either an undo or redo: 

1999 """ 

2000 c, u = self.c, self 

2001 w = c.frame.body.wrapper 

2002 # Redraw and recolor. 

2003 c.frame.body.updateEditors() # New in Leo 4.4.8. 

2004 # 

2005 # Set the new position. 

2006 if 0: # Don't do this: it interferes with selection ranges. 

2007 # This strange code forces a recomputation of the root position. 

2008 c.selectPosition(c.p) 

2009 else: 

2010 c.setCurrentPosition(c.p) 

2011 # 

2012 # # 1451. *Always* set the changed bit. 

2013 # Redrawing *must* be done here before setting u.undoing to False. 

2014 i, j = w.getSelectionRange() 

2015 ins = w.getInsertPoint() 

2016 c.redraw() 

2017 c.recolor() 

2018 if u.inHead: 

2019 c.editHeadline() 

2020 u.inHead = False 

2021 else: 

2022 c.bodyWantsFocus() 

2023 w.setSelectionRange(i, j, insert=ins) 

2024 w.seeInsertPoint() 

2025 #@-others 

2026#@-others 

2027#@@language python 

2028#@@tabwidth -4 

2029#@@pagewidth 70 

2030#@-leo