Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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: 

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

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

154 def dumpBead(self, n): 

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): 

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 

178 bunch = u.beads[n] 

179 self.setIvarsFromBunch(bunch) 

180 if 'undo' in g.app.debug: 

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: 

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. 

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): 

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): 

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'): 

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 

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 

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': 

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 

451 bunch = u.beads[u.bead] 

452 if not u.beads: 

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

454 return 

455 if bunch.kind == 'beforeGroup': 

456 bunch.kind = 'afterGroup' 

457 else: 

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 

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 

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 

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 bunch = u.createCommonBunch(p) 

548 # Sets 

549 # oldDirty = p.isDirty(), 

550 # oldMarked = p.isMarked(), 

551 # oldSel = w and w.getSelectionRange() or None, 

552 # p = p.copy(), 

553 # Set types & helpers 

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 bunch = u.createCommonBunch(p) 

568 # Sets 

569 # oldDirty = p.isDirty(), 

570 # oldMarked = p.isMarked(), 

571 # oldSel = w and w.getSelectionRange() or None, 

572 # p = p.copy(), 

573 # Set types & helpers 

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 

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 

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 

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 

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) 

753 # Sets u.oldMarked, u.oldSel, u.p 

754 bunch.oldBody = p.b 

755 bunch.oldHead = p.h 

756 bunch.oldIns = w.getInsertPoint() 

757 bunch.oldYScroll = w.getYScrollPosition() 

758 return bunch 

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

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

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

762 u = self 

763 bunch = u.createCommonBunch(p) 

764 # Set types. 

765 bunch.kind = 'beforeGroup' 

766 bunch.undoType = command 

767 bunch.verboseUndoGroup = verboseUndoGroup 

768 # Set helper only for redo: 

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

770 bunch.undoHelper = u.undoGroup 

771 bunch.redoHelper = u.redoGroup 

772 bunch.items = [] 

773 # Push the bunch. 

774 u.bead += 1 

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

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

777 def beforeChangeHeadline(self, p): 

778 """ 

779 Return data that gets passed to afterChangeNode. 

780 

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

782 """ 

783 u = self 

784 bunch = u.createCommonBunch(p) 

785 bunch.oldHead = p.h 

786 return bunch 

787 

788 beforeChangeHead = beforeChangeHeadline 

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

790 def beforeChangeNodeContents(self, p): 

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

792 c, u = self.c, self 

793 w = c.frame.body.wrapper 

794 bunch = u.createCommonBunch(p) 

795 bunch.oldBody = p.b 

796 bunch.oldHead = p.h 

797 # #1413: Always restore yScroll if possible. 

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

799 return bunch 

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

801 def beforeChangeTree(self, p): 

802 u = self 

803 c = u.c 

804 w = c.frame.body.wrapper 

805 bunch = u.createCommonBunch(p) 

806 bunch.oldSel = w.getSelectionRange() 

807 bunch.oldText = w.getAllText() 

808 bunch.oldTree = u.saveTree(p) 

809 return bunch 

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

811 def beforeClearRecentFiles(self): 

812 u = self 

813 p = u.c.p 

814 bunch = u.createCommonBunch(p) 

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

816 return bunch 

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

818 def beforeCloneNode(self, p): 

819 u = self 

820 bunch = u.createCommonBunch(p) 

821 return bunch 

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

823 def beforeDeleteNode(self, p): 

824 u = self 

825 bunch = u.createCommonBunch(p) 

826 bunch.oldBack = p.back() 

827 bunch.oldParent = p.parent() 

828 return bunch 

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

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

831 u = self 

832 if copiedBunchList is None: 

833 copiedBunchList = [] 

834 bunch = u.createCommonBunch(p) 

835 bunch.pasteAsClone = pasteAsClone 

836 if pasteAsClone: 

837 # Save the list of bunched. 

838 bunch.beforeTree = copiedBunchList 

839 return bunch 

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

841 def beforeMark(self, p, command): 

842 u = self 

843 bunch = u.createCommonBunch(p) 

844 bunch.kind = 'mark' 

845 bunch.undoType = command 

846 return bunch 

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

848 def beforeMoveNode(self, p): 

849 u = self 

850 bunch = u.createCommonBunch(p) 

851 bunch.oldN = p.childIndex() 

852 bunch.oldParent_v = p._parentVnode() 

853 return bunch 

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

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

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

857 u = self 

858 bunch = u.createCommonBunch(p) 

859 # Set types. 

860 bunch.kind = 'sort' 

861 bunch.undoType = undoType 

862 bunch.undoHelper = u.undoSort 

863 bunch.redoHelper = u.redoSort 

