Add 'src/jexer/' from commit 'cf01c92f5809a0732409e280fb0f32f27393618d'
[fanfix.git] / src / jexer / teditor / Document.java
index 5b7050fe22efd3963ca762256e163ba30c39a87b..2abfef6635f3c1877fc733ee36ea8c67d01160b6 100644 (file)
@@ -3,7 +3,7 @@
  *
  * The MIT License (MIT)
  *
- * Copyright (C) 2017 Kevin Lamonte
+ * Copyright (C) 2019 Kevin Lamonte
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -28,6 +28,9 @@
  */
 package jexer.teditor;
 
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -38,6 +41,10 @@ import jexer.bits.CellAttributes;
  */
 public class Document {
 
+    // ------------------------------------------------------------------------
+    // Variables --------------------------------------------------------------
+    // ------------------------------------------------------------------------
+
     /**
      * The list of lines.
      */
@@ -54,6 +61,11 @@ public class Document {
      */
     private boolean overwrite = false;
 
+    /**
+     * If true, the document has been edited.
+     */
+    private boolean dirty = false;
+
     /**
      * The default color for the TEditor class.
      */
@@ -64,6 +76,32 @@ public class Document {
      */
     private Highlighter highlighter = new Highlighter();
 
+    // ------------------------------------------------------------------------
+    // Constructors -----------------------------------------------------------
+    // ------------------------------------------------------------------------
+
+    /**
+     * Construct a new Document from an existing text string.
+     *
+     * @param str the text string
+     * @param defaultColor the color for unhighlighted text
+     */
+    public Document(final String str, final CellAttributes defaultColor) {
+        this.defaultColor = defaultColor;
+
+        // TODO: set different colors based on file extension
+        highlighter.setJavaColors();
+
+        String [] rawLines = str.split("\n");
+        for (int i = 0; i < rawLines.length; i++) {
+            lines.add(new Line(rawLines[i], this.defaultColor, highlighter));
+        }
+    }
+
+    // ------------------------------------------------------------------------
+    // Document ---------------------------------------------------------------
+    // ------------------------------------------------------------------------
+
     /**
      * Get the overwrite flag.
      *
@@ -73,6 +111,41 @@ public class Document {
         return overwrite;
     }
 
+    /**
+     * Get the dirty value.
+     *
+     * @return true if the buffer is dirty
+     */
+    public boolean isDirty() {
+        return dirty;
+    }
+
+    /**
+     * Save contents to file.
+     *
+     * @param filename file to save to
+     * @throws IOException if a java.io operation throws
+     */
+    public void saveToFilename(final String filename) throws IOException {
+        OutputStreamWriter output = null;
+        try {
+            output = new OutputStreamWriter(new FileOutputStream(filename),
+                "UTF-8");
+
+            for (Line line: lines) {
+                output.write(line.getRawString());
+                output.write("\n");
+            }
+
+            dirty = false;
+        }
+        finally {
+            if (output != null) {
+                output.close();
+            }
+        }
+    }
+
     /**
      * Set the overwrite flag.
      *
@@ -137,20 +210,24 @@ public class Document {
     }
 
     /**
-     * Construct a new Document from an existing text string.
+     * Get the character at the current cursor position in the text.
      *
-     * @param str the text string
-     * @param defaultColor the color for unhighlighted text
+     * @return the character, or -1 if the cursor is at the end of the line
      */
-    public Document(final String str, final CellAttributes defaultColor) {
-        this.defaultColor = defaultColor;
-
-        // TODO: set different colors based on file extension
-        highlighter.setJavaColors();
+    public int getChar() {
+        return lines.get(lineNumber).getChar();
+    }
 
-        String [] rawLines = str.split("\n");
-        for (int i = 0; i < rawLines.length; i++) {
-            lines.add(new Line(rawLines[i], this.defaultColor, highlighter));
+    /**
+     * Set the current cursor position of the editing line.  0-based.
+     *
+     * @param cursor the new cursor position
+     */
+    public void setCursor(final int cursor) {
+        if (cursor >= lines.get(lineNumber).getDisplayLength()) {
+            lines.get(lineNumber).end();
+        } else {
+            lines.get(lineNumber).setCursor(cursor);
         }
     }
 
@@ -163,7 +240,7 @@ public class Document {
         if (lineNumber < lines.size() - 1) {
             int x = lines.get(lineNumber).getCursor();
             lineNumber++;
-            if (x > lines.get(lineNumber).getDisplayLength()) {
+            if (x >= lines.get(lineNumber).getDisplayLength()) {
                 lines.get(lineNumber).end();
             } else {
                 lines.get(lineNumber).setCursor(x);
@@ -187,7 +264,7 @@ public class Document {
             if (lineNumber > lines.size() - 1) {
                 lineNumber = lines.size() - 1;
             }
-            if (x > lines.get(lineNumber).getDisplayLength()) {
+            if (x >= lines.get(lineNumber).getDisplayLength()) {
                 lines.get(lineNumber).end();
             } else {
                 lines.get(lineNumber).setCursor(x);
@@ -206,7 +283,7 @@ public class Document {
         if (lineNumber > 0) {
             int x = lines.get(lineNumber).getCursor();
             lineNumber--;
-            if (x > lines.get(lineNumber).getDisplayLength()) {
+            if (x >= lines.get(lineNumber).getDisplayLength()) {
                 lines.get(lineNumber).end();
             } else {
                 lines.get(lineNumber).setCursor(x);
@@ -230,7 +307,7 @@ public class Document {
             if (lineNumber < 0) {
                 lineNumber = 0;
             }
-            if (x > lines.get(lineNumber).getDisplayLength()) {
+            if (x >= lines.get(lineNumber).getDisplayLength()) {
                 lines.get(lineNumber).end();
             } else {
                 lines.get(lineNumber).setCursor(x);
@@ -241,21 +318,184 @@ public class Document {
     }
 
     /**
-     * Decrement the cursor by one.  If at the first column, do nothing.
+     * Decrement the cursor by one.  If at the first column on the first
+     * line, do nothing.
      *
      * @return true if the cursor position changed
      */
     public boolean left() {
-        return lines.get(lineNumber).left();
+        if (!lines.get(lineNumber).left()) {
+            // We are on the leftmost column, wrap
+            if (up()) {
+                end();
+            } else {
+                return false;
+            }
+        }
+        return true;
     }
 
     /**
-     * Increment the cursor by one.  If at the last column, do nothing.
+     * Increment the cursor by one.  If at the last column on the last line,
+     * do nothing.
      *
      * @return true if the cursor position changed
      */
     public boolean right() {
-        return lines.get(lineNumber).right();
+        if (!lines.get(lineNumber).right()) {
+            // We are on the rightmost column, wrap
+            if (down()) {
+                home();
+            } else {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Go back to the beginning of this word if in the middle, or the
+     * beginning of the previous word.
+     */
+    public void backwardsWord() {
+
+        // If at the beginning of a word already, push past it.
+        if ((getChar() != -1)
+            && (getRawLine().length() > 0)
+            && !Character.isSpace((char) getChar())
+        ) {
+            left();
+        }
+
+        // int line = lineNumber;
+        while ((getChar() == -1)
+            || (getRawLine().length() == 0)
+            || Character.isSpace((char) getChar())
+        ) {
+            if (left() == false) {
+                return;
+            }
+        }
+
+
+        assert (getChar() != -1);
+
+        if (!Character.isSpace((char) getChar())
+            && (getRawLine().length() > 0)
+        ) {
+            // Advance until at the beginning of the document or a whitespace
+            // is encountered.
+            while (!Character.isSpace((char) getChar())) {
+                int line = lineNumber;
+                if (left() == false) {
+                    // End of document, bail out.
+                    return;
+                }
+                if (lineNumber != line) {
+                    // We wrapped a line.  Here that counts as whitespace.
+                    right();
+                    return;
+                }
+            }
+        }
+
+        // We went one past the word, push back to the first character of
+        // that word.
+        right();
+        return;
+    }
+
+    /**
+     * Go to the beginning of the next word.
+     */
+    public void forwardsWord() {
+        int line = lineNumber;
+        while ((getChar() == -1)
+            || (getRawLine().length() == 0)
+        ) {
+            if (right() == false) {
+                return;
+            }
+            if (lineNumber != line) {
+                // We wrapped a line.  Here that counts as whitespace.
+                if (!Character.isSpace((char) getChar())) {
+                    // We found a character immediately after the line.
+                    // Done!
+                    return;
+                }
+                // Still looking...
+                line = lineNumber;
+            }
+        }
+        assert (getChar() != -1);
+
+        if (!Character.isSpace((char) getChar())
+            && (getRawLine().length() > 0)
+        ) {
+            // Advance until at the end of the document or a whitespace is
+            // encountered.
+            while (!Character.isSpace((char) getChar())) {
+                line = lineNumber;
+                if (right() == false) {
+                    // End of document, bail out.
+                    return;
+                }
+                if (lineNumber != line) {
+                    // We wrapped a line.  Here that counts as whitespace.
+                    if (!Character.isSpace((char) getChar())
+                        && (getRawLine().length() > 0)
+                    ) {
+                        // We found a character immediately after the line.
+                        // Done!
+                        return;
+                    }
+                    break;
+                }
+            }
+        }
+
+        while ((getChar() == -1)
+            || (getRawLine().length() == 0)
+        ) {
+            if (right() == false) {
+                return;
+            }
+            if (lineNumber != line) {
+                // We wrapped a line.  Here that counts as whitespace.
+                if (!Character.isSpace((char) getChar())) {
+                    // We found a character immediately after the line.
+                    // Done!
+                    return;
+                }
+                // Still looking...
+                line = lineNumber;
+            }
+        }
+        assert (getChar() != -1);
+
+        if (Character.isSpace((char) getChar())) {
+            // Advance until at the end of the document or a non-whitespace
+            // is encountered.
+            while (Character.isSpace((char) getChar())) {
+                if (right() == false) {
+                    // End of document, bail out.
+                    return;
+                }
+            }
+            return;
+        }
+
+        // We wrapped the line to get here.
+        return;
+    }
+
+    /**
+     * Get the raw string that matches this line.
+     *
+     * @return the string
+     */
+    public String getRawLine() {
+        return lines.get(lineNumber).getRawString();
     }
 
     /**
@@ -280,14 +520,64 @@ public class Document {
      * Delete the character under the cursor.
      */
     public void del() {
-        lines.get(lineNumber).del();
+        dirty = true;
+        int cursor = lines.get(lineNumber).getCursor();
+        if (cursor < lines.get(lineNumber).getDisplayLength() - 1) {
+            lines.get(lineNumber).del();
+        } else if (lineNumber < lines.size() - 2) {
+            // Join two lines
+            StringBuilder newLine = new StringBuilder(lines.
+                get(lineNumber).getRawString());
+            newLine.append(lines.get(lineNumber + 1).getRawString());
+            lines.set(lineNumber, new Line(newLine.toString(),
+                    defaultColor, highlighter));
+            lines.get(lineNumber).setCursor(cursor);
+            lines.remove(lineNumber + 1);
+        }
     }
 
     /**
      * Delete the character immediately preceeding the cursor.
      */
     public void backspace() {
-        lines.get(lineNumber).backspace();
+        dirty = true;
+        int cursor = lines.get(lineNumber).getCursor();
+        if (cursor > 0) {
+            lines.get(lineNumber).backspace();
+        } else if (lineNumber > 0) {
+            // Join two lines
+            lineNumber--;
+            String firstLine = lines.get(lineNumber).getRawString();
+            if (firstLine.length() > 0) {
+                // Backspacing combining two lines
+                StringBuilder newLine = new StringBuilder(firstLine);
+                newLine.append(lines.get(lineNumber + 1).getRawString());
+                lines.set(lineNumber, new Line(newLine.toString(),
+                        defaultColor, highlighter));
+                lines.get(lineNumber).setCursor(firstLine.length());
+                lines.remove(lineNumber + 1);
+            } else {
+                // Backspacing an empty line
+                lines.remove(lineNumber);
+                lines.get(lineNumber).setCursor(0);
+            }
+        }
+    }
+
+    /**
+     * Split the current line into two, like pressing the enter key.
+     */
+    public void enter() {
+        dirty = true;
+        int cursor = lines.get(lineNumber).getRawCursor();
+        String original = lines.get(lineNumber).getRawString();
+        String firstLine = original.substring(0, cursor);
+        String secondLine = original.substring(cursor);
+        lines.add(lineNumber + 1, new Line(secondLine, defaultColor,
+                highlighter));
+        lines.set(lineNumber, new Line(firstLine, defaultColor, highlighter));
+        lineNumber++;
+        lines.get(lineNumber).home();
     }
 
     /**
@@ -296,7 +586,8 @@ public class Document {
      *
      * @param ch the character to replace or insert
      */
-    public void addChar(final char ch) {
+    public void addChar(final int ch) {
+        dirty = true;
         if (overwrite) {
             lines.get(lineNumber).replaceChar(ch);
         } else {
@@ -337,4 +628,13 @@ public class Document {
         return n;
     }
 
+    /**
+     * Get the current line length.
+     *
+     * @return the number of cells needed to display the current line
+     */
+    public int getLineLength() {
+        return lines.get(lineNumber).getDisplayLength();
+    }
+
 }