devc代码补全没效果_从零开始写文本编辑器(二十八):自动补全(上)
前言
我本沒打算這么早就寫“自動補全”功能的。
但是在寫XML資源編輯時,為了實現自動引用已有資源@string/xxx,需要一個合適的列表來讓我選擇。這樣能防止拼寫錯誤。
也就是說,初衷是為了防止拼寫錯誤,結果分析了性價比,還是上自動補全功能吧。
XML自動補全是一個較大的模塊,它分為多個子模塊,本篇發稿時,全部模塊還遠沒完成。在本篇中只講述自動補全的GUI模塊,并演示 java 關鍵字代碼補全作結尾。
調研自動補全 Auto Complete
“自動補全”是一個寬泛的說法,具體到代碼編輯器,就是“代碼補全”,本篇統稱為“自動補全”。
自動補全的好處:
- 自動匹配已知輸入字符串,猜測完整字符串
- 簡單如:從首字符開始連續匹配
- 高級如:不連續匹配
- 自動彈出選擇列表
- 用簡單的 UP/DOWN 按鍵,瀏覽選擇項
- 用簡單的 ENTER 鍵,選擇補全項,并自動插入光標位置。
“自動補全”的流程圖
這是一張粗糙的流程圖,還有小細節,用代碼更直觀表述。但在上代碼之前,先總體說下功能類。
類清單
- Complete:補全。提供“補全”的列表數據
- EatEnter:“吃掉回車”。因為回車符與退出符不同,回車符是可顯示字符,當用于確認插入操作時,要主動吃掉。
- Focus:焦點。當顯示彈出菜單列表時,要把焦點交還給編輯器,否則無法持續編輯。
- FrameCode:代碼窗口。這是我個人習慣用Frame前綴表示某窗口類。
- Insert:插入。完成代碼插入,內部記憶了插入的光標位置。
- ListComplete:補全列表。同Frame一樣,List前綴表示它是一個JList,是顯示補全數據的容器。
- Location:位置。它計算出補全列表彈出的坐標x, y位置,讓左上角臨近光標。
- PopupMenuComplete:補全彈出菜單。同Frame一樣,PopupMenu前綴表示,它是一個JPopupMenu,它是ListComplete的容器,自動處理了 Escape 等邏輯。
- TextEditor:編輯器。這是不是前些篇中的編輯,它沒有行號等功能。只是我在“自動補全”中臨時編寫的。
OK,全部類就是這些了。
用例:彈出菜單顯示補全列表
public void keyReleased(java.awt.event.KeyEvent e) {int keyCode = e.getKeyCode();if (keyCode == KeyEvent.VK_UP) {popupMenuComplete.selectPrevious();} else if (keyCode == KeyEvent.VK_DOWN) {popupMenuComplete.selectNext();} else if (keyCode == KeyEvent.VK_ESCAPE) {popupMenuComplete.setVisible(false);popupMenuComplete.clean();} else if (Character.isWhitespace(e.getKeyChar())) {popupMenuComplete.setVisible(false);popupMenuComplete.clean();} else {String headString = textEditor.getHeadString();if (headString != null && headString.length() > 0) {insert.setPosition(textEditor.getCaretPosition());popupMenuComplete.receiveInputString(headString);Point point = location.getLocation();popupMenuComplete.show(textEditor, point.x, point.y);focus.backToTextComponent();}} };當用戶輸入后,偵聽到可見字符輸入,編輯器從光標處向前搜索已知輸入字符串 headString。
為了方便記憶,我把補全字符串分解為:頭部(head string)和 尾部(tail string),這是headString命名的由來。
/*** * @return null if condition failed.*/ public String getHeadString() {int caretPosition = getCaretPosition();String text = getText();int start = indexOfWordStart();if (start > caretPosition) {return null;}return text.substring(start, caretPosition); }比如:輸入'p',則返回 "p"。
然后彈出菜單(此時不可見),開始接收已知字符串,進行匹配。
public void receiveInputString(String headString) {this.headString = headString; // String[] data = complete.createListData(headString);Vector<String> data = complete.createListKeywordsJava(headString);listComplete.setListData(data);listComplete.setSelectedIndex(0); }本篇中匹配數據集為 java 關鍵字,使用簡單的起始字符串匹配。
public Vector<String> createListKeywordsJava(String headString) {Vector<String> vector = new Vector<String>();for (String string : keywords) {if (string.startsWith(headString)) {vector.add(string);}}return vector; }private String[] keywords = new String[] { "abstract", "assert", "boolean", "break", "byte", "case", "catch","char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final","finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long","native", "new", "package", "private", "protected", "public", "return", "strictfp", "short", "static","super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile","while" };返回的字符串向量送給列表顯示,并默認選中第1項(index=0)。
返回窗口領空后,把焦點還給編輯器(JTextPane textEditor)。
package editor.xml.visual.autocomplete2;import javax.swing.text.JTextComponent;public class Focus {private JTextComponent textComponent;public Focus(JTextComponent textComponent) {this.textComponent = textComponent;}/*** after show pop up menu, move focus back on text component.*/public void backToTextComponent() {textComponent.requestFocus();} }用例:彈出菜單的位置計算
package editor.xml.visual.autocomplete2;import java.awt.Point; import java.awt.geom.Rectangle2D;import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent;public class Location {private JTextComponent textComponent;public Location(JTextComponent textComponent) {this.textComponent = textComponent;}/*** * @return point location in text component, not base on screen.*/private Point getCaretLocation() {try {int caretPosition = textComponent.getCaretPosition();Rectangle2D rectangle2d = textComponent.modelToView2D(caretPosition);int x = (int) rectangle2d.getMaxX();int y = (int) rectangle2d.getMaxY();return new Point(x, y);} catch (BadLocationException e2) {e2.printStackTrace();return null;}}/*** <pre>* 提示:invoker 要使用 textComponent為參數* </pre>* * @return point of location left-top on invoker.* */public Point getLocation() {Point point = getCaretLocation();int baseY = textComponent.getBaseline(0, 0);point.y += baseY;return point;}}這段邏輯主要是控件坐標API的使用,invoker 的目標容器會影響顯示的父位置,進而會影響總的坐標計算,為了靈活性,我不想寫“死“,所以只好加注釋說明。
Point point = location.getLocation(); popupMenuComplete.show(textEditor, point.x, point.y);上述的 show(textEditor, ...,如果把 textEditor換成了窗口等父控件,則顯示坐標就會計算偏離。
用例:瀏覽列表
if (keyCode == KeyEvent.VK_UP) {popupMenuComplete.selectPrevious(); } else if (keyCode == KeyEvent.VK_DOWN) {popupMenuComplete.selectNext();// PopupMenuComplete.java public void selectPrevious() {int hopeIndex = listComplete.getSelectedIndex() - 1;int index = Math.max(hopeIndex, 0);listComplete.setSelectedIndex(index); }public void selectNext() {int hopeIndex = listComplete.getSelectedIndex() + 1;int index = Math.max(hopeIndex, 0);listComplete.setSelectedIndex(index); }此處可以寫成循環瀏覽,eclipse 就是可循環瀏覽,我這里就不復雜化。
用例:取消補全
} else if (keyCode == KeyEvent.VK_ESCAPE) {popupMenuComplete.setVisible(false);popupMenuComplete.clean();用例:插入補全
package editor.xml.visual.autocomplete2;import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent;public class Insert {public Insert(JTextComponent textComponent) {this.textComponent = textComponent;}private JTextComponent textComponent;private int position;public int getPosition() {return position;}public void setPosition(int position) {this.position = position;}public void insert(String tailString) throws BadLocationException {textComponent.getDocument().insertString(position, tailString, null);} }記得要“吃掉回車符”哦!
package editor.xml.visual.autocomplete2;import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent;public class EatEnter {private JTextComponent textComponent;public EatEnter(JTextComponent textComponent) {this.textComponent = textComponent;}public void eat() {final int position = textComponent.getCaretPosition();try {textComponent.getDocument().remove(position - 1, 1);} catch (BadLocationException e) {e.printStackTrace();}} }看看效果
在演示中,好像在第二行處有BUG,in的前綴怎么會出現 if 關鍵字。這些BUG我后續再迭代修正,本篇主要邏輯就是這些。
這是一個非常粗糙的膠水式模塊,后續慢慢會演變成一個自動補全框架。
以上~
參考資料
- stackoverflow 搜索 "auto complete" 若干文章
工具
- Gif錄制軟件:ScreenToGif
總結
以上是生活随笔為你收集整理的devc代码补全没效果_从零开始写文本编辑器(二十八):自动补全(上)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在辣妈汇添加收货地址方法图解
- 下一篇: s3c2440移植MQTT