864 bunch.oldChildren = oldChildren 

865 bunch.newChildren = newChildren 

866 bunch.sortChildren = sortChildren # A bool 

867 # Push the bunch. 

868 u.bead += 1 

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

870 return bunch 

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

872 def createCommonBunch(self, p): 

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

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

875 u = self 

876 c = u.c 

877 w = c.frame.body.wrapper 

878 return g.Bunch( 

879 oldMarked=p and p.isMarked(), 

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

881 p=p and p.copy(), 

882 ) 

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

884 # Translation does not affect these routines. 

885 

886 def canRedo(self): 

887 u = self 

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

889 

890 def canUndo(self): 

891 u = self 

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

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

894 def clearUndoState(self): 

895 """Clears then entire Undo state. 

896 

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

898 u = self 

899 u.clearOptionalIvars() # Do this first. 

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

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

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

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

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

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

906 newInsert=None, oldSel=None, newSel=None, oldYview=None, 

907 ): 

908 """ 

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

910 that is, with the proper granularity. 

911 

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

913 and Redo commands merely reset the bead pointer. 

914 

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

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

917 u.afterChangeBody. 

918 

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

920 """ 

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

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

923 undo_type = undo_type.capitalize() 

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

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

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

927 if u.redoing or u.undoing: 

928 return None 

929 if undo_type is None: 

930 return None 

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

932 u.clearUndoState() 

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

934 return None 

935 if oldText == newText: 

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

937 return None 

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

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

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

941 u.clearOptionalIvars() 

942 # Set the params. 

943 u.undoType = undo_type 

944 u.p = p.copy() 

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

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

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

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

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

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

951 #@@c 

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

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

954 new_len = len(new_lines) 

955 old_len = len(old_lines) 

956 min_len = min(old_len, new_len) 

957 i = 0 

958 while i < min_len: 

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

960 break 

961 i += 1 

962 leading = i 

963 if leading == new_len: 

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

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

966 trailing = 0 

967 else: 

968 i = 0 

969 while i < min_len - leading: 

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

971 break 

972 i += 1 

973 trailing = i 

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

975 if trailing == 0: 

976 old_middle_lines = old_lines[leading:] 

977 new_middle_lines = new_lines[leading:] 

978 else: 

979 old_middle_lines = old_lines[leading : -trailing] 

980 new_middle_lines = new_lines[leading : -trailing] 

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

982 i = len(oldText) - 1 

983 old_newlines = 0 

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

985 old_newlines += 1 

986 i -= 1 

987 i = len(newText) - 1 

988 new_newlines = 0 

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

990 new_newlines += 1 

991 i -= 1 

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

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

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

995 u.oldText = None 

996 u.newText = None 

997 u.leading = leading 

998 u.trailing = trailing 

999 u.oldMiddleLines = old_middle_lines 

1000 u.newMiddleLines = new_middle_lines 

1001 u.oldNewlines = old_newlines 

1002 u.newNewlines = new_newlines 

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

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

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

1006 # Remember the selection. 

1007 u.oldSel = oldSel 

1008 u.newSel = newSel 

1009 # Remember the scrolling position. 

1010 if oldYview: 

1011 u.yview = oldYview 

1012 else: 

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

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

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

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

1017 #@+at 

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

1019 # may adjust the top bead: 

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

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

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

1023 #@@c 

1024 granularity = u.granularity 

1025 old_d = u.peekBead(u.bead) 

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

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

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

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

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

1031 if ( 

1032 not old_d or not old_p or 

1033 old_p.v != p.v or 

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

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

1036 undo_type != 'Typing' 

1037 ): 

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

1039 elif granularity == 'char': 

1040 newBead = True # This was the old way. 

1041 elif granularity == 'node': 

1042 newBead = False # Always replace previous bead. 

1043 else: 

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

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

1046 newBead = ( 

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

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

1049 ) 

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

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

1052 try: 

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

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

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

1056 old_start = old_end = new_start = new_end = 0 

1057 if oldSel is not None: 

1058 old_start, old_end = oldSel 

1059 if newSel is not None: 

1060 new_start, new_end = newSel 

1061 if u.prevSel is None: 

1062 prev_start, prev_end = 0, 0 

1063 else: 

1064 prev_start, prev_end = u.prevSel 

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

1066 # The new and old characters are not contiguous. 

1067 newBead = True 

1068 else: 

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

1070 old_row, old_col = g.convertPythonIndexToRowCol( 

1071 oldText, old_start) 

1072 new_row, new_col = g.convertPythonIndexToRowCol( 

1073 newText, new_start) 

1074 prev_row, prev_col = g.convertPythonIndexToRowCol( 

1075 oldText, prev_start) 

1076 old_lines = g.splitLines(oldText) 

1077 new_lines = g.splitLines(newText) 

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

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

1080 # The new and old characters are not contiguous. 

1081 newBead = True 

1082 elif old_col == 0 or new_col == 0: 

1083 # py-lint: disable=W0511 

1084 # W0511:1362: TODO 

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

1086 # char at the beginning of an existing line 

1087 pass # We have just inserted a line. 

1088 else: 

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

1090 old_s = old_lines[old_row] 

1091 new_s = new_lines[new_row] 

1092 # New in 4.3b2: 

1093 # Guard against invalid oldSel or newSel params. 

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

1095 newBead = True 

1096 else: 

1097 old_ch = old_s[old_col - 1] 

1098 new_ch = new_s[new_col - 1] 

1099 newBead = self.recognizeStartOfTypingWord( 

1100 old_lines, old_row, old_col, old_ch, 

1101 new_lines, new_row, new_col, new_ch, 

1102 prev_row, prev_col) 

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

1104 except Exception: 

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

1106 g.es_exception() 

1107 newBead = True 

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

1109 # Save end selection as new "previous" selection 

1110 u.prevSel = u.newSel 

1111 if newBead: 

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

1113 bunch = g.Bunch( 

1114 p=p.copy(), 

1115 kind='typing', # lowercase. 

1116 undoType=undo_type, # capitalized. 

1117 undoHelper=u.undoTyping, 

1118 redoHelper=u.redoTyping, 

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

1120 oldText=u.oldText, 

1121 oldSel=u.oldSel, 

1122 oldNewlines=u.oldNewlines, 

1123 oldMiddleLines=u.oldMiddleLines, 

1124 ) 

1125 u.pushBead(bunch) 

1126 else: 

1127 bunch = old_d 

1128 bunch.leading = u.leading 

1129 bunch.trailing = u.trailing 

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

1131 bunch.newNewlines = u.newNewlines 

1132 bunch.newMiddleLines = u.newMiddleLines 

1133 bunch.newSel = u.newSel 

1134 bunch.newText = u.newText 

1135 bunch.yview = u.yview 

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

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

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

1139 if u.per_node_undo: 

1140 u.putIvarsToVnode(p) 

1141 # 

1142 # Finish updating the text. 

1143 p.v.setBodyString(newText) 

1144 u.updateAfterTyping(p, w) 

1145 

1146 # Compatibility 

1147 

1148 setUndoTypingParams = doTyping 

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

1150 def recognizeStartOfTypingWord(self, 

1151 old_lines, old_row, old_col, old_ch, 

1152 new_lines, new_row, new_col, new_ch, 

1153 prev_row, prev_col 

1154 ): 

1155 """ 

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

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

1158 undo with 'word' granularity. 

1159 

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

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

1162 of the value returned here. 

1163 

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

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

1166 

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

1168 for use by more sophisticated algorithms. 

1169 """ 

1170 # Start a word if new_ch begins whitespace + word 

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

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

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

1174 return new_word_started or moved_cursor 

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

1176 def enableMenuItems(self): 

1177 u = self 

1178 frame = u.c.frame 

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

1180 if menu: 

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

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

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

1184 def onSelect(self, old_p, p): 

1185 

1186 u = self 

1187 if u.per_node_undo: 

1188 if old_p and u.beads: 

1189 u.putIvarsToVnode(old_p) 

1190 u.setIvarsFromVnode(p) 

1191 u.setUndoTypes() 

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

1193 def putIvarsToVnode(self, p): 

1194 

1195 u, v = self, p.v 

1196 assert self.per_node_undo 

1197 bunch = g.bunch() 

1198 for key in self.optionalIvars: 

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

1200 # Put these ivars by hand. 

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

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

1203 v.undo_info = bunch 

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

1205 def setIvarsFromVnode(self, p): 

1206 u = self 

1207 v = p.v 

1208 assert self.per_node_undo 

1209 u.clearUndoState() 

1210 if hasattr(v, 'undo_info'): 

1211 u.setIvarsFromBunch(v.undo_info) 

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

1213 def updateAfterTyping(self, p, w): 

1214 """ 

1215 Perform all update tasks after changing body text. 

1216 

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

1218 """ 

1219 c = self.c 

1220 if g.isTextWrapper(w): 

1221 # An important, ever-present unit test. 

1222 all = w.getAllText() 

1223 if g.unitTesting: 

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

1225 elif p.b != all: 

1226 g.trace( 

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

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

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

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

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

1232 # From u.doTyping. 

1233 newSel = w.getSelectionRange() 

1234 if newSel is None: 

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

1236 else: 

1237 i, j = newSel 

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

1239 else: 

1240 if g.unitTesting: 

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

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

1243 p.v.insertSpot = 0 

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

1245 # 

1246 # #1749. 

1247 if p.isDirty(): 

1248 redraw_flag = False 

1249 else: 

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

1251 redraw_flag = True 

1252 if not c.isChanged(): 

1253 c.setChanged() 

1254 # Update editors. 

1255 c.frame.body.updateEditors() 

1256 # Update icons. 

1257 val = p.computeIcon() 

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

1259 p.v.iconVal = val 

1260 redraw_flag = True 

1261 # 

1262 # Recolor the body. 

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

1264 c.recolor() 

1265 if redraw_flag: 

1266 c.redraw_after_icons_changed() 

1267 w.setFocus() 

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

1269 @cmd('redo') 

1270 def redo(self, event=None): 

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

1272 c, u = self.c, self 

1273 if not c.p: 

1274 return 

1275 # End editing *before* getting state. 

1276 c.endEditing() 

1277 if not u.canRedo(): 

1278 return 

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

1280 return 

1281 # 

1282 # Init status. 

1283 u.redoing = True 

1284 u.groupCount = 0 

1285 if u.redoHelper: 

1286 u.redoHelper() 

1287 else: 

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

1289 # 

1290 # Finish. 

1291 c.checkOutline() 

1292 u.update_status() 

1293 u.redoing = False 

1294 u.bead += 1 

1295 u.setUndoTypes() 

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

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

1298 def redoHelper(self): 

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

1300 pass 

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

1302 def redoChangeBody(self): 

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

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

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

1306 c.selectPosition(u.p) 

1307 u.p.setDirty() 

1308 u.p.b = u.newBody 

1309 u.p.h = u.newHead 

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

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

1312 if u.newMarked: 

1313 u.p.setMarked() 

1314 else: 

1315 u.p.clearMarked() 

1316 if u.groupCount == 0: 

1317 w.setAllText(u.newBody) 

1318 i, j = u.newSel 

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

1320 w.setYScrollPosition(u.newYScroll) 

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

1322 u.updateMarks('new') 

1323 u.p.setDirty() 

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

1325 def redoChangeHeadline(self): 

1326 c, u = self.c, self 

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

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

1329 c.selectPosition(u.p) 

1330 u.p.setDirty() 

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

1332 # Restore the headline. 

1333 u.p.initHeadString(u.newHead) 

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

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

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

1337 def redoClearRecentFiles(self): 

1338 u = self 

1339 c = u.c 

1340 rf = g.app.recentFilesManager 

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

1342 rf.createRecentFilesMenuItems(c) 

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

1344 def redoCloneMarkedNodes(self): 

1345 u = self 

1346 c = u.c 

1347 c.selectPosition(u.p) 

1348 c.cloneMarked() 

1349 u.newP = c.p 

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

1351 def redoCopyMarkedNodes(self): 

1352 u = self 

1353 c = u.c 

1354 c.selectPosition(u.p) 

1355 c.copyMarked() 

1356 u.newP = c.p 

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

1358 def redoCloneNode(self): 

1359 u = self 

1360 c = u.c 

1361 cc = c.chapterController 

1362 if cc: 

1363 cc.selectChapterByName('main') 

1364 if u.newBack: 

1365 u.newP._linkAfter(u.newBack) 

1366 elif u.newParent: 

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

1368 else: 

1369 u.newP._linkAsRoot() 

1370 c.selectPosition(u.newP) 

1371 u.newP.setDirty() 

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

1373 def redoDeleteMarkedNodes(self): 

1374 u = self 

1375 c = u.c 

1376 c.selectPosition(u.p) 

1377 c.deleteMarked() 

1378 c.selectPosition(u.newP) 

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

1380 def redoDeleteNode(self): 

1381 u = self 

1382 c = u.c 

1383 c.selectPosition(u.p) 

1384 c.deleteOutline() 

1385 c.selectPosition(u.newP) 

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

1387 def redoDemote(self): 

1388 u = self 

1389 c = u.c 

1390 parent_v = u.p._parentVnode() 

1391 n = u.p.childIndex() 

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

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

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

1395 # Adjust the parent links of the moved nodes. 

1396 # There is no need to adjust descendant links. 

1397 for v in u.followingSibs: 

1398 v.parents.remove(parent_v) 

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

1400 u.p.setDirty() 

1401 c.setCurrentPosition(u.p) 

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

1403 def redoGroup(self): 

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

1405 u = self 

1406 # Remember these values. 

1407 c = u.c 

1408 newSel = u.newSel 

1409 p = u.p.copy() 

1410 u.groupCount += 1 

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

1412 count = 0 

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

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

1415 g.trace(bunch) 

1416 else: 

1417 for z in bunch.items: 

1418 self.setIvarsFromBunch(z) 

1419 if z.redoHelper: 

1420 z.redoHelper() 

1421 count += 1 

1422 else: 

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

1424 u.groupCount -= 1 

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

1426 if not g.unitTesting and u.verboseUndoGroup: 

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

1428 p.setDirty() 

1429 c.selectPosition(p) 

1430 if newSel: 

1431 i, j = newSel 

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

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

1434 def redoHoistNode(self): 

1435 c, u = self.c, self 

1436 u.p.setDirty() 

1437 c.selectPosition(u.p) 

1438 c.hoist() 

1439 

1440 def redoDehoistNode(self): 

1441 c, u = self.c, self 

1442 u.p.setDirty() 

1443 c.selectPosition(u.p) 

1444 c.dehoist() 

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

1446 def redoInsertNode(self): 

1447 u = self 

1448 c = u.c 

1449 cc = c.chapterController 

1450 if cc: 

1451 cc.selectChapterByName('main') 

1452 if u.newBack: 

1453 u.newP._linkAfter(u.newBack) 

1454 elif u.newParent: 

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

1456 else: 

1457 u.newP._linkAsRoot() 

1458 if u.pasteAsClone: 

1459 for bunch in u.afterTree: 

1460 v = bunch.v 

1461 if u.newP.v == v: 

1462 u.newP.b = bunch.body 

1463 u.newP.h = bunch.head 

1464 else: 

1465 v.setBodyString(bunch.body) 

1466 v.setHeadString(bunch.head) 

1467 u.newP.setDirty() 

1468 c.selectPosition(u.newP) 

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

1470 def redoMark(self): 

1471 u = self 

1472 c = u.c 

1473 u.updateMarks('new') 

1474 if u.groupCount == 0: 

1475 u.p.setDirty() 

1476 c.selectPosition(u.p) 

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

1478 def redoMove(self): 

1479 u = self 

1480 c = u.c 

1481 cc = c.chapterController 

1482 v = u.p.v 

1483 assert u.oldParent_v 

1484 assert u.newParent_v 

1485 assert v 

1486 if cc: 

1487 cc.selectChapterByName('main') 

1488 # Adjust the children arrays of the old parent. 

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

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

1491 u.oldParent_v.setDirty() 

1492 # Adjust the children array of the new parent. 

1493 parent_v = u.newParent_v 

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

1495 v.parents.append(u.newParent_v) 

1496 v.parents.remove(u.oldParent_v) 

1497 u.newParent_v.setDirty() 

1498 # 

1499 u.updateMarks('new') 

1500 u.newP.setDirty() 

1501 c.selectPosition(u.newP) 

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

1503 def redoNodeContents(self): 

1504 c, u = self.c, self 

1505 w = c.frame.body.wrapper 

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

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

1508 c.selectPosition(u.p) 

1509 u.p.setDirty() 

1510 # Restore the body. 

1511 u.p.setBodyString(u.newBody) 

1512 w.setAllText(u.newBody) 

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

1514 # Restore the headline. 

1515 u.p.initHeadString(u.newHead) 

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

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

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

1519 i, j = u.newSel 

1520 w.setSelectionRange(i, j) 

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

1522 w.setYScrollPosition(u.newYScroll) 

1523 u.updateMarks('new') 

1524 u.p.setDirty() 

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

1526 def redoPromote(self): 

1527 u = self 

1528 c = u.c 

1529 parent_v = u.p._parentVnode() 

1530 # Add the children to parent_v's children. 

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

1532 old_children = parent_v.children[:] 

1533 parent_v.children = old_children[:n] 

1534 # Add children up to the promoted nodes. 

1535 parent_v.children.extend(u.children) 

1536 # Add the promoted nodes. 

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

1538 # Add the children up to the promoted nodes. 

1539 # Remove the old children. 

1540 u.p.v.children = [] 

1541 # Adjust the parent links in the moved children. 

1542 # There is no need to adjust descendant links. 

1543 for child in u.children: 

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

1545 child.parents.append(parent_v) 

1546 u.p.setDirty() 

1547 c.setCurrentPosition(u.p) 

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

1549 def redoSort(self): 

1550 u = self 

1551 c = u.c 

1552 parent_v = u.p._parentVnode() 

1553 parent_v.children = u.newChildren 

1554 p = c.setPositionAfterSort(u.sortChildren) 

1555 p.setAllAncestorAtFileNodesDirty() 

1556 c.setCurrentPosition(p) 

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

1558 def redoTree(self): 

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

1560 u = self 

1561 c = u.c 

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

1563 u.p.setDirty() 

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

1565 if u.newSel: 

1566 i, j = u.newSel 

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

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

1569 def redoTyping(self): 

1570 u = self 

1571 c = u.c 

1572 current = c.p 

1573 w = c.frame.body.wrapper 

1574 # selectPosition causes recoloring, so avoid if possible. 

1575 if current != u.p: 

1576 c.selectPosition(u.p) 

1577 u.p.setDirty() 

1578 self.undoRedoText( 

1579 u.p, u.leading, u.trailing, 

1580 u.newMiddleLines, u.oldMiddleLines, 

1581 u.newNewlines, u.oldNewlines, 

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

1583 u.updateMarks('new') 

1584 if u.newSel: 

1585 c.bodyWantsFocus() 

1586 i, j = u.newSel 

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

1588 if u.yview: 

1589 c.bodyWantsFocus() 

1590 w.setYScrollPosition(u.yview) 

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

1592 @cmd('undo') 

1593 def undo(self, event=None): 

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

1595 u = self 

1596 c = u.c 

1597 if not c.p: 

1598 g.trace('no current position') 

1599 return 

1600 # End editing *before* getting state. 

1601 c.endEditing() 

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

1603 u.setIvarsFromVnode(c.p) 

1604 if not u.canUndo(): 

1605 return 

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

1607 return 

1608 # 

1609 # Init status. 

1610 u.undoing = True 

1611 u.groupCount = 0 

1612 # 

1613 # Dispatch. 

1614 if u.undoHelper: 

1615 u.undoHelper() 

1616 else: 

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

1618 # 

1619 # Finish. 

1620 c.checkOutline() 

1621 u.update_status() 

1622 u.undoing = False 

1623 u.bead -= 1 

1624 u.setUndoTypes() 

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

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

1627 def undoHelper(self): 

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

1629 pass 

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

1631 def undoChangeBody(self): 

1632 """ 

1633 Undo all changes to the contents of a node, 

1634 including headline and body text, and marked bits. 

1635 """ 

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

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

1638 if c.p != u.p: 

1639 c.selectPosition(u.p) 

1640 u.p.setDirty() 

1641 u.p.b = u.oldBody 

1642 u.p.h = u.oldHead 

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

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

1645 if u.oldMarked: 

1646 u.p.setMarked() 

1647 else: 

1648 u.p.clearMarked() 

1649 if u.groupCount == 0: 

1650 w.setAllText(u.oldBody) 

1651 i, j = u.oldSel 

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

1653 w.setYScrollPosition(u.oldYScroll) 

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

1655 u.updateMarks('old') 

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

1657 def undoChangeHeadline(self): 

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

1659 c, u = self.c, self 

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

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

1662 c.selectPosition(u.p) 

1663 u.p.setDirty() 

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

1665 u.p.initHeadString(u.oldHead) 

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

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

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

1669 def undoClearRecentFiles(self): 

1670 u = self 

1671 c = u.c 

1672 rf = g.app.recentFilesManager 

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

1674 rf.createRecentFilesMenuItems(c) 

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

1676 def undoCloneMarkedNodes(self): 

1677 u = self 

1678 next = u.p.next() 

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

1680 next.doDelete() 

1681 u.p.setAllAncestorAtFileNodesDirty() 

1682 u.c.selectPosition(u.p) 

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

1684 def undoCloneNode(self): 

1685 u = self 

1686 c = u.c 

1687 cc = c.chapterController 

1688 if cc: 

1689 cc.selectChapterByName('main') 

1690 c.selectPosition(u.newP) 

1691 c.deleteOutline() 

1692 u.p.setDirty() 

1693 c.selectPosition(u.p) 

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

1695 def undoCopyMarkedNodes(self): 

1696 u = self 

1697 next = u.p.next() 

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

1699 next.doDelete() 

1700 u.p.setAllAncestorAtFileNodesDirty() 

1701 u.c.selectPosition(u.p) 

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

1703 def undoDeleteMarkedNodes(self): 

1704 u = self 

1705 c = u.c 

1706 # Undo the deletes in reverse order 

1707 aList = u.deleteMarkedNodesData[:] 

1708 aList.reverse() 

1709 for p in aList: 

1710 if p.stack: 

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

1712 else: 

1713 parent_v = c.hiddenRootNode 

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

1715 p.v.setDirty() 

1716 u.p.setAllAncestorAtFileNodesDirty() 

1717 c.selectPosition(u.p) 

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

1719 def undoDeleteNode(self): 

1720 u = self 

1721 c = u.c 

1722 if u.oldBack: 

1723 u.p._linkAfter(u.oldBack) 

1724 elif u.oldParent: 

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

1726 else: 

1727 u.p._linkAsRoot() 

1728 u.p.setDirty() 

1729 c.selectPosition(u.p) 

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

1731 def undoDemote(self): 

1732 u = self 

1733 c = u.c 

1734 parent_v = u.p._parentVnode() 

1735 n = len(u.followingSibs) 

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

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

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

1739 parent_v.children.extend(u.followingSibs) 

1740 # Adjust the parent links. 

1741 # There is no need to adjust descendant links. 

1742 parent_v.setDirty() 

1743 for sib in u.followingSibs: 

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

1745 sib.parents.append(parent_v) 

1746 u.p.setAllAncestorAtFileNodesDirty() 

1747 c.setCurrentPosition(u.p) 

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

1749 def undoGroup(self): 

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

1751 u = self 

1752 # Remember these values. 

1753 c = u.c 

1754 oldSel = u.oldSel 

1755 p = u.p.copy() 

1756 u.groupCount += 1 

1757 bunch = u.beads[u.bead] 

1758 count = 0 

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

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

1761 g.trace(bunch) 

1762 else: 

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

1764 reversedItems = bunch.items[:] 

1765 reversedItems.reverse() 

1766 for z in reversedItems: 

1767 self.setIvarsFromBunch(z) 

1768 if z.undoHelper: 

1769 z.undoHelper() 

1770 count += 1 

1771 else: 

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

1773 u.groupCount -= 1 

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

1775 if not g.unitTesting and u.verboseUndoGroup: 

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

1777 p.setDirty() 

1778 c.selectPosition(p) 

1779 if oldSel: 

1780 i, j = oldSel 

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

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

1783 def undoHoistNode(self): 

1784 u = self 

1785 c = u.c 

1786 u.p.setDirty() 

1787 c.selectPosition(u.p) 

1788 c.dehoist() 

1789 

1790 def undoDehoistNode(self): 

1791 u = self 

1792 c = u.c 

1793 u.p.setDirty() 

1794 c.selectPosition(u.p) 

1795 c.hoist() 

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

1797 def undoInsertNode(self): 

1798 u = self 

1799 c = u.c 

1800 cc = c.chapterController 

1801 if cc: 

1802 cc.selectChapterByName('main') 

1803 u.newP.setAllAncestorAtFileNodesDirty() 

1804 c.selectPosition(u.newP) 

1805 c.deleteOutline() 

1806 # Bug fix: 2016/03/30. 

1807 # This always selects the proper new position. 

1808 # c.selectPosition(u.p) 

1809 if u.pasteAsClone: 

1810 for bunch in u.beforeTree: 

1811 v = bunch.v 

1812 if u.p.v == v: 

1813 u.p.b = bunch.body 

1814 u.p.h = bunch.head 

1815 else: 

1816 v.setBodyString(bunch.body) 

1817 v.setHeadString(bunch.head) 

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

1819 def undoMark(self): 

1820 u = self 

1821 c = u.c 

1822 u.updateMarks('old') 

1823 if u.groupCount == 0: 

1824 u.p.setDirty() 

1825 c.selectPosition(u.p) 

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

1827 def undoMove(self): 

1828 

1829 u = self 

1830 c = u.c 

1831 cc = c.chapterController 

1832 if cc: 

1833 cc.selectChapterByName('main') 

1834 v = u.p.v 

1835 assert u.oldParent_v 

1836 assert u.newParent_v 

1837 assert v 

1838 # Adjust the children arrays. 

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

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

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

1842 # Recompute the parent links. 

1843 v.parents.append(u.oldParent_v) 

1844 v.parents.remove(u.newParent_v) 

1845 u.updateMarks('old') 

1846 u.p.setDirty() 

1847 c.selectPosition(u.p) 

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

1849 def undoNodeContents(self): 

1850 """ 

1851 Undo all changes to the contents of a node, 

1852 including headline and body text, and marked bits. 

1853 """ 

1854 c, u = self.c, self 

1855 w = c.frame.body.wrapper 

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

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

1858 c.selectPosition(u.p) 

1859 u.p.setDirty() 

1860 u.p.b = u.oldBody 

1861 w.setAllText(u.oldBody) 

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

1863 u.p.h = u.oldHead 

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

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

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

1867 i, j = u.oldSel 

1868 w.setSelectionRange(i, j) 

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

1870 w.setYScrollPosition(u.oldYScroll) 

1871 u.updateMarks('old') 

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

1873 def undoPromote(self): 

1874 u = self 

1875 c = u.c 

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

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

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

1879 # Adjust the old parents children 

1880 old_children = parent_v.children 

1881 parent_v.children = old_children[:n] 

1882 # Add the nodes before the promoted nodes. 

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

1884 # Add the nodes after the promoted nodes. 

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

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

1887 # Adjust the parent links. 

1888 # There is no need to adjust descendant links. 

1889 parent_v.setDirty() 

1890 for child in u.children: 

1891 child.parents.remove(parent_v) 

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

1893 u.p.setAllAncestorAtFileNodesDirty() 

1894 c.setCurrentPosition(u.p) 

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

1896 def undoRedoText(self, p, 

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

1898 oldMidLines, newMidLines, # Lists of unmatched lines. 

1899 oldNewlines, newNewlines, # Number of trailing newlines. 

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

1901 undoType=None 

1902 ): 

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

1904 # newNewlines is unused, but it has symmetry. 

1905 u = self 

1906 c = u.c 

1907 w = c.frame.body.wrapper 

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

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

1910 # Recreate the text using the present body text. 

1911 body = p.b 

1912 body = g.checkUnicode(body) 

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

1914 s = [] 

1915 if leading > 0: 

1916 s.extend(body_lines[:leading]) 

1917 if oldMidLines: 

1918 s.extend(oldMidLines) 

1919 if trailing > 0: 

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

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

1922 # Remove trailing newlines in s. 

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

1924 s = s[:-1] 

1925 # Add oldNewlines newlines. 

1926 if oldNewlines > 0: 

1927 s = s + '\n' * oldNewlines 

1928 result = s 

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

1930 p.setBodyString(result) 

1931 p.setDirty() 

1932 w.setAllText(result) 

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

1934 if sel: 

1935 i, j = sel 

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

1937 c.frame.body.recolor(p) 

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

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

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

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

1942 # Same as undoReplace except uses g.Bunch. 

1943 u = self 

1944 c = u.c 

1945 if new_data is None: 

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

1947 # Put the new data in the bead. 

1948 bunch = u.beads[u.bead] 

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

1950 u.beads[u.bead] = bunch 

1951 # Replace data in tree with old data. 

1952 u.restoreTree(old_data) 

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

1954 return p # Nothing really changes. 

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

1956 def undoSort(self): 

1957 u = self 

1958 c = u.c 

1959 parent_v = u.p._parentVnode() 

1960 parent_v.children = u.oldChildren 

1961 p = c.setPositionAfterSort(u.sortChildren) 

1962 p.setAllAncestorAtFileNodesDirty() 

1963 c.setCurrentPosition(p) 

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

1965 def undoTree(self): 

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

1967 u = self 

1968 c = u.c 

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

1970 u.p.setAllAncestorAtFileNodesDirty() 

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

1972 if u.oldSel: 

1973 i, j = u.oldSel 

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

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

1976 def undoTyping(self): 

1977 c, u = self.c, self 

1978 w = c.frame.body.wrapper 

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

1980 if c.p != u.p: 

1981 c.selectPosition(u.p) 

1982 u.p.setDirty() 

1983 u.undoRedoText( 

1984 u.p, u.leading, u.trailing, 

1985 u.oldMiddleLines, u.newMiddleLines, 

1986 u.oldNewlines, u.newNewlines, 

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

1988 u.updateMarks('old') 

1989 if u.oldSel: 

1990 c.bodyWantsFocus() 

1991 i, j = u.oldSel 

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

1993 if u.yview: 

1994 c.bodyWantsFocus() 

1995 w.setYScrollPosition(u.yview) 

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

1997 def update_status(self): 

1998 """ 

1999 Update status after either an undo or redo: 

2000 """ 

2001 c, u = self.c, self 

2002 w = c.frame.body.wrapper 

2003 # Redraw and recolor. 

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

2005 # 

2006 # Set the new position. 

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

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

2009 c.selectPosition(c.p) 

2010 else: 

2011 c.setCurrentPosition(c.p) 

2012 # 

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

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

2015 i, j = w.getSelectionRange() 

2016 ins = w.getInsertPoint() 

2017 c.redraw() 

2018 c.recolor() 

2019 if u.inHead: 

2020 c.editHeadline() 

2021 u.inHead = False 

2022 else: 

2023 c.bodyWantsFocus() 

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

2025 w.seeInsertPoint() 

2026 #@-others 

2027#@-others 

2028#@@language python 

2029#@@tabwidth -4 

2030#@@pagewidth 70 

2031#@-leo