How to design undo & redo in text editor?

后端 未结 8 852
渐次进展
渐次进展 2020-12-05 15:11

Part of my project is to write a text editor that is used for typing some rules, compiling my application and running it. Writing compiler was end and release beta version.

8条回答
  •  不思量自难忘°
    2020-12-05 15:52

    Wow, what a conicidence - I have literally in the last hour implemented undo/redo in my WYSIWYG text editor:

    The basic idea is to either save the entire contents of the text editor in an array, or the difference between the last edit.

    Update this array at significant points, i.e. every few character (check the length of the content each keypress, if its more than say 20 characters different then make a save point). Also at changes in styling (if rich text), adding images (if it allows this), pasting text, etc. You also need a pointer(just an int variable) to point at which item in the array is the current state of the editor)

    Make the array have a set length. Each time you add a save point, add it to the start of the array, and move all of the other data points down by one. (the last item in the array will be forgotten once you have so many save points)

    When the user presses the undo button, check to see if the current contents of the editor are the same as the latest save (if they are not, then the user has made changes since the last save point, so save the current contents of the editor (so it can be redo-ed), make the editor equal to the last save point, and make the pointer variable = 1 (2nd item in array ). If they are they same, then no changes have been made since the last save point, so you need to undo to the point before that. To do this, increment the pointer value + 1, and make the contents of the editor = the value of pointer.

    To redo simply decrease the pointer value by 1 and load the contents of the array (make sure to check if you have reached the end of the array).

    If the user makes edits after undoing, then move the pointed value array cell up to cell 0, and move the rest up by the same amount (you dont want to redo to other stuff once they've made different edits).

    One other major catch point - make sure you only add a save point if the contents of the text editor have actually changed (otherwise you get duplicate save points and it will seem like undo is not doing anything to the user.

    I can't help you with java specifics, but I'm happy to answer any other questions you have,

    Nico

提交回复
热议问题