Merge commit '77d3a60869e7a780c6ae069e51530e1eacece5e2'
[fanfix.git] / src / jexer / teditor / Line.java
index de1265982c67e3190a122a1dae0e692ba7e2a17e..b5c980a59f9c9812b6f6a84ce832fe9781051702 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"),
@@ -32,6 +32,8 @@ import java.util.ArrayList;
 import java.util.List;
 
 import jexer.bits.CellAttributes;
+import jexer.bits.GraphicsChars;
+import jexer.bits.StringUtils;
 
 /**
  * A Line represents a single line of text on the screen, as a collection of
@@ -39,6 +41,10 @@ import jexer.bits.CellAttributes;
  */
 public class Line {
 
+    // ------------------------------------------------------------------------
+    // Variables --------------------------------------------------------------
+    // ------------------------------------------------------------------------
+
     /**
      * The list of words.
      */
@@ -55,27 +61,129 @@ public class Line {
     private Highlighter highlighter = null;
 
     /**
-     * The current cursor position on this line.
+     * The current edition position on this line.
+     */
+    private int position = 0;
+
+    /**
+     * The current editing position screen column number.
+     */
+    private int screenPosition = 0;
+
+    /**
+     * The raw text of this line, what is passed to Word to determine
+     * highlighting behavior.
+     */
+    private StringBuilder rawText;
+
+    // ------------------------------------------------------------------------
+    // Constructors -----------------------------------------------------------
+    // ------------------------------------------------------------------------
+
+    /**
+     * Construct a new Line from an existing text string, and highlight
+     * certain strings.
+     *
+     * @param str the text string
+     * @param defaultColor the color for unhighlighted text
+     * @param highlighter the highlighter to use
+     */
+    public Line(final String str, final CellAttributes defaultColor,
+        final Highlighter highlighter) {
+
+        this.defaultColor = defaultColor;
+        this.highlighter = highlighter;
+
+        this.rawText = new StringBuilder();
+        int col = 0;
+        for (int i = 0; i < str.length(); i++) {
+            char ch = str.charAt(i);
+            if (ch == '\t') {
+                // Expand tabs
+                int j = col % 8;
+                do {
+                    rawText.append(' ');
+                    j++;
+                    col++;
+                } while ((j % 8) != 0);
+                continue;
+            }
+            if ((ch <= 0x20) || (ch == 0x7F)) {
+                // Replace all other C0 bytes with CP437 glyphs.
+                rawText.append(GraphicsChars.CP437[(int) ch]);
+                col++;
+                continue;
+            }
+
+            rawText.append(ch);
+            col++;
+        }
+
+        scanLine();
+    }
+
+    /**
+     * Construct a new Line from an existing text string.
+     *
+     * @param str the text string
+     * @param defaultColor the color for unhighlighted text
+     */
+    public Line(final String str, final CellAttributes defaultColor) {
+        this(str, defaultColor, null);
+    }
+
+    /**
+     * Private constructor used by dup().
      */
-    private int cursor = 0;
+    private Line() {
+        // NOP
+    }
+
+    // ------------------------------------------------------------------------
+    // Line -------------------------------------------------------------------
+    // ------------------------------------------------------------------------
 
     /**
-     * The current word that the cursor position is in.
+     * Create a duplicate instance.
+     *
+     * @return duplicate intance
      */
-    private Word currentWord;
+    public Line dup() {
+        Line other = new Line();
+        other.defaultColor = defaultColor;
+        other.highlighter = highlighter;
+        other.position = position;
+        other.screenPosition = screenPosition;
+        other.rawText = new StringBuilder(rawText);
+        other.scanLine();
+        return other;
+    }
 
     /**
-     * We use getDisplayLength() a lot, so cache the value.
+     * Get a (shallow) copy of the words in this line.
+     *
+     * @return a copy of the word list
      */
-    private int displayLength = -1;
+    public List<Word> getWords() {
+        return new ArrayList<Word>(words);
+    }
 
     /**
-     * Get the current cursor position.
+     * Get the current cursor position in the text.
+     *
+     * @return the cursor position
+     */
+    public int getRawCursor() {
+        return position;
+    }
+
+    /**
+     * Get the current cursor position on screen.
      *
      * @return the cursor position
      */
     public int getCursor() {
-        return cursor;
+        return screenPosition;
     }
 
     /**
@@ -91,17 +199,20 @@ public class Line {
             throw new IndexOutOfBoundsException("Max length is " +
                 getDisplayLength() + ", requested position " + cursor);
         }
-        this.cursor = cursor;
-        // TODO: set word
+        screenPosition = cursor;
+        position = screenToTextPosition(screenPosition);
     }
 
     /**
-     * Get a (shallow) copy of the list of words.
+     * Get the character at the current cursor position in the text.
      *
-     * @return the list of words
+     * @return the character, or -1 if the cursor is at the end of the line
      */
-    public List<Word> getWords() {
-        return new ArrayList<Word>(words);
+    public int getChar() {
+        if (position == rawText.length()) {
+            return -1;
+        }
+        return rawText.codePointAt(position);
     }
 
     /**
@@ -110,73 +221,67 @@ public class Line {
      * @return the number of cells needed to display this line
      */
     public int getDisplayLength() {
-        if (displayLength != -1) {
-            return displayLength;
-        }
-        int n = 0;
-        for (Word word: words) {
-            n += word.getDisplayLength();
-        }
-        displayLength = n;
+        int n = StringUtils.width(rawText.toString());
 
-        // If we have any visible characters, add one to the display so that
-        // the cursor is immediately after the data.
-        if (displayLength > 0) {
-            displayLength++;
+        if (n > 0) {
+            // If we have any visible characters, add one to the display so
+            // that the position is immediately after the data.
+            return n + 1;
         }
-        return displayLength;
+        return n;
     }
 
     /**
-     * Construct a new Line from an existing text string, and highlight
-     * certain strings.
+     * Get the raw string that matches this line.
      *
-     * @param str the text string
-     * @param defaultColor the color for unhighlighted text
-     * @param highlighter the highlighter to use
+     * @return the string
      */
-    public Line(final String str, final CellAttributes defaultColor,
-        final Highlighter highlighter) {
+    public String getRawString() {
+        return rawText.toString();
+    }
 
-        this.defaultColor = defaultColor;
-        this.highlighter = highlighter;
+    /**
+     * Get the raw length of this line.
+     *
+     * @return the length of this line in characters, which may be different
+     * from the number of cells needed to display it
+     */
+    public int length() {
+        return rawText.length();
+    }
 
-        currentWord = new Word(this.defaultColor, this.highlighter);
-        words.add(currentWord);
-        for (int i = 0; i < str.length(); i++) {
-            char ch = str.charAt(i);
-            Word newWord = currentWord.addChar(ch);
-            if (newWord != currentWord) {
+    /**
+     * Scan rawText and make words out of it.  Note package private access.
+     */
+    void scanLine() {
+        words.clear();
+        Word word = new Word(this.defaultColor, this.highlighter);
+        words.add(word);
+        for (int i = 0; i < rawText.length();) {
+            int ch = rawText.codePointAt(i);
+            i += Character.charCount(ch);
+            Word newWord = word.addChar(ch);
+            if (newWord != word) {
                 words.add(newWord);
-                currentWord = newWord;
+                word = newWord;
             }
         }
-        for (Word word: words) {
-            word.applyHighlight();
+        for (Word w: words) {
+            w.applyHighlight();
         }
     }
 
-    /**
-     * Construct a new Line from an existing text string.
-     *
-     * @param str the text string
-     * @param defaultColor the color for unhighlighted text
-     */
-    public Line(final String str, final CellAttributes defaultColor) {
-        this(str, defaultColor, null);
-    }
-
     /**
      * Decrement the cursor by one.  If at the first column, do nothing.
      *
      * @return true if the cursor position changed
      */
     public boolean left() {
-        if (cursor == 0) {
+        if (position == 0) {
             return false;
         }
-        // TODO: switch word
-        cursor--;
+        screenPosition -= StringUtils.width(rawText.codePointBefore(position));
+        position -= Character.charCount(rawText.codePointBefore(position));
         return true;
     }
 
@@ -189,11 +294,14 @@ public class Line {
         if (getDisplayLength() == 0) {
             return false;
         }
-        if (cursor == getDisplayLength() - 1) {
+        if (screenPosition == getDisplayLength() - 1) {
             return false;
         }
-        // TODO: switch word
-        cursor++;
+        if (position < rawText.length()) {
+            screenPosition += StringUtils.width(rawText.codePointAt(position));
+            position += Character.charCount(rawText.codePointAt(position));
+        }
+        assert (position <= rawText.length());
         return true;
     }
 
@@ -203,9 +311,9 @@ public class Line {
      * @return true if the cursor position changed
      */
     public boolean home() {
-        if (cursor > 0) {
-            cursor = 0;
-            currentWord = words.get(0);
+        if (position > 0) {
+            position = 0;
+            screenPosition = 0;
             return true;
         }
         return false;
@@ -217,12 +325,9 @@ public class Line {
      * @return true if the cursor position changed
      */
     public boolean end() {
-        if (cursor != getDisplayLength() - 1) {
-            cursor = getDisplayLength() - 1;
-            if (cursor < 0) {
-                cursor = 0;
-            }
-            currentWord = words.get(words.size() - 1);
+        if (screenPosition != getDisplayLength() - 1) {
+            position = rawText.length();
+            screenPosition = StringUtils.width(rawText.toString());
             return true;
         }
         return false;
@@ -232,14 +337,50 @@ public class Line {
      * Delete the character under the cursor.
      */
     public void del() {
-        // TODO
+        assert (words.size() > 0);
+
+        if (screenPosition < getDisplayLength()) {
+            int n = Character.charCount(rawText.codePointAt(position));
+            for (int i = 0; i < n; i++) {
+                rawText.deleteCharAt(position);
+            }
+        }
+
+        // Re-scan the line to determine the new word boundaries.
+        scanLine();
     }
 
     /**
      * Delete the character immediately preceeding the cursor.
+     *
+     * @param tabSize the tab stop size
+     * @param backspaceUnindents If true, backspace at an indent level goes
+     * back a full indent level.  If false, backspace always goes back one
+     * column.
      */
-    public void backspace() {
-        // TODO
+    public void backspace(final int tabSize, final boolean backspaceUnindents) {
+        if ((backspaceUnindents == true)
+            && (tabSize > 0)
+            && (screenPosition > 0)
+            && (rawText.charAt(position - 1) == ' ')
+            && ((screenPosition % tabSize) == 0)
+        ) {
+            boolean doBackTab = true;
+            for (int i = 0; i < position; i++) {
+                if (rawText.charAt(i) != ' ') {
+                    doBackTab = false;
+                    break;
+                }
+            }
+            if (doBackTab) {
+                backTab(tabSize);
+                return;
+            }
+        }
+
+        if (left()) {
+            del();
+        }
     }
 
     /**
@@ -247,8 +388,15 @@ public class Line {
      *
      * @param ch the character to insert
      */
-    public void addChar(final char ch) {
-        // TODO
+    public void addChar(final int ch) {
+        if (screenPosition < getDisplayLength() - 1) {
+            rawText.insert(position, Character.toChars(ch));
+        } else {
+            rawText.append(Character.toChars(ch));
+        }
+        position += Character.charCount(ch);
+        screenPosition += StringUtils.width(ch);
+        scanLine();
     }
 
     /**
@@ -256,8 +404,95 @@ public class Line {
      *
      * @param ch the character to replace
      */
-    public void replaceChar(final char ch) {
-        // TODO
+    public void replaceChar(final int ch) {
+        if (screenPosition < getDisplayLength() - 1) {
+            // Replace character
+            String oldText = rawText.toString();
+            rawText = new StringBuilder(oldText.substring(0, position));
+            rawText.append(Character.toChars(ch));
+            rawText.append(oldText.substring(position + 1));
+            screenPosition += StringUtils.width(rawText.codePointAt(position));
+            position += Character.charCount(ch);
+        } else {
+            rawText.append(Character.toChars(ch));
+            position += Character.charCount(ch);
+            screenPosition += StringUtils.width(ch);
+        }
+        scanLine();
+    }
+
+    /**
+     * Determine string position from screen position.
+     *
+     * @param screenPosition the position on screen
+     * @return the equivalent position in text
+     */
+    private int screenToTextPosition(final int screenPosition) {
+        if (screenPosition == 0) {
+            return 0;
+        }
+
+        int n = 0;
+        for (int i = 0; i < rawText.length(); i++) {
+            n += StringUtils.width(rawText.codePointAt(i));
+            if (n >= screenPosition) {
+                return i + 1;
+            }
+        }
+        // screenPosition exceeds the available text length.
+        throw new IndexOutOfBoundsException("screenPosition " + screenPosition +
+            " exceeds available text length " + rawText.length());
+    }
+
+    /**
+     * Trim trailing whitespace from line, repositioning cursor if needed.
+     */
+    public void trimRight() {
+        if (rawText.length() == 0) {
+            return;
+        }
+        if (!Character.isWhitespace(rawText.charAt(rawText.length() - 1))) {
+            return;
+        }
+        while ((rawText.length() > 0)
+            && Character.isWhitespace(rawText.charAt(rawText.length() - 1))
+        ) {
+            rawText.deleteCharAt(rawText.length() - 1);
+        }
+        if (position >= rawText.length()) {
+            end();
+        }
+        scanLine();
+    }
+
+    /**
+     * Handle the tab character.
+     *
+     * @param tabSize the tab stop size
+     */
+    public void tab(final int tabSize) {
+        if (tabSize > 0) {
+            do {
+                addChar(' ');
+            } while ((screenPosition % tabSize) != 0);
+        }
+    }
+
+    /**
+     * Handle the backtab (shift-tab) character.
+     *
+     * @param tabSize the tab stop size
+     */
+    public void backTab(final int tabSize) {
+        if ((tabSize > 0) && (screenPosition > 0)
+            && (rawText.charAt(position - 1) == ' ')
+        ) {
+            do {
+                backspace(tabSize, false);
+            } while (((screenPosition % tabSize) != 0)
+                && (screenPosition > 0)
+                && (rawText.charAt(position - 1) == ' '));
+        }
     }
 
 }