public void commandAction(Command command, Displayable displayable) { if ((displayable == D_MAIN) && D_MAIN.Responds()) { if (command == c_exit) { exitMIDlet(); } if (command == c_history) { switchDisplayable(null, getL_history()); Stack st = D_MAIN.getEqHS(); Enumeration en = st.elements(); l_history.deleteAll(); while (en.hasMoreElements()) { l_history.append((String) en.nextElement(), null); } } if (command == c_tovars) { getL_vars().deleteAll(); StringBuffer sb; Enumeration values = D_MAIN.getEqVars().elements(); Enumeration names = D_MAIN.getEqVars().keys(); String name; Real value; while ((values.hasMoreElements()) && (names.hasMoreElements())) { name = String.valueOf(names.nextElement()); value = new Real(String.valueOf((values.nextElement()))); Real.NumberFormat n = new Real.NumberFormat(); n.maxwidth = 17; n.fse = Real.NumberFormat.FSE_NONE; sb = new StringBuffer(value.toString(n)); if (chartools.contains(sb, 'e')) { StringBuffer ev = new StringBuffer(); for (int i = sb.length() - 1; i > -1; --i) { if (sb.charAt(i) == 'e') { sb.deleteCharAt(i); break; } ev.append(sb.charAt(i)); sb.deleteCharAt(i); } ev.reverse(); sb.append(" * 10^(" + ev + ")"); if ((!(sb.equals(new StringBuffer("")))) && (!(name.equals(""))) && (!(sb.equals(new StringBuffer("null")))) && (!(name.equals("null")))) { l_vars.append(name + " = " + sb.toString(), null); } } else { if ((!(sb.equals(new StringBuffer("")))) && (!(name.equals(""))) && (!(sb.equals(new StringBuffer("null")))) && (!(name.equals("null")))) { getL_vars().append(name + " = " + sb.toString(), null); } } } switchDisplayable(null, getL_vars()); } } if (displayable == f_welcome) { if (command == c_canvas) { switchDisplayable(null, D_MAIN); } } else if (displayable == form) { if (command == c_history) { } else if (command == c_tovars) { } } else if (displayable == l_history) { if (command == List.SELECT_COMMAND) { l_historyAction(); } else if (command == c_canvas) { switchDisplayable(null, D_MAIN); } else if (command == c_insert) { if (l_history.size() != 0) { StringBuffer sb = new StringBuffer(); String his = l_history.getString(l_history.getSelectedIndex()); boolean p_end = false; for (int i = 0; i < his.length(); i++) { if (his.charAt(i) == '=') { break; } if (p_end) { sb.append(his.charAt(i)); } if (his.charAt(i) == ':') { p_end = true; } } sb.deleteCharAt(sb.length() - 1); D_MAIN.appendDispCont(" " + sb.toString()); } switchDisplayable(null, D_MAIN); D_MAIN.repaint(); } } else if (displayable == l_vars) { if (command == List.SELECT_COMMAND) { l_varsAction(); } else if (command == c_canvas) { switchDisplayable(null, D_MAIN); } else if (command == c_delvar) { try { StringBuffer sb = new StringBuffer(); String his = l_vars.getString(l_vars.getSelectedIndex()); for (int i = 0; i < his.length(); i++) { if (his.charAt(i) == '=') { break; } sb.append(his.charAt(i)); } D_MAIN.deletevar(sb.toString().trim()); l_vars.delete(l_vars.getSelectedIndex()); } catch (error er) { switchDisplayable(null, getA_error()); a_error.setString(er.getMessage()); } } else if (command == c_insert) { StringBuffer sb = new StringBuffer(); String his = l_vars.getString(l_vars.getSelectedIndex()); for (int i = 0; i < his.length(); i++) { if (his.charAt(i) == '=') { break; } sb.append(his.charAt(i)); } D_MAIN.appendDispCont(sb.toString()); switchDisplayable(null, D_MAIN); D_MAIN.repaint(); } } }
public static void decry() { try { BufferedReader bf = new BufferedReader(new FileReader("ciphertext.txt")); BufferedWriter wr = new BufferedWriter(new FileWriter("plaintext.txt")); char rkey[] = new char[26]; for (char i = 'a'; i <= 'z'; i++) { if (key.charAt(i - 'a') > 'z' || key.charAt(i - 'a') < 'a') continue; rkey[key.charAt(i - 'a') - 'a'] = i; } System.out.println(rkey); StringBuffer strb; String str; while (((str = bf.readLine())) != null) { strb = new StringBuffer(str); // System.out.println(strb); // String ans; for (int i = 0; i < strb.length(); i++) { if (strb.charAt(i) >= 'a' && strb.charAt(i) <= 'z') { strb.setCharAt(i, rkey[strb.charAt(i) - 'a']); } } System.out.println(strb.toString()); wr.write(strb.toString()); wr.newLine(); } // keyf.close(); wr.close(); bf.close(); } catch (IOException e) { } }
/** * Constructs a new path from current user path. This is an easy way to get a path if the user * specified, for example, "..\Java" as new path. This method will return the argument if this one * is a path to a root (i.e, if <code>change</code> is equal to C:\Jdk, constructPath will return * C:\Jdk). * * @param change The modification to apply to the path */ public static String constructPath(String change) { if (beginsWithRoot(change)) return change; StringBuffer newPath = new StringBuffer(getUserDirectory()); char current; char lastChar = '\0'; boolean toAdd = false; change = change.trim(); StringBuffer buf = new StringBuffer(change.length()); for (int i = 0; i < change.length(); i++) { switch ((current = change.charAt(i))) { case '.': if (lastChar == '.') { String parent = (new File(newPath.toString())).getParent(); if (parent != null) newPath = new StringBuffer(parent); } else if ((lastChar != '\0' && lastChar != '\\' && lastChar != '/') || (i < change.length() - 1 && change.charAt(i + 1) != '.')) buf.append('.'); lastChar = '.'; break; case '\\': case '/': if (lastChar == '\0') { newPath = new StringBuffer(getRoot(newPath.toString())); } else { char c = newPath.charAt(newPath.length() - 1); if (c != '\\' && c != '/') newPath.append(File.separator).append(buf.toString()); else newPath.append(buf.toString()); buf = new StringBuffer(); toAdd = false; } lastChar = '\\'; break; case '~': if (i < change.length() - 1) { if (change.charAt(i + 1) == '\\' || change.charAt(i + 1) == '/') newPath = new StringBuffer(getHomeDirectory()); else buf.append('~'); } else if (i == 0) newPath = new StringBuffer(getHomeDirectory()); else buf.append('~'); lastChar = '~'; break; default: lastChar = current; buf.append(current); toAdd = true; break; } } if (toAdd) { char c = newPath.charAt(newPath.length() - 1); if (c != '\\' && c != '/') newPath.append(File.separator).append(buf.toString()); else newPath.append(buf.toString()); } return newPath.toString(); }
public TextState copyAll() { TextState tmp = copyState(); if (s.length() == 0) return tmp; for (int i = 0; i < s.length(); i++) { tmp.s.append(s.charAt(i)); } return tmp; }
public static String getRandomString(int length) { StringBuffer sb = new StringBuffer(); Random r = new Random(); int range = buffer.length(); for (int i = 0; i < length; i++) { sb.append(buffer.charAt(r.nextInt(range))); } return sb.toString(); }
public String getPropertyName(String name) { // Set the first letter of the property name to lower-case StringBuffer propertyName = new StringBuffer(name); char c = propertyName.charAt(0); if (c >= 'A' && c <= 'Z') { c -= 'A' - 'a'; propertyName.setCharAt(0, c); } return propertyName.toString(); }
public void run() { // synchronized(str){ for (int i = 0; i < 100; i++) { System.out.print(str); } str.replace(0, 1, ("" + (char) ((int) (str.charAt(0)) + 1))); System.out.println("str NOW " + str); // } System.out.println("current Thread exiting; str now " + str); }
// return all grantees: thr_0, thr_1, thr_2 ..., excluding itself private static String getAllGrantees() { StringBuffer aStr = new StringBuffer(" "); Map<String, String> userPasswd = (Map<String, String>) SQLBB.getBB().getSharedMap().get(SQLSecurityTest.userPasswdMap); for (Map.Entry<String, String> e : userPasswd.entrySet()) { if (!e.getKey().equalsIgnoreCase("thr_" + RemoteTestModule.getCurrentThread().getThreadId())) aStr.append(e.getKey() + ", "); } if (aStr.charAt(aStr.length() - 2) == ',') { aStr.deleteCharAt(aStr.length() - 2); } aStr.deleteCharAt(0); // delete the leading space return aStr.toString(); }
/** * This method inserts a blank character between to consecutive newline characters if encoutered. * Also appends a blank character at the beginning of the text, if the first character is a * newline character and at the end of the text, if the last character is also a newline. This is * useful when trying to layout the paragraphs. Thanks to Teodor Danciu for this this method (c) * 2003 Teodor Danciu */ public static String treatNewLineChars(String source) { String result = source; if (source != null && source.length() > 0) { StringBuffer sbuffer = new StringBuffer(source); // insert a blank character between every two consecutives // newline characters int offset = source.length() - 1; int pos = source.lastIndexOf("\n\n", offset); while (pos >= 0 && offset > 0) { sbuffer = sbuffer.insert(pos + 1, " "); offset = pos - 1; pos = source.lastIndexOf("\n\n", offset); } // append a blank character at the and of the text // if the last character is a newline character if (sbuffer.charAt(sbuffer.length() - 1) == '\n') { sbuffer.append(' '); } // append a blank character at the begining of the text // if the first character is a newline character if (sbuffer.charAt(0) == '\n') { sbuffer.insert(0, ' '); } result = sbuffer.toString(); } // remove this if you want to treat the tab characters in a special way result = replaceTabWithBlank(result); return result; }
/** * Getters/Setters are supposed to be kept with their associated property. Search the list of * entries to find the property and attach the setter. * * @param entries list of all items (methods, fields) in the class. */ private void hookGetterToProperty(List<ClassContentsEntry> entries) { ListIterator<ClassContentsEntry> li = entries.listIterator(); String property = MethodUtil.getPropertyName((PsiMethod) myEnd); while (li.hasNext()) { Object o = li.next(); if (o instanceof FieldEntry) { FieldEntry fe = (FieldEntry) o; StringBuffer sb = new StringBuffer(fe.getName()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); if (fe.getGetterMethod() == null && property.equals(sb.toString())) { fe.setGetterMethod(this); myKeptWithProperty = true; break; } } } }
private String formatName(String name) { StringBuffer propertyName = new StringBuffer(); if (lowerCase) propertyName.append(name.toLowerCase()); else propertyName.append(name); char c = propertyName.charAt(0); if (firstLetterUpperCase) { if (c >= 'a' && c <= 'z') { c += 'A' - 'a'; } } else { if (c >= 'A' && c <= 'Z') { c -= 'A' - 'a'; } } propertyName.setCharAt(0, c); return propertyName.toString(); }
// return optionally any insert, delete, trigger, select [col list], update [col list] private String getPrivilegeLists(String tableName) { StringBuffer aStr = new StringBuffer(" "); for (int i = 0; i < tablePriv.length; i++) { if (SQLTest.random.nextBoolean()) { aStr.append(tablePriv[i]); // insert delete etc if (i > 2) { aStr.append(getColumnLists(tableName)); // column list for the table } // may include column list aStr.append(", "); } } if (aStr.charAt(aStr.length() - 2) == ',') { aStr.deleteCharAt(aStr.length() - 2); } aStr.deleteCharAt(0); // delete the leading space return aStr.toString(); }
private void addPattern( String verb, String input, Middleware[] handler, List<PatternBinding> bindings) { // We need to search for any :<token name> tokens in the String and replace them with named // capture groups Matcher m = Pattern.compile(":([A-Za-z][A-Za-z0-9_]*)").matcher(input); StringBuffer sb = new StringBuffer(); Set<String> groups = new HashSet<>(); while (m.find()) { String group = m.group().substring(1); if (groups.contains(group)) { throw new IllegalArgumentException( "Cannot use identifier " + group + " more than once in pattern string"); } m.appendReplacement(sb, "(?<$1>[^\\/]+)"); groups.add(group); } m.appendTail(sb); // ignore tailing slash if not part of the input, not really REST but common on other frameworks if (sb.charAt(sb.length() - 1) != '/') { sb.append("\\/?$"); } Pattern regex = Pattern.compile(sb.toString()); boolean exists = false; // verify if the binding already exists, if yes add to it for (PatternBinding pb : bindings) { if (pb.isFor(input)) { exists = true; pb.addMiddleware(handler); break; } } if (!exists) { PatternBinding binding = new PatternBinding(hashCode(), verb, input, regex, groups, handler); bindings.add(binding); } // also pass the vertx object to the routes for (Middleware h : handler) { if (!h.isInitialized() && isInitialized()) { h.init(yoke, mount); } } }
// returns column list: column-id, column-id ... private String getColumnLists(String tableName) { List<String> colNames = (List<String>) tableCols.get(tableName); StringBuffer aStr = new StringBuffer(" "); for (int i = 0; i < colNames.size(); i++) { if (SQLTest.random.nextBoolean()) { aStr.append(colNames.get(i) + ", "); } } if (aStr.charAt(aStr.length() - 2) == ',') { aStr.deleteCharAt(aStr.length() - 2); } aStr.deleteCharAt(0); // delete the leading space if (aStr.length() != 1) { aStr.insert(1, '('); aStr.append(')'); } // has column return aStr.toString(); }
public Vector getCloseTags(String desc) { final StringBuffer buf = new StringBuffer(desc); final Vector tags = new Vector(); StringBuffer bit = null; char quotes = '\0'; int i = -1; char lastC = ' '; while ((++i) < buf.length()) { switch (buf.charAt(i)) { case '<': if (quotes != '\0') bit = null; else if (bit != null) { if (MXP.tagDebug) { System.out.println("/TAG/CLOSER2S=" + Util.toStringList(tags)); System.out.flush(); } return tags; } else bit = new StringBuffer(""); break; case '>': if ((quotes == '\0') && (bit != null) && (bit.toString().trim().length() > 0)) tags.add(bit.toString().toUpperCase().trim()); bit = null; break; case ' ': case '\t': if ((quotes == '\0') && (bit != null) && (bit.toString().trim().length() > 0)) tags.add(bit.toString().toUpperCase().trim()); bit = null; break; case '"': case '\'': if (lastC == '\\') bit = null; else if ((quotes != '\0') && (quotes == buf.charAt(i))) quotes = '\0'; else if (quotes == '\0') quotes = buf.charAt(i); bit = null; break; default: if ((bit != null) && (Character.isLetterOrDigit(buf.charAt(i)))) bit.append(buf.charAt(i)); else bit = null; break; } lastC = buf.charAt(i); } if (MXP.tagDebug) { System.out.println("/TAG/CLOSERS=" + Util.toStringList(tags)); System.out.flush(); } return tags; }
// any number of users excluding itself private static String getGrantees(int num) { StringBuffer aStr = new StringBuffer(" "); Map<String, String> userPasswd = (Map<String, String>) SQLBB.getBB().getSharedMap().get(SQLSecurityTest.userPasswdMap); userPasswd.remove("thr_" + RemoteTestModule.getCurrentThread().getThreadId()); String[] users = new String[userPasswd.size()]; userPasswd.keySet().toArray(users); int i = 0; while (i < num) { int x = SQLTest.random.nextInt(users.length); aStr.append(users[x] + ", "); i++; } if (aStr.charAt(aStr.length() - 2) == ',') { aStr.deleteCharAt(aStr.length() - 2); } aStr.deleteCharAt(0); // delete the leading space return aStr.toString(); }
private static String FilterID(String id) { if (id == null) { return null; } else { StringBuffer newID = new StringBuffer(); int st = 0; for (int i = 0; i < id.length(); i++) { char ch = Character.toLowerCase(id.charAt(i)); if (Character.isLetterOrDigit(ch)) { newID.append(ch); st = 1; } else if (st == 1) { newID.append("_"); st = 0; } else { // ignore char } } while ((newID.length() > 0) && (newID.charAt(newID.length() - 1) == '_')) { newID.setLength(newID.length() - 1); } return newID.toString(); } }
private Object createObject( Node node, String name, String classPackage, String type, String value, boolean setProperty) { Bean parentBean = null; if (beansStack.size() > 0) parentBean = (Bean) beansStack.peek(); Object object = null; // param is either an XSD type or a bean, // check if it can be converted to an XSD type XSDatatype dt = null; try { dt = DatatypeFactory.getTypeByName(type); } catch (DatatypeException dte) { // the type is not a valid XSD data type } // convert null value to default if ((dt != null) && (value == null)) { Class objType = dt.getJavaObjectType(); if (objType == String.class) value = ""; else if ((objType == java.math.BigInteger.class) || (objType == Long.class) || (objType == Integer.class) || (objType == Short.class) || (objType == Byte.class)) value = "0"; else if ((objType == java.math.BigDecimal.class) || (objType == Double.class) || (objType == Float.class)) value = "0.0"; else if (objType == Boolean.class) value = "false"; else if (objType == java.util.Date.class) value = DateUtils.getCurrentDate(); else if (objType == java.util.Calendar.class) value = DateUtils.getCurrentDateTime(); } // check whether the type was converted to an XSD datatype if ((dt != null) && dt.isValid(value, null)) { // create and return an XSD Java object (e.g. String, Integer, Boolean, etc) object = dt.createJavaObject(value, null); if (object instanceof java.util.Calendar) { // check that the object is truly a Calendar // because DatatypeFactory converts xsd:date // types to GregorianCalendar instead of Date. if (type.equals("date")) { java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); try { object = df.parse(value); } catch (java.text.ParseException pe) { object = new java.util.Date(); } } } } else { // Create a bean object if (topLevelBean == null) topLevelBean = parentBean; object = pushBeanOnStack(classPackage, type); // Check fields to see if this property is the 'value' for the object Field[] fields = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].isAnnotationPresent(ObjectXmlAsValue.class)) { try { StringBuffer fieldName = new StringBuffer(fields[i].getName()); char c = fieldName.charAt(0); if (c >= 'a' && c <= 'z') { c += 'A' - 'a'; } fieldName.setCharAt(0, c); fieldName.insert(0, "set"); Method method = object .getClass() .getMethod(fieldName.toString(), new Class[] {fields[i].getType()}); method.invoke(object, value); break; } catch (Exception e) { System.err.println(e.getMessage()); } } } NamedNodeMap nodeAttrs = node.getAttributes(); // iterate attributes and set field values for property attributes for (int i = 0; i < nodeAttrs.getLength(); i++) { String nodePrefix = nodeAttrs.item(i).getPrefix(); if (nodePrefix.equals(nsPrefix)) { String nodeName = nodeAttrs.item(i).getLocalName(); String nodeValue = nodeAttrs.item(i).getNodeValue(); try { Field field = object.getClass().getDeclaredField(nodeName); if (field.isAnnotationPresent(ObjectXmlAsAttribute.class)) { StringBuffer fieldName = new StringBuffer(field.getName()); char c = fieldName.charAt(0); if (c >= 'a' && c <= 'z') { c += 'A' - 'a'; } fieldName.setCharAt(0, c); fieldName.insert(0, "set"); Method method = object.getClass().getMethod(fieldName.toString(), new Class[] {field.getType()}); if (field.getType() == String.class) method.invoke(object, nodeValue); else if (field.getType() == Boolean.TYPE) method.invoke(object, StringUtils.strToBool(nodeValue, "true")); else if (field.getType() == Byte.TYPE) method.invoke(object, Byte.valueOf(nodeValue).byteValue()); else if (field.getType() == Character.TYPE) method.invoke(object, Character.valueOf(nodeValue.charAt(0))); else if (field.getType() == Double.TYPE) method.invoke(object, Double.valueOf(nodeValue).doubleValue()); else if (field.getType() == Float.TYPE) method.invoke(object, Float.valueOf(nodeValue).floatValue()); else if (field.getType() == Integer.TYPE) method.invoke(object, Integer.valueOf(nodeValue).intValue()); else if (field.getType() == Long.TYPE) method.invoke(object, Long.valueOf(nodeValue).longValue()); else if (field.getType() == Short.TYPE) method.invoke(object, Short.valueOf(nodeValue).shortValue()); } } catch (Exception e) { System.err.println(e.getMessage()); } } } } if ((parentBean != null) && (setProperty)) { parentBean.setProperty(name, object); } return object; }
public StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons) throws IOException { offset = 0; braceNesting = 0; scopes.clear(); String symbol; JavaScriptToken token; // begin if (tokens.size() == 0) { StringBuffer result = new StringBuffer(); return result; } // end JavaScriptToken lastToken = getToken(0); ScriptOrFnScope currentScope; JavaScriptIdentifier identifier; int length = tokens.size(); // 文本的长度 StringBuffer result = new StringBuffer(); int linestartpos = 0; enterScope(globalScope); // 将globalScope压入栈scopes中 while (offset < length) { token = consumeToken(); symbol = token.getValue(); currentScope = getCurrentScope(); switch (token.getType()) { case Token.GET: case Token.SET: lastToken = token; // 注意没有break; case Token.NAME: if (offset >= 2 && getToken(-2).getType() == Token.DOT || getToken(0).getType() == Token.OBJECTLIT) { result.append(symbol); } else { identifier = getIdentifier(symbol, currentScope); if (identifier != null) { if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } if (currentScope != globalScope // 全局域中的变量可能被HTML文档使用,不需要发出警告 && identifier.getRefcount() == 0) { warn("标识符" + symbol + "已经声明但未使用 ", true); } } else { result.append(symbol); } } break; case Token.REGEXP: case Token.STRING: result.append(symbol); break; case Token.NUMBER: if (getToken(0).getType() == Token.DOT) { // calling methods on int requires a leading dot so JS // doesn't // treat the method as the decimal component of a float result.append('('); result.append(symbol); result.append(')'); } else { result.append(symbol); } break; case Token.ADD: case Token.SUB: result.append(literals.get(new Integer(token.getType()))); if (offset < length) { token = getToken(0); if (token.getType() == Token.INC || token.getType() == Token.DEC || token.getType() == Token.ADD || token.getType() == Token.DEC) { // Handle the case x +/- ++/-- y // We must keep a white space here. Otherwise, x +++ y // would be // interpreted as x ++ + y by the compiler, which is a // bug (due // to the implicit(隐式的) assignment being done on the // wrong variable) result.append(' '); } else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD || token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) { // Handle the case x + + y and x - - y result.append(' '); } } break; case Token.FUNCTION: if (lastToken.getType() != Token.GET && lastToken.getType() != Token.SET) { result.append("function"); } lastToken = token; token = consumeToken(); if (token.getType() == Token.NAME) { result.append(' '); symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } if (currentScope != globalScope && identifier.getRefcount() == 0) { warn("标识符" + symbol + "已经声明但未使用", true); } token = consumeToken(); } assert token.getType() == Token.LP; result.append('('); currentScope = indexedScopes.get(new Integer(offset)); // 根据左圆括号的下一个索引映射得到函数作用域 enterScope(currentScope); while ((token = consumeToken()).getType() != Token.RP) { assert token.getType() == Token.NAME || token.getType() == Token.COMMA; if (token.getType() == Token.NAME) { symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } } else if (token.getType() == Token.COMMA) { result.append(','); } } result.append(')'); token = consumeToken(); // 得到左花括号 assert token.getType() == Token.LC; result.append("{"); // nomodify braceNesting++; token = getToken(0); if (token.getType() == Token.STRING && getToken(1).getType() == Token.SEMI) { // This is a hint. Skip it! consumeToken(); consumeToken(); } break; case Token.RETURN: case Token.TYPEOF: result.append(literals.get(new Integer(token.getType()))); // No space needed after 'return' and 'typeof' when followed // by '(', '[', '{', a string or a regexp. if (offset < length) { token = getToken(0); if (token.getType() != Token.LP && token.getType() != Token.LB && token.getType() != Token.LC && token.getType() != Token.STRING && token.getType() != Token.REGEXP && token.getType() != Token.SEMI) { result.append(' '); } } break; case Token.CASE: case Token.THROW: result.append(literals.get(new Integer(token.getType()))); // White-space needed after 'case' and 'throw' when not followed // by a string. if (offset < length && getToken(0).getType() != Token.STRING) { result.append(' '); } break; case Token.BREAK: case Token.CONTINUE: result.append(literals.get(new Integer(token.getType()))); if (offset < length && getToken(0).getType() != Token.SEMI) { // If 'break' or 'continue' is not followed by a // semi-colon(分号), it must // be followed by a label, hence(因此) the need for a white // space. result.append(' '); } break; case Token.LC: result.append("{"); // nomodify braceNesting++; break; case Token.RC: result.append('}'); braceNesting--; assert braceNesting >= currentScope.getBraceNesting(); if (braceNesting == currentScope.getBraceNesting()) { leaveCurrentScope(); } break; case Token.SEMI: // No need to output a semi-colon if the next character is a // right-curly... if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) { result.append(';'); } if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) { // Some source control tools don't like it when files // containing lines longer // than, say 8000 characters, are checked in. The linebreak // option is used in // that case to split long lines after a specific column. result.append('\n'); linestartpos = result.length(); } break; case Token.COMMA: // No need to output a comma if the next character is a // right-curly or a right-square bracket if (offset < length && getToken(0).getType() != Token.RC && getToken(0).getType() != Token.RB) { result.append(','); } break; case Token.CONDCOMMENT: case Token.KEEPCOMMENT: if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') { result.append("\n"); } result.append("/*"); if (token.getType() == Token.KEEPCOMMENT) { result.append("!"); } result.append(symbol); result.append("*/\n"); break; // begin--这个分支用于实现压扁控制流 // 此分支将if(expression){...}else if(expression){...}else{...}转化为 // switch(expression){case true:原if块;break;case false:原else块;break;} case Token.IF: if (!EditOptionPanel.checkBoxFlatten.isSelected()) { result.append(symbol); break; } FlattenIF flattenIF = new FlattenIF(offset, length, tokens, currentScope); String switchBlock = flattenIF.flattenIF(); result.append(switchBlock); offset = flattenIF.offset; break; case Token.WHILE: if (!EditOptionPanel.checkBoxOpacity.isSelected()) { result.append(symbol); break; } result.append(symbol); OpacityPredicate opacityPredicateWhile = new OpacityPredicate(offset, tokens, currentScope); String whileBlock = opacityPredicateWhile.opacityPredicateWhile(); result.append(whileBlock); offset = opacityPredicateWhile.offset; break; case Token.DO: if (!EditOptionPanel.checkBoxOpacity.isSelected()) { result.append(symbol); break; } result.append(symbol); OpacityPredicate opacityPredicateDoWhile = new OpacityPredicate(offset, tokens, currentScope); String doWhileBlock = opacityPredicateDoWhile.opacityPredicateDoWhile(); result.append(doWhileBlock); offset = opacityPredicateDoWhile.offset; break; // end default: String literal = literals.get(new Integer(token.getType())); if (literal != null) { result.append(literal); } else { warn("此标志符不能被打印出来:" + symbol, true); } break; } } // Append a semi-colon at the end, even if unnecessary semi-colons are // supposed to be removed. This is especially useful when concatenating // several minified files (the absence of an ending semi-colon at the // end of one file may very likely cause a syntax error) /*if (!preserveAllSemiColons && result.length() > 0 && getToken(-1).getType() != Token.CONDCOMMENT && getToken(-1).getType() != Token.KEEPCOMMENT) { if (result.charAt(result.length() - 1) == '\n') { result.setCharAt(result.length() - 1, ';'); } else { result.append(';'); } }*/ // 暂时用不上,注释掉 return result; }
public boolean searchAndReplace( @NotNull Editor editor, @NotNull LineRange range, @NotNull String excmd, String exarg) { boolean res = true; // Explicitly exit visual mode here, so that visual mode marks don't change when we move the // cursor to a match. if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { VimPlugin.getMotion().exitVisual(editor); } CharPointer cmd = new CharPointer(new StringBuffer(exarg)); // sub_nsubs = 0; // sub_nlines = 0; int which_pat; if (excmd.equals("~")) { which_pat = RE_LAST; /* use last used regexp */ } else { which_pat = RE_SUBST; /* use last substitute regexp */ } CharPointer pat; CharPointer sub; char delimiter; /* new pattern and substitution */ if (excmd.charAt(0) == 's' && !cmd.isNul() && !Character.isWhitespace(cmd.charAt()) && "0123456789cegriIp|\"".indexOf(cmd.charAt()) == -1) { /* don't accept alphanumeric for separator */ if (CharacterClasses.isAlpha(cmd.charAt())) { VimPlugin.showMessage(MessageHelper.message(Msg.E146)); return false; } /* * undocumented vi feature: * "\/sub/" and "\?sub?" use last used search pattern (almost like * //sub/r). "\&sub&" use last substitute pattern (like //sub/). */ if (cmd.charAt() == '\\') { cmd.inc(); if ("/?&".indexOf(cmd.charAt()) == -1) { VimPlugin.showMessage(MessageHelper.message(Msg.e_backslash)); return false; } if (cmd.charAt() != '&') { which_pat = RE_SEARCH; /* use last '/' pattern */ } pat = new CharPointer(""); /* empty search pattern */ delimiter = cmd.charAt(); /* remember delimiter character */ cmd.inc(); } else /* find the end of the regexp */ { which_pat = RE_LAST; /* use last used regexp */ delimiter = cmd.charAt(); /* remember delimiter character */ cmd.inc(); pat = cmd.ref(0); /* remember start of search pat */ cmd = RegExp.skip_regexp(cmd, delimiter, true); if (cmd.charAt() == delimiter) /* end delimiter found */ { cmd.set('\u0000').inc(); /* replace it with a NUL */ } } /* * Small incompatibility: vi sees '\n' as end of the command, but in * Vim we want to use '\n' to find/substitute a NUL. */ sub = cmd.ref(0); /* remember the start of the substitution */ while (!cmd.isNul()) { if (cmd.charAt() == delimiter) /* end delimiter found */ { cmd.set('\u0000').inc(); /* replace it with a NUL */ break; } if (cmd.charAt(0) == '\\' && cmd.charAt(1) != 0) /* skip escaped characters */ { cmd.inc(); } cmd.inc(); } } else /* use previous pattern and substitution */ { if (lastReplace == null) /* there is no previous command */ { VimPlugin.showMessage(MessageHelper.message(Msg.e_nopresub)); return false; } pat = null; /* search_regcomp() will use previous pattern */ sub = new CharPointer(lastReplace); } /* * Find trailing options. When '&' is used, keep old options. */ if (cmd.charAt() == '&') { cmd.inc(); } else { do_all = Options.getInstance().isSet("gdefault"); do_ask = false; do_error = true; // do_print = false; do_ic = 0; } while (!cmd.isNul()) { /* * Note that 'g' and 'c' are always inverted, also when p_ed is off. * 'r' is never inverted. */ if (cmd.charAt() == 'g') { do_all = !do_all; } else if (cmd.charAt() == 'c') { do_ask = !do_ask; } else if (cmd.charAt() == 'e') { do_error = !do_error; } else if (cmd.charAt() == 'r') /* use last used regexp */ { which_pat = RE_LAST; } else if (cmd.charAt() == 'i') /* ignore case */ { do_ic = 'i'; } else if (cmd.charAt() == 'I') /* don't ignore case */ { do_ic = 'I'; } else if (cmd.charAt() != 'p') { break; } cmd.inc(); } int line1 = range.getStartLine(); int line2 = range.getEndLine(); /* * check for a trailing count */ cmd = CharHelper.skipwhite(cmd); if (CharacterClasses.isDigit(cmd.charAt())) { int i = CharHelper.getdigits(cmd); if (i <= 0 && do_error) { VimPlugin.showMessage(MessageHelper.message(Msg.e_zerocount)); return false; } line1 = line2; line2 = EditorHelper.normalizeLine(editor, line1 + i - 1); } /* * check for trailing command or garbage */ cmd = CharHelper.skipwhite(cmd); if (!cmd.isNul() && cmd.charAt() != '"') /* if not end-of-line or comment */ { VimPlugin.showMessage(MessageHelper.message(Msg.e_trailing)); return false; } String pattern = ""; if (pat == null || pat.isNul()) { switch (which_pat) { case RE_LAST: pattern = lastPattern; break; case RE_SEARCH: pattern = lastSearch; break; case RE_SUBST: pattern = lastSubstitute; break; } } else { pattern = pat.toString(); } lastSubstitute = pattern; if (pattern != null) { setLastPattern(editor, pattern); } // int start = editor.logicalPositionToOffset(new LogicalPosition(line1, 0)); // int end = editor.logicalPositionToOffset(new LogicalPosition(line2, // EditorHelper.getLineLength(editor, line2))); int start = editor.getDocument().getLineStartOffset(line1); int end = editor.getDocument().getLineEndOffset(line2); RegExp sp; RegExp.regmmatch_T regmatch = new RegExp.regmmatch_T(); sp = new RegExp(); regmatch.regprog = sp.vim_regcomp(pattern, 1); if (regmatch.regprog == null) { if (do_error) { VimPlugin.showMessage(MessageHelper.message(Msg.e_invcmd)); } return false; } /* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */ if (do_ic == 'i') { regmatch.rmm_ic = true; } else if (do_ic == 'I') { regmatch.rmm_ic = false; } /* * ~ in the substitute pattern is replaced with the old pattern. * We do it here once to avoid it to be replaced over and over again. * But don't do it when it starts with "\=", then it's an expression. */ if (!(sub.charAt(0) == '\\' && sub.charAt(1) == '=') && lastReplace != null) { StringBuffer tmp = new StringBuffer(sub.toString()); int pos = 0; while ((pos = tmp.indexOf("~", pos)) != -1) { if (pos == 0 || tmp.charAt(pos - 1) != '\\') { tmp.replace(pos, pos + 1, lastReplace); pos += lastReplace.length(); } pos++; } sub = new CharPointer(tmp); } lastReplace = sub.toString(); searchHighlight(false); if (logger.isDebugEnabled()) { logger.debug("search range=[" + start + "," + end + "]"); logger.debug("pattern=" + pattern + ", replace=" + sub); } int lastMatch = -1; int lastLine = -1; int searchcol = 0; boolean firstMatch = true; boolean got_quit = false; int lcount = EditorHelper.getLineCount(editor); for (int lnum = line1; lnum <= line2 && !got_quit; ) { CharacterPosition newpos = null; int nmatch = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, searchcol); if (nmatch > 0) { if (firstMatch) { VimPlugin.getMark().saveJumpLocation(editor); firstMatch = false; } String match = sp.vim_regsub_multi(regmatch, lnum, sub, 1, false); // logger.debug("found match[" + spos + "," + epos + "] - replace " + match); int line = lnum + regmatch.startpos[0].lnum; CharacterPosition startpos = new CharacterPosition(lnum + regmatch.startpos[0].lnum, regmatch.startpos[0].col); CharacterPosition endpos = new CharacterPosition(lnum + regmatch.endpos[0].lnum, regmatch.endpos[0].col); int startoff = EditorHelper.characterPositionToOffset(editor, startpos); int endoff = EditorHelper.characterPositionToOffset(editor, endpos); int newend = startoff + match.length(); if (do_all || line != lastLine) { boolean doReplace = true; if (do_ask) { // editor.getSelectionModel().setSelection(startoff, endoff); RangeHighlighter hl = highlightConfirm(editor, startoff, endoff); int choice = getConfirmChoice(match); // editor.getSelectionModel().removeSelection(); editor.getMarkupModel().removeHighlighter(hl); switch (choice) { case 0: // Yes doReplace = true; break; case 1: // No doReplace = false; break; case 2: // All do_ask = false; break; case JOptionPane.CLOSED_OPTION: case 3: // Quit doReplace = false; got_quit = true; break; case 4: // Last do_all = false; line2 = lnum; doReplace = true; break; } } if (doReplace) { editor.getDocument().replaceString(startoff, endoff, match); lastMatch = startoff; newpos = EditorHelper.offsetToCharacterPosition(editor, newend); lnum += newpos.line - endpos.line; line2 += newpos.line - endpos.line; } } lastLine = line; lnum += nmatch - 1; if (do_all && startoff != endoff) { if (newpos != null) { lnum = newpos.line; searchcol = newpos.column; } else { searchcol = endpos.column; } } else { searchcol = 0; lnum++; } } else { lnum++; searchcol = 0; } } if (lastMatch != -1) { MotionGroup.moveCaret( editor, VimPlugin.getMotion() .moveCaretToLineStartSkipLeading( editor, editor.offsetToLogicalPosition(lastMatch).line)); } else { VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern)); } return res; }
public synchronized Vector getParsedAttributes() { if (parsedAttributes != null) return parsedAttributes; parsedAttributes = new Vector(); attributeValues = new Hashtable(); alternativeAttributes = new Hashtable(); final StringBuffer buf = new StringBuffer(attributes.trim()); StringBuffer bit = new StringBuffer(""); char quotes = '\0'; int i = -1; char lastC = ' '; boolean firstEqual = false; while ((++i) < buf.length()) { switch (buf.charAt(i)) { case '=': if ((!firstEqual) && (bit.length() > 0)) { final String tag = bit.toString().toUpperCase().trim(); bit = new StringBuffer(""); parsedAttributes.addElement(tag); attributeValues.put(tag, bit); } else bit.append(buf.charAt(i)); firstEqual = true; break; case '\n': case '\r': case ' ': case '\t': if (quotes == '\0') { if ((!firstEqual) && (bit.length() > 0)) parsedAttributes.addElement(bit.toString().toUpperCase().trim()); bit = new StringBuffer(""); firstEqual = false; } else bit.append(buf.charAt(i)); break; case '"': case '\'': if (lastC == '\\') bit.append(buf.charAt(i)); else if ((lastC == '=') || (quotes != '\0') || ((quotes == '\0') && ((lastC == ' ') || (lastC == '\t')))) { if ((quotes != '\0') && (quotes == buf.charAt(i))) { quotes = '\0'; if ((!firstEqual) && (bit.length() > 0)) parsedAttributes.addElement(bit.toString().toUpperCase().trim()); bit = new StringBuffer(""); firstEqual = false; } else { if (quotes != '\0') bit.append(buf.charAt(i)); else quotes = buf.charAt(i); } } else bit.append(buf.charAt(i)); break; default: bit.append(buf.charAt(i)); break; } lastC = buf.charAt(i); } if ((!firstEqual) && (bit.length() > 0)) parsedAttributes.addElement(bit.toString().toUpperCase().trim()); for (int p = parsedAttributes.size() - 1; p >= 0; p--) { final String PA = (String) parsedAttributes.elementAt(p); final StringBuffer VAL = (StringBuffer) attributeValues.get(PA); if ((VAL != null) && (parsedAttributes.contains(VAL.toString()))) { parsedAttributes.removeElementAt(p); attributeValues.remove(PA); alternativeAttributes.put(PA, VAL.toString()); } } return parsedAttributes; }