Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Manipulation or Recursive Function?

I'm in the process of coding a HTML Editor in Java. I want it to support auto-indentation. I have a Composite pattern implemented to represent the HTML tag objects in the file currently being edited. For example, this code:

<table> <tr> <th>Col1</th> <th>Col2</th> </tr> <tr> <td>Data1</td> <td>Data2</td> </tr> </table>

would result in this structural representation in the composite:

  • table -> tr(first), tr(second)
  • tr(first) -> th(Col1), th(Col2)
  • tr(second) -> td(Data1), td(Data2)

where x -> y, z means that x is a parent of y and z.

I have two options here:

  1. Create a recursive function to return a string with the indentation included.
  2. Create a recursive function that simply returns an non-formatted string of the current HTML code and then add in the indentation afterwards.

It is easy to do the first; however, I find it hard to continue to auto-indent following a user's indentation pattern if they alter the pattern. Because of this, I think Option 2 is preferable. I feel like this may also be more dynamic, if I can get it working correctly. Problem is, I'm not quite sure how to manipulate the string.

My thought is that I could somehow use a stack. I could push an open tag onto it and pop it off when it's closed. The number of tags on the stack would determine the number of times I need to indent before the next tag on a new line. I could use an integer instead, but the same concept applies. The issue is that I don't know how to go about iterating through the tags in the string so that I can manipulate it.

So, is there any way to do string manipulation the way I described it? Or is it better to go with the recursive function?

like image 213
yeapiekiyay Avatar asked Nov 13 '22 19:11

yeapiekiyay


1 Answers

Given your so well-articulated question, I think you are the best person to answer it, and you just need more information.

To come up with that information, this may be helpful:

  1. Consider the whole life cycle of the text. You will need to react on keystrokes etc. Then having model and presentation clearly separated is much better rather than manipulating the padded strings. Another benefit is that you can choose an existing text edit component relatively independently from the model

  2. Consider examples: rich text editors, open source like jEdit etc.

like image 143
full.stack.ex Avatar answered Nov 15 '22 12:11

full.stack.ex