code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package quickdb.db.connection; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author gato */ public interface IConnectionDB { public void connectMySQL(); public void connectPostgres(); public void connectSQLServer(); public void connectSQLite(); public void connectFirebird(); public void closeConnection(); public void openBlock(String tableName); public void insertField(String columnName, Object columnValue) throws SQLException; public int insertRow(String query) throws SQLException; public int closeBlock() throws java.lang.Exception; public boolean existTable(String tableName); public ResultSet updateField(String table, String where); public ResultSet select(String select); public ResultSet selectWhere(String table, String where); public Connection getConnection(); public ResultSet getRs(); public void initTransaction() throws SQLException; public void cancelTransaction() throws SQLException; public void confirmTransaction() throws SQLException; public void executeQuery(String sql) throws SQLException; public void disconnect(); public void deleteRows(String tableName, String where) throws Exception; public String getSchema(); }
zzqchy-qaw1
java/src/main/java/quickdb/db/connection/IConnectionDB.java
Java
lgpl
1,315
package quickdb.db.connection; import java.sql.*; /** * * @author Diego Sarmentero */ public class ConnectionDB implements IConnectionDB{ protected Connection connection = null; protected Statement statement = null; protected ResultSet rs = null; private boolean tryAgain = true; //Connection Data private String host; private String port; private String nameDB; private String username; private String password; private String url; private String driver; protected String schema; public ConnectionDB(String... dbParameters) { this.host = dbParameters[0]; this.port = dbParameters[1]; this.nameDB = dbParameters[2]; this.username = dbParameters[3]; this.password = dbParameters[4]; } private void connect() { try { Class.forName(this.driver); connection = DriverManager.getConnection(url, username, password); this.connection.setAutoCommit(false); } catch (ClassNotFoundException e) { System.err.println("Driver couldn't be loaded. " + e.getMessage()); } catch (SQLException e) { System.err.println("Error trying to connect. " + e.getMessage()); } } @Override public void connectMySQL() { this.driver = "com.mysql.jdbc.Driver"; this.url = "jdbc:mysql://" + host + ":" + port + "/" + nameDB; this.connect(); } @Override public void connectPostgres() { this.driver = "org.postgresql.Driver"; this.url = "jdbc:postgresql://" + host + ":" + port + "/" + nameDB; this.connect(); } @Override public void connectSQLServer() { this.driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; this.url = "jdbc:sqlserver://" + host + ":" + port + ";" + "databaseName=" + nameDB; this.connect(); } @Override public void connectSQLite() { this.driver = "org.sqlite.JDBC"; this.url = "jdbc:sqlite:" + nameDB + ".db"; this.connect(); } @Override public void connectFirebird() { this.driver = "org.firebirdsql.jdbc.FBDriver"; this.url = "jdbc:firebirdsql:" + host + "/" + port + ":" + nameDB; this.connect(); } @Override public void closeConnection() { try { connection.close(); } catch (Exception e) { System.err.println( "'cerrarConexion()' Error trying to close connection. " + e.getMessage()); } } @Override public void openBlock(String tableName) { try { statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = statement.executeQuery("SELECT * FROM " + tableName + ";"); rs.moveToInsertRow(); tryAgain = true; } catch (SQLException e) { if (tryAgain) { this.connect(); tryAgain = false; this.openBlock(tableName); } } } @Override public void insertField(String columnName, Object columnValue) throws SQLException { try { rs.updateObject(columnName, columnValue); } catch (SQLException e) { throw e; } catch (NullPointerException nullEx) { SQLException sqlEx = new SQLException(); throw sqlEx; } } @Override public int insertRow(String query) throws SQLException { int index = 0; try { statement = connection.createStatement(); statement.execute(query + ";"); rs = statement.getGeneratedKeys(); rs.next(); index = rs.getInt(1); statement.close(); } catch (SQLException e) { throw e; } catch (NullPointerException nullEx) { SQLException sqlEx = new SQLException(); throw sqlEx; } return index; } @Override public int closeBlock() throws java.lang.Exception { int index = 0; try { if (rs != null) { rs.insertRow(); rs.close(); rs = statement.executeQuery("SELECT LAST_INSERT_ID();"); rs.next(); index = rs.getInt(1); } } catch (SQLException e) { throw e; } finally { rs.close(); statement.close(); } return index; } @Override public boolean existTable(String tableName) { try { statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = statement.executeQuery("SELECT * FROM " + tableName + " LIMIT 1;"); return rs.next(); } catch (SQLException e) { //System.err.println(e.getMessage()); } return false; } @Override public ResultSet updateField(String table, String where) { try { statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = statement.executeQuery("SELECT * FROM " + table + " WHERE " + where + ";"); tryAgain = true; } catch (SQLException e) { if (tryAgain) { this.connect(); tryAgain = false; return this.updateField(table, where); } else { System.err.println("Error trying to update field. " + e.getMessage()); } } return rs; } @Override public ResultSet select(String select) { try { statement = connection.createStatement(); rs = statement.executeQuery(select + ";"); tryAgain = true; return rs; } catch (SQLException e) { if (tryAgain) { this.connect(); tryAgain = false; return this.select(select); } else { System.err.println("'Select()'. " + e.getMessage()); } } return null; } @Override public ResultSet selectWhere(String table, String where) { try { statement = connection.createStatement(); rs = statement.executeQuery("SELECT * FROM " + table + " WHERE " + where + ";"); tryAgain = true; return rs; } catch (SQLException e) { if (tryAgain) { this.connect(); tryAgain = false; return this.selectWhere(table, where); } else { System.err.println("'SelectWhere()'. " + e.getMessage()); } } return null; } @Override public Connection getConnection() { return this.connection; } @Override public ResultSet getRs() { return this.rs; } @Override public void initTransaction() throws SQLException { connection.setAutoCommit(false); } @Override public void cancelTransaction() throws SQLException { connection.rollback(); } @Override public void confirmTransaction() throws SQLException { connection.commit(); } @Override public void executeQuery(String sql) throws SQLException { try { statement = connection.createStatement(); statement.executeUpdate(sql + ";"); statement.close(); tryAgain = true; } catch (Exception e) { if (tryAgain) { this.connect(); tryAgain = false; this.executeQuery(sql); } else { throw new SQLException(); } } } @Override public void disconnect() { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void deleteRows(String tableName, String where) throws Exception { // Creamos una statement SQL statement = connection.createStatement(); // Ejecutamos la consulta statement.executeUpdate("DELETE FROM " + tableName + " WHERE " + where + ";"); statement.close(); } @Override public String getSchema(){ return this.schema; } }
zzqchy-qaw1
java/src/main/java/quickdb/db/connection/ConnectionDB.java
Java
lgpl
8,611
package quickdb.db; import java.util.Collection; /** * * @author Diego Sarmentero */ public class AdminThread implements Runnable{ private AdminBase admin; private Object object; private String sqlQuery; private OPERATIONS oper; private enum OPERATIONS{ SAVE, MODIFY, DELETE, EXECUTE, LAZYLOAD, OBTAINWHERE, OBTAIN, OBTAINSTRING, OBTAINSELECT, SAVEALL, MODIFYALL } public AdminThread(AdminBase.DATABASE db, String... args){ admin = AdminBase.initialize(db, args); } public AdminThread(AdminBase admin){ this.admin = admin; } void setProperties(Object obj, String sql, OPERATIONS o){ this.object = obj; this.sqlQuery = sql; this.oper = o; } @Override public void run(){ switch(this.oper){ case SAVE: this.admin.save(object);break; case MODIFY: this.admin.modify(object);break; case DELETE: this.admin.delete(object);break; case EXECUTE: this.admin.executeQuery(sqlQuery);break; case LAZYLOAD: this.admin.lazyLoad(object, sqlQuery);break; case OBTAINWHERE: this.admin.obtainWhere(object, sqlQuery);break; case OBTAIN: this.admin.obtain(object);break; case OBTAINSTRING: this.admin.obtain(object, sqlQuery);break; case OBTAINSELECT: this.admin.obtainSelect(object, sqlQuery);break; case SAVEALL: this.admin.saveAll(((Collection)object));break; case MODIFYALL: this.admin.modifyAll(((Collection)object));break; } } public void save(Object obj){ AdminThread at = new AdminThread(this.admin); at.setProperties(obj, "", OPERATIONS.SAVE); Thread t = new Thread(at); t.start(); } public void modify(Object obj){ AdminThread at = new AdminThread(this.admin); at.setProperties(obj, "", OPERATIONS.MODIFY); Thread t = new Thread(at); t.start(); } public void delete(Object obj){ AdminThread at = new AdminThread(this.admin); at.setProperties(obj, "", OPERATIONS.DELETE); Thread t = new Thread(at); t.start(); } public void execute(String query){ AdminThread at = new AdminThread(this.admin); at.setProperties(null, query, OPERATIONS.EXECUTE); Thread t = new Thread(at); t.start(); } public void lazyLoad(Object... obj){ AdminThread at = new AdminThread(this.admin); String sql; if(obj.length == 2){ sql = String.valueOf(obj[1]); }else{ sql = ""; } at.setProperties(obj[0], sql, OPERATIONS.LAZYLOAD); Thread t = new Thread(at); t.start(); } public void obtainWhere(Object obj, String sql){ AdminThread at = new AdminThread(this.admin); at.setProperties(obj, sql, OPERATIONS.OBTAINWHERE); Thread t = new Thread(at); t.start(); } public void obtainSelect(Object obj, String sql){ AdminThread at = new AdminThread(this.admin); at.setProperties(obj, sql, OPERATIONS.OBTAINSELECT); Thread t = new Thread(at); t.start(); } public void obtain(Object obj){ AdminThread at = new AdminThread(this.admin); at.setProperties(obj, "", OPERATIONS.OBTAIN); Thread t = new Thread(at); t.start(); } public void obtain(Object obj, String sql){ AdminThread at = new AdminThread(this.admin); at.setProperties(obj, sql, OPERATIONS.OBTAINSTRING); Thread t = new Thread(at); t.start(); } public void saveAll(Collection array){ AdminThread at = new AdminThread(this.admin); at.setProperties(array, "", OPERATIONS.SAVEALL); Thread t = new Thread(at); t.start(); } public void modifyAll(Collection array){ AdminThread at = new AdminThread(this.admin); at.setProperties(array, "", OPERATIONS.MODIFYALL); Thread t = new Thread(at); t.start(); } public void setAutoCommit(boolean value){ this.admin.setAutoCommit(value); } }
zzqchy-qaw1
java/src/main/java/quickdb/db/AdminThread.java
Java
lgpl
4,358
package quickdb.db; import java.security.InvalidParameterException; import quickdb.db.dbms.DbmsInterpreter; import quickdb.db.dbms.mysql.ColumnDefined; import quickdb.db.dbms.mysql.DataType; import quickdb.modelSupport.M2mTable; import quickdb.modelSupport.PrimitiveCollec; import quickdb.query.Query; import quickdb.query.StringQuery; import java.sql.ResultSet; import java.util.Collection; import java.util.ArrayList; import java.sql.SQLException; import java.util.Hashtable; import java.util.Stack; import quickdb.db.connection.IConnectionDB; import quickdb.exception.OptimisticLockException; import quickdb.reflection.EntityManager; /** * * @author Diego Sarmentero */ public class AdminBase { protected IConnectionDB conex; protected ResultSet rs; protected EntityManager manager; protected String tableForcedName; protected boolean forceTable; private Stack<ResultSet> arrayRs; private DATABASE db; private boolean collectionHasName; private boolean collection; private boolean startObtainAll; private boolean commit; private boolean autoCommit; public enum DATABASE { MYSQL, POSTGRES, SQLSERVER, SQLite, FIREBIRD, MariaDB }; protected AdminBase(DATABASE db, String... args) { this.db = db; this.commit = true; this.autoCommit = false; this.startObtainAll = false; this.collection = false; this.collectionHasName = false; this.forceTable = false; this.tableForcedName = ""; this.manager = new EntityManager(); this.arrayRs = new Stack<ResultSet>(); this.conex = DbmsInterpreter.connect(db, args); } /** * For MySQL args: MYSQL, host, port, catalog, username, password * @param Database enumeration * @param Array of String depending on the database selected */ public static AdminBase initialize(DATABASE db, String... args) { AdminBase admin; switch(db){ case SQLite: admin = new AdminSQLite(db, args);break; default: admin = new AdminBase(db, args);break; } return admin; } /** * Initialize the AdminBase private attribute from AdminBinding * when QuickDB is used in the Data Model through inheritance * @param db * @param args */ public static void initializeAdminBinding(DATABASE db, String... args) { AdminBase admin = new AdminBase(db, args); AdminBinding.initializeAdminBase(admin); } public void initializeAdminBinding(){ AdminBinding.initializeAdminBase(this); } public static void initializeViews(DATABASE db, String... args) { AdminBase admin = new AdminBase(db, args); View.initializeAllViews(admin); } public void initializeViews(){ View.initializeAllViews(this); } /** * Store the object in the Database (create the Table if not exist) * @param Object * @return True if the object could be saved, False in the other case */ public boolean save(Object object) { int value = -1; try{ boolean commitValue = this.commit; if(this.commit || this.autoCommit){ conex.initTransaction(); this.commit = false; } ArrayList array = this.manager.entity2Array(this, object, EntityManager.OPERATION.SAVE); value = this.saveProcess(array, object); this.commit = commitValue; if(this.commit || this.autoCommit){ conex.confirmTransaction(); if(this.conex.getConnection().getAutoCommit()){ this.conex.getConnection().setAutoCommit(false); } } }catch(SQLException e){ this.commit = true; } return (value > 0); } protected int saveProcess(ArrayList array, Object object) { int index = -1; String table = ""; int i = 2; try { if (this.forceTable) { table = tableForcedName; array.set(0, table); } else { table = String.valueOf(array.get(0)); } conex.openBlock(table); int size = array.size() - 1; for (; i < size; i++) { Object[] obj = (Object[]) array.get(i); String column = (String) obj[0]; Object value = obj[1]; conex.insertField(column, value); } index = conex.closeBlock(); if (this.collection) { this.saveMany2Many(((String) array.get(0)), true, index); } this.manager.updateCache(object.getClass(), this); } catch (SQLException ex) { int value = -1; try{ this.conex.getConnection().setAutoCommit(true); if (!this.checkTableExist(table)) { if (this.createTable(object, array.toArray())) { value = this.saveProcess(array, object); } } else { if (this.addColumn(table, object, array, i)) { value = this.saveProcess(array, object); } } }catch(Exception e){} return value; } catch (Exception e) { conex.connectMySQL(); try { conex.cancelTransaction(); } catch (Exception ex) { return -1; } } return index; } /** * Store the object in the Database (create the Table if not exist) and * return the value of the PrimaryKey. * @param Object * @return The value of the PrimaryKey, or -1 if the object couldn't be * saved. */ public int saveGetIndex(Object object) { int index = -1; try { boolean commitValue = this.commit; if(this.commit || this.autoCommit){ conex.initTransaction(); this.commit = false; } ArrayList array = this.manager.entity2Array(this, object, EntityManager.OPERATION.SAVE); index = this.saveProcess(array, object); this.commit = commitValue; if(this.commit || this.autoCommit){ conex.confirmTransaction(); if(this.conex.getConnection().getAutoCommit()){ this.conex.getConnection().setAutoCommit(false); } } } catch (SQLException e) { this.commit = true; } return index; } protected boolean saveMany2Many(String table, boolean saveNotModify, int index) { ArrayList many = new ArrayList(); try { String where = ""; int sizeCollection = this.manager.sizeCollectionStack(); for (int i = 0; i < sizeCollection; i++) { ArrayList collec = this.manager.getCollection(); int size = collec.size(); if(size > 0 && collec.get(0) instanceof PrimitiveCollec){ for (int q = 0; q < size; q++) { ((PrimitiveCollec) collec.get(q)).setBase(index); many.add(collec.get(q)); } }else{ for (int q = 0; q < size; q++) { many.add(new M2mTable(index, ((Integer) collec.get(q)))); } } this.collection = false; this.forceTable = true; if (this.collectionHasName) { this.tableForcedName = this.manager.getNameCollection(); } else { String nameCollection = this.manager.getNameCollection(); //Consult if the table name or its inverse exists and asign match this.tableForcedName = table + nameCollection; where = "base = " + index; String tempTableName = nameCollection + table; if (!this.checkTableExist(this.tableForcedName) && this.checkTableExist(tempTableName)) { this.tableForcedName = tempTableName; where = "related = " + index; for (M2mTable m2m : ((ArrayList<M2mTable>) many)) { int temp = m2m.getBase(); m2m.setBase(m2m.getRelated()); m2m.setRelated(temp); } } } if (!saveNotModify) { String sql = "DELETE FROM " + this.tableForcedName + " WHERE " + where; this.executeQuery(sql); } this.saveAll(many); many.clear(); } } catch (Exception e) { return false; } finally { this.collection = false; this.forceTable = false; this.collectionHasName = false; } return true; } /** * For this method only is the object to be modify. * It is necessary to execute obtain previously to recover * the proper object. * @param Object * @return True if the modification was successfull, False in the other case */ public boolean modify(Object object) { if(!this.manager.checkOptimisticLock(this, object)){ throw new OptimisticLockException(); } boolean value = false; try{ boolean commitValue = this.commit; if(this.commit || this.autoCommit){ conex.initTransaction(); this.commit = false; } ArrayList<String> manys = this.manager.getRef().isMany2Many(object.getClass()); if (!manys.isEmpty()) { if (this.manager.deleteMany2Many(this, object, manys)) { this.manager.cleanStack(); value = this.save(object); } } else { value = this.modifyProcess(object); } this.commit = commitValue; if(this.commit || this.autoCommit) conex.confirmTransaction(); }catch(SQLException e){ this.commit = true; } return value; } protected boolean modifyProcess(Object object) { ArrayList array = this.manager.entity2Array(this, object, EntityManager.OPERATION.MODIFY); try { this.rs = conex.updateField(((String) array.get(0)), String.valueOf(array.get(array.size() - 1))); rs.next(); do { int size = array.size() - 1; for (int i = 1; i < size; i++) { Object[] obj = (Object[]) array.get(i); String column = (String) obj[0]; Object value = obj[1]; rs.updateObject(column, value); rs.updateRow(); } } while (rs.next()); int index = Integer.parseInt(String.valueOf(array.get(array.size() - 1)). substring(String.valueOf(array.get(array.size() - 1)).indexOf("=")+1)); if (this.collection) { this.saveMany2Many(((String) array.get(0)), false, index); } this.manager.updateCache(object.getClass(), this); } catch (Exception e) { try { conex.cancelTransaction(); } catch (Exception ex) { return false; } return false; } return true; } private int modifyGetIndex(Object object) { int index = this.manager.getRef().checkIndexValue(object); /*If the index is greater than 0 it means that the Object already exist in the Database and has to be modify, if index is lower than 0 it means that this is a new Object that has to be added to the database*/ if (index > 0) { this.modify(object); } else { index = this.saveGetIndex(object); } return index; } /** * Delete the object received as parameter from the Database * @param Object * @return True if the operation complete successfully, False in the other case. */ public boolean delete(Object object) { try { boolean commitValue = this.commit; if(this.commit || this.autoCommit){ conex.initTransaction(); this.commit = false; } ArrayList array = this.manager.entity2Array(this, object, EntityManager.OPERATION.DELETE); conex.deleteRows(((String) array.get(0)), ((String) array.get(array.size() - 1))); this.manager.deleteParent(this, object); //Obtain the attributes from this object that are collections //and delete their relations in the Relational Table. ArrayList<String[]> strings = this.manager.getCollectionsTableForDelete(object, this); int index = (Integer) ((Object[]) array.get(1))[1]; for (String[] s : strings) { if (this.checkTableExist(s[0])) { this.executeQuery("DELETE FROM " + s[0] + " WHERE base=" + index); } else if (this.checkTableExist(s[1])) { this.executeQuery("DELETE FROM " + s[1] + " WHERE related=" + index); } } this.commit = commitValue; if(this.commit || this.autoCommit) conex.confirmTransaction(); } catch (Exception e) { this.commit = true; try { conex.cancelTransaction(); } catch (Exception ex) { return false; } return false; } return true; } /** * Execute the SQL query received as parameter * @param object * @return */ public boolean executeQuery(String statement) { try { conex.executeQuery(statement); return true; } catch (Exception e) { return false; } } private boolean obtainNext(Object object) { try { if (rs.next() && (this.manager.result2Object(this, object, rs) != null)) { return true; } } catch (Exception e) { return false; } finally { this.rs = this.arrayRs.peek(); } return false; } /** * Receive an Object and a query and return a Collection of object * from the same type as was received, that represent the result of * that query. * @param Object * @param Query [String] * @return ArrayList [Collection of Object] */ public ArrayList obtainAll(Class clazz, String sql) { boolean cacheable = this.manager.isCacheable(clazz); if(cacheable){ ArrayList array = this.manager.obtainCache(sql, this, clazz); if(array != null){ return array; } } this.startObtainAll = true; ArrayList results = new ArrayList(); try { boolean value = false; Object object = this.manager.getRef().emptyInstance(clazz); if(sql.startsWith("SELECT ")){ value = this.obtainSelect(object, sql); }else{ value = this.obtainWhere(object, sql); } if (value) { this.rs = this.arrayRs.peek(); results.add(object); Object obj = this.manager.getRef().emptyInstance(object); while (this.obtainNext(obj)) { results.add(obj); obj = this.manager.getRef().emptyInstance(object); } } if(cacheable){ this.manager.makeCacheable(sql, results, clazz, this); } } catch (Exception e) { return null; } finally { this.startObtainAll = false; this.arrayRs.pop(); if (!this.arrayRs.isEmpty()) { this.rs = this.arrayRs.peek(); } } return results; } /** * Load the attributes in the object gradually. * If this method received 2 parameters[Object, StringQuery] is * the first time that the object is going to be loaded, the next * time is only needed to receive the Object. * @param Object, [String only for the first time] * @return Object */ public boolean lazyLoad(Object... object) { this.manager.setDropDown(false); boolean value = false; if (object.length == 2) { String sql = String.valueOf(object[1]); value = this.obtain(object[0], sql); } else { value = this.manager.completeLazyLoad(this, object[0]); } this.manager.setDropDown(true); return value; } /** * This method can receive an object to determine the type of * object that is going to be manage and a String with the query. * (Faster than 'obtain', this method doesnt has to parse the expression) * @param Object, String * @return True if the object could be obtained, False in the other case. */ public boolean obtainWhere(Object object, String sql) { ArrayList array = this.manager.entity2Array(this, object, EntityManager.OPERATION.OBTAIN); try { if (this.collectionHasName) { this.rs = conex.selectWhere(this.manager.getNameCollection(), sql); } else { this.rs = conex.selectWhere(((String) array.get(0)), sql); } this.arrayRs.push(this.rs); if (rs.next() && (this.manager.result2Object(this, object, rs) != null)) { return true; } } catch (Exception e) { return false; } finally { if (!this.startObtainAll) { this.arrayRs.pop(); if (!this.arrayRs.isEmpty()) { this.rs = this.arrayRs.peek(); } } else { this.startObtainAll = false; } } return false; } /** * This Method return an Object[] containing String[] in each item, * that represent the result of the specified query as a Matrix of Strings * @param SQL Query [String] * @param Number of Columns involved [int] * @return Object[] or null */ public Object[] obtainTable(Object... prop) { try { this.rs = conex.select((String)prop[0]); rs.next(); int cols = 0; String[] names = new String[0]; boolean hash = false; if(prop.length > 1 && prop[1].getClass().getSimpleName().equalsIgnoreCase("Integer")){ cols = (Integer) prop[1]; }else if(prop.length > 1 && prop[1].getClass().getSimpleName().equalsIgnoreCase("Boolean")){ if((Boolean)prop[1]){ String sql = ((String) prop[0]).toLowerCase(); names = sql.substring( sql.indexOf("select ")+7, sql.indexOf(" from")).split(","); cols = names.length; hash = true; }else{ String sql = ((String) prop[0]).toLowerCase(); cols = sql.substring( sql.indexOf("select ")+7, sql.indexOf(" from")).split(",").length; } }else{ throw new InvalidParameterException(); } if(hash){ ArrayList<Hashtable<String, Object>> array = new ArrayList<Hashtable<String, Object>>(); do { Hashtable<String, Object> table = new Hashtable<String, Object>(cols); for (int i = 1; i < cols + 1; i++) { table.put(names[i-1].trim(), rs.getObject(i)); } array.add(table); } while (rs.next()); return array.toArray(); }else{ ArrayList<String[]> array = new ArrayList<String[]>(); do { String[] objs = new String[cols]; for (int i = 1; i < cols + 1; i++) { objs[i - 1] = rs.getObject(i).toString(); } array.add(objs); } while (rs.next()); return array.toArray(); } } catch (Exception e) { return null; } } @Deprecated public Object[] obtainJoin(String sql, int cols){ return this.obtainTable(sql, cols); } public Query obtain(Object obj){ return Query.create(this, obj); } /** * Return the object restore with the information from the * database, based on the Object Oriented Query that was received. * @param Object * @param Query statement * @return True if the Object could be restored, False in the other case. */ public boolean obtain(Object obj, String sql) { String query = StringQuery.parse(obj.getClass(), sql); return this.obtainSelect(obj, query); } /** * Return the Object from the Database that represent * the [completely] specified query * @param Object * @param SQL Query [String] * @return True if the object could be restored, False in the other case. */ public boolean obtainSelect(Object object, String sql) { try { this.rs = conex.select(sql); this.arrayRs.push(this.rs); if (rs.next() && (this.manager.result2Object(this, object, rs) != null)) { return true; } } catch (Exception e) { return false; } finally { if (!this.startObtainAll) { this.arrayRs.pop(); if (!this.arrayRs.isEmpty()) { this.rs = this.arrayRs.peek(); } } else { this.startObtainAll = false; } } return false; } /** * Save all the items in the Collection in the Database * @param An Object that implement java.util.Collection * @return An ArrayList with the number of elements inserted or * an ArrayList with each item index if the array received * represent a Collection Reference. */ public ArrayList<Integer> saveAll(Collection array) { ArrayList<Integer> results = new ArrayList<Integer>(); try{ boolean commitValue = this.commit; if(this.commit || this.autoCommit){ conex.initTransaction(); this.commit = false; } Object objects[] = array.toArray(); if (!this.collection) { for (int i = 0; i < objects.length; i++) { if (!this.save(objects[i])) { results.add(i); //throw exception break; } } } else { this.collection = false; for (Object obj : objects) { results.add(this.saveGetIndex(obj)); } this.collection = true; } this.commit = commitValue; if(this.commit || this.autoCommit){ conex.confirmTransaction(); if(this.conex.getConnection().getAutoCommit()){ this.conex.getConnection().setAutoCommit(false); } } }catch(SQLException e){ this.commit = true; } return results; } /** * Modify in the Database the objects in the array received as * parameter. * @param An Object that implements java.util.Collection with the items * @return An ArrayList with the index of each item if collection if from * a Reference Collection or an ArrayList with the number of item that * couldnt be updated if this is not a Collection Reference */ public ArrayList<Integer> modifyAll(Collection array) { ArrayList<Integer> results = new ArrayList<Integer>(); try{ boolean commitValue = this.commit; if(this.commit || this.autoCommit){ conex.initTransaction(); this.commit = false; } Object objects[] = array.toArray(); if (!this.collection) { for (int i = 0; i < objects.length; i++) { if (!this.modify(objects[i])) { results.add(i); break; } } } else { this.collection = false; for (Object obj : objects) { int index = this.modifyGetIndex(obj); results.add(index); } this.collection = true; } this.commit = commitValue; if(this.commit || this.autoCommit) conex.confirmTransaction(); }catch(SQLException e){ this.commit = true; } return results; } protected boolean createTable(Object entity, Object[] objects) { return DbmsInterpreter.createTable(db, this, entity, objects, manager); } protected boolean addColumn(String table, Object object, ArrayList array, int pos) throws Exception{ String statement = ""; if ((object.getClass().getDeclaredFields()[pos-1].getDeclaredAnnotations().length != 0)) { Object columns[] = this.manager.mappingDefinition(this, object); statement = String.format("ALTER TABLE %s ADD %s", table, ((ColumnDefined) columns[pos]).toString()); } else { DataType dataType = new DataType(); statement = String.format("ALTER TABLE %s ADD %s %s", table, String.valueOf(((Object[]) array.get(pos))[0]), dataType.getDataType(((Object[]) array.get(pos))[1].getClass(), ((Object[]) array.get(pos))[1].toString().length())); } return this.executeQuery(statement); } public void openAtomicBlock(){ this.commit = false; try{ this.conex.initTransaction(); }catch(Exception e){ this.commit = true; } } public void closeAtomicBlock(){ this.commit = true; try{ this.conex.confirmTransaction(); }catch(Exception e){ } } public void cancelAtomicBlock(){ this.commit = true; try{ this.conex.cancelTransaction(); }catch(Exception e){ } } public void setAutoCommit(boolean value){ this.autoCommit = value; } /** * Return True if the specified Table exist in the Database * @param Table Name * @return Boolean */ public boolean checkTableExist(String table) { return this.conex.existTable(table); } public void setCollection(boolean collection) { this.collection = collection; } public boolean getCollection() { return this.collection; } public void setCollectionHasName(boolean collectionHasName) { this.collectionHasName = collectionHasName; } public IConnectionDB getConex() { return this.conex; } public DATABASE getDB(){ return this.db; } public void close(){ this.conex.closeConnection(); } public void setForceTable(boolean forceTable) { this.forceTable = forceTable; } public void setTableForcedName(String tableForcedName) { this.tableForcedName = tableForcedName; } public void activateLogging(Object... values){ this.close(); if((Boolean) values[0]){ if(values.length < 2) throw new InvalidParameterException(); this.conex = DbmsInterpreter.connectLogging(db, ((String) values[1]), DbmsInterpreter.properties); }else{ this.conex = DbmsInterpreter.connect(db, DbmsInterpreter.properties); } } }
zzqchy-qaw1
java/src/main/java/quickdb/db/AdminBase.java
Java
lgpl
28,950
package quickdb.db.dbms; import quickdb.db.AdminBase; import quickdb.db.connection.ConnectionDB; import quickdb.db.connection.ConnectionDBFirebird; import quickdb.db.connection.ConnectionDBPostgre; import quickdb.db.connection.IConnectionDB; import quickdb.db.connection.ProxyConnectionDB; import quickdb.db.dbms.firebird.Firebird; import quickdb.db.dbms.mysql.MySQL; import quickdb.db.dbms.postgre.PostgreSQL; import quickdb.db.dbms.sqlite.SQLite; import quickdb.reflection.EntityManager; /** * * @author Diego Sarmentero */ public class DbmsInterpreter { public static String[] properties; public static ConnectionDB connect(AdminBase.DATABASE db, String... args){ DbmsInterpreter.properties = args; ConnectionDB conex = null; switch (db) { case MariaDB: case MYSQL: conex = new ConnectionDB(args); conex.connectMySQL(); break; case SQLSERVER: conex = new ConnectionDB(args); conex.connectSQLServer(); break; case POSTGRES: conex = new ConnectionDBPostgre(args); conex.connectPostgres(); break; case SQLite: conex = new ConnectionDB("", "", args[0], "", ""); conex.connectSQLite(); break; case FIREBIRD: conex = new ConnectionDBFirebird(args); conex.connectFirebird(); break; } return conex; } public static IConnectionDB connectLogging(AdminBase.DATABASE db, String path, String... args){ DbmsInterpreter.properties = args; IConnectionDB conex = null; ProxyConnectionDB.configureLogger(path); switch (db) { case MYSQL: conex = (IConnectionDB) ProxyConnectionDB.newInstance(new ConnectionDB(args)); conex.connectMySQL(); break; case SQLSERVER: conex = (IConnectionDB) ProxyConnectionDB.newInstance(new ConnectionDB(args)); conex.connectSQLServer(); break; case POSTGRES: conex = (IConnectionDB) ProxyConnectionDB.newInstance(new ConnectionDBPostgre(args)); conex.connectPostgres(); break; case SQLite: conex = (IConnectionDB) ProxyConnectionDB.newInstance(new ConnectionDB("", "", args[0], "", "")); conex.connectSQLite(); break; case FIREBIRD: conex = (IConnectionDB) ProxyConnectionDB.newInstance(new ConnectionDBFirebird(args)); conex.connectFirebird(); break; } return conex; } public static boolean createTable(AdminBase.DATABASE db, AdminBase admin, Object entity, Object[] objects, EntityManager manager){ boolean value = false; switch(db){ case SQLite: value = SQLite.createTable(admin, entity, objects, manager); break; case MYSQL: value = MySQL.createTable(admin, entity, objects, manager); break; case POSTGRES: value = PostgreSQL.createTable(admin, entity, objects, manager); break; case FIREBIRD: value = Firebird.createTable(admin, entity, objects, manager); break; } return value; } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/DbmsInterpreter.java
Java
lgpl
3,564
package quickdb.db.dbms.mysql; import java.util.HashMap; import java.sql.Date; /** * * @author Diego Sarmentero */ public class DataType { private HashMap<Class, String> mysqlDataType; public DataType() { //MYSQL this.mysqlDataType = new HashMap<Class, String>(); this.mysqlDataType.put(Integer.class, "INTEGER"); this.mysqlDataType.put(Double.class, "DOUBLE"); this.mysqlDataType.put(Float.class, "FLOAT"); this.mysqlDataType.put(String.class, "VARCHAR"); this.mysqlDataType.put(Boolean.class, "TINYINT(1)"); this.mysqlDataType.put(Long.class, "BIGINT"); this.mysqlDataType.put(Short.class, "SMALLINT"); this.mysqlDataType.put(Date.class, "DATE"); } public String getDataType(Class clazz, int length) { if (clazz == String.class) { length = 150; }else if((clazz == Integer.class) && (length == 1)) { length = 11; } if (clazz == Boolean.class || clazz == Date.class || clazz == Double.class) { return this.mysqlDataType.get(clazz); } else { return this.mysqlDataType.get(clazz).concat("(" + length + ")"); } } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/mysql/DataType.java
Java
lgpl
1,233
package quickdb.db.dbms.mysql; import quickdb.annotation.Column; import quickdb.annotation.ColumnDefinition; import quickdb.db.AdminBase; import quickdb.reflection.EntityManager; import java.lang.annotation.Annotation; import java.lang.reflect.Field; /** * * @author Diego Sarmentero */ public class MySQL { public static boolean createTable(AdminBase admin, Object entity, Object[] objects, EntityManager manager){ StringBuilder statement = new StringBuilder(); DataType dataType = new DataType(); StringBuilder colDefinition = new StringBuilder(); StringBuilder constraints = new StringBuilder(); String primaryKey = String.valueOf(((Object[])objects[1])[0]); statement.append(String.format("CREATE TABLE IF NOT EXISTS " + "%s (", objects[0])); String close = String.format(", PRIMARY KEY (%s)) " + "ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1", primaryKey); Object columns[] = null; if (entity.getClass().getDeclaredAnnotations().length != 0){ columns = manager.mappingDefinition(admin, entity); } Field[] fields = entity.getClass().getDeclaredFields(); boolean primary = true; int q = 1; for (int i = 0; i < fields.length; i++, q++) { boolean withAnnotation = false; boolean ignore = false; String name = fields[i].getName(); Annotation annotations[] = fields[i].getDeclaredAnnotations(); for (Annotation a : annotations) { if(a instanceof ColumnDefinition){ withAnnotation = true; } if (a instanceof Column) { ignore = ((Column) a).ignore(); if(((Column)a).name().length() != 0){ name = ((Column)a).name(); } } } if(ignore){ ignore = false; q--; continue; }else if(!(objects[q] instanceof Object[]) || !name.equalsIgnoreCase(String.valueOf(((Object[]) objects[q])[0]))){ q--; continue; }else if(primary){ primary = false; if(withAnnotation){ statement.append(String.format("%s", ((ColumnDefined) columns[1]).toString())); }else{ statement.append(String.format("%s int(11) NOT NULL AUTO_INCREMENT", primaryKey)); } continue; } if(withAnnotation){ colDefinition.append(String.format(", %s", ((ColumnDefined) columns[q]).toString())); if (((ColumnDefined) columns[q]).hasConstraints()) { constraints.append(String.format(", %s", ((ColumnDefined) columns[q]).obtainConstraints())); } }else{ Object obj[] = (Object[]) objects[q]; statement.append(String.format(", %s %s NOT NULL", obj[0], dataType.getDataType(obj[1].getClass(), obj[1].toString().length()))); } } if (objects[objects.length - 2] instanceof Object[] && ((Object[]) objects[objects.length - 2])[0] == "parent_id") { colDefinition.append(", parent_id int(11) NOT NULL"); } statement.append(colDefinition.toString()); statement.append(constraints.toString()); statement.append(close); return admin.executeQuery(statement.toString()); } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/mysql/MySQL.java
Java
lgpl
3,808
package quickdb.db.dbms.mysql; /** * * @author Diego Sarmentero */ public class ColumnDefined { protected String name; protected String type; protected int length; protected boolean notNull; protected String defaultValue; protected boolean autoIncrement; protected boolean unique; protected boolean primary; protected String format; protected String storage; public ColumnDefined() { } public ColumnDefined(String name, String type, int length, boolean notNull, String defaultValue, boolean autoIncrement, boolean unique, boolean primary, String format, String storage) { this.name = name; this.type = type; this.length = length; this.notNull = notNull; this.defaultValue = defaultValue; this.autoIncrement = autoIncrement; this.unique = unique; this.primary = primary; this.format = format; this.storage = storage; } @Override public String toString() { StringBuilder column = new StringBuilder(); column.append(this.getName() + " " + this.getType() + " "); if (this.getLength() != -1) { column.append("(" + this.getLength() + ") "); } else if (this.getLength() == -1 && this.type.equalsIgnoreCase("VARCHAR")) { column.append("(150) "); } if (this.isNotNull()) { column.append("NOT NULL "); } else { column.append("NULL "); } if (this.defaultValue.length() != 0) { column.append("DEFAULT '" + this.getDefaultValue() + "' "); } if (this.isAutoIncrement()) { column.append("AUTO_INCREMENT "); } if (!this.format.equalsIgnoreCase("DEFAULT")) { column.append("COLUMN_FORMAT " + this.getFormat() + " "); } if (!this.storage.equalsIgnoreCase("DEFAULT")) { column.append("STORAGE " + this.getStorage() + " "); } return column.toString(); } public boolean hasConstraints() { return (this.isUnique() || this.isPrimary()); } public String obtainConstraints() { StringBuilder constraint = new StringBuilder(); if (this.isUnique()) { constraint.append("UNIQUE KEY (" + this.getName() + ") "); } /*if (this.isPrimary()) { constraint.append("PRIMARY KEY (" + this.getName() + ") "); }*/ return constraint.toString(); } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the length */ public int getLength() { return length; } /** * @param length the length to set */ public void setLength(int length) { this.length = length; } /** * @return the notNull */ public boolean isNotNull() { return notNull; } /** * @param notNull the notNull to set */ public void setNotNull(boolean notNull) { this.notNull = notNull; } /** * @return the defaultValue */ public String getDefaultValue() { return defaultValue; } /** * @param defaultValue the defaultValue to set */ public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } /** * @return the autoIncrement */ public boolean isAutoIncrement() { return autoIncrement; } /** * @param autoIncrement the autoIncrement to set */ public void setAutoIncrement(boolean autoIncrement) { this.autoIncrement = autoIncrement; } /** * @return the unique */ public boolean isUnique() { return unique; } /** * @param unique the unique to set */ public void setUnique(boolean unique) { this.unique = unique; } /** * @return the primary */ public boolean isPrimary() { return primary; } /** * @param primary the primary to set */ public void setPrimary(boolean primary) { this.primary = primary; } /** * @return the format */ public String getFormat() { return format; } /** * @param format the format to set */ public void setFormat(String format) { this.format = format; } /** * @return the storage */ public String getStorage() { return storage; } /** * @param storage the storage to set */ public void setStorage(String storage) { this.storage = storage; } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/mysql/ColumnDefined.java
Java
lgpl
5,039
package quickdb.db.dbms.sqlite; import quickdb.annotation.Column; import quickdb.db.AdminBase; import quickdb.reflection.EntityManager; import java.lang.annotation.Annotation; import java.lang.reflect.Field; /** * * @author Diego Sarmentero */ public class SQLite { public static boolean createTable(AdminBase admin, Object entity, Object[] objects, EntityManager manager){ StringBuilder statement = new StringBuilder(); String primaryKey = String.valueOf(((Object[])objects[1])[0]); statement.append(String.format("CREATE TABLE IF NOT EXISTS " + "%s (", objects[0])); Field[] fields = entity.getClass().getDeclaredFields(); boolean primary = true; int q = 1; for (int i = 0; i < fields.length; i++, q++) { boolean ignore = false; String name = fields[i].getName(); Annotation annotations[] = fields[i].getDeclaredAnnotations(); for (Annotation a : annotations) { if (a instanceof Column) { ignore = ((Column) a).ignore(); if(((Column)a).name().length() != 0){ name = ((Column)a).name(); } } } if(ignore){ ignore = false; q--; continue; }else if(!(objects[q] instanceof Object[]) || !name.equalsIgnoreCase(String.valueOf(((Object[]) objects[q])[0]))){ q--; continue; }else if(primary){ primary = false; statement.append(String.format("%s INTEGER PRIMARY KEY", primaryKey)); continue; } statement.append(String.format(", %s", name)); } if (objects[objects.length - 2] instanceof Object[] && ((Object[]) objects[objects.length - 2])[0] == "parent_id") { statement.append(", parent_id"); } statement.append(")"); return admin.executeQuery(statement.toString()); } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/sqlite/SQLite.java
Java
lgpl
2,145
package quickdb.db.dbms.postgre; import quickdb.db.dbms.mysql.ColumnDefined; /** * * @author Diego Sarmentero */ public class ColumnDefinedPostgre extends ColumnDefined { public ColumnDefinedPostgre() { } public ColumnDefinedPostgre(String name, String type, int length, boolean notNull, String defaultValue, boolean autoIncrement, boolean unique, boolean primary, String format, String storage) { this.name = name; this.type = type; this.length = length; this.notNull = notNull; this.defaultValue = defaultValue; this.autoIncrement = autoIncrement; this.unique = unique; this.primary = primary; this.format = format; this.storage = storage; } @Override public String toString() { StringBuilder column = new StringBuilder(); if (this.isAutoIncrement()) { this.setType("serial"); } column.append(this.getName() + " " + this.getType() + " "); if (this.getLength() != -1) { column.append("(" + this.getLength() + ") "); } else if (this.getLength() == -1 && this.type.equalsIgnoreCase("character varying")) { column.append("(150) "); } if (this.isNotNull()) { column.append("NOT NULL "); } else { column.append("NULL "); } if (this.defaultValue.length() != 0) { column.append("DEFAULT '" + this.getDefaultValue() + "' "); } return column.toString(); } @Override public boolean hasConstraints() { return (this.isUnique() || this.isPrimary()); } @Override public String obtainConstraints() { StringBuilder constraint = new StringBuilder(); if (this.isUnique()) { constraint.append("CONSTRAINT un_" + this.getName() + " " + "UNIQUE (" + this.getName() + ") "); } /*if (this.isPrimary()) { if(constraint.length() != 0) constraint.append(", "); constraint.append("CONSTRAINT 'pk_" + this.getName() + "' " + "PRIMARY KEY (" + this.getName() + ") "); }*/ return constraint.toString(); } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/postgre/ColumnDefinedPostgre.java
Java
lgpl
2,276
package quickdb.db.dbms.postgre; import quickdb.annotation.Column; import quickdb.annotation.ColumnDefinition; import quickdb.db.AdminBase; import quickdb.reflection.EntityManager; import java.lang.annotation.Annotation; import java.lang.reflect.Field; /** * * @author Diego Sarmentero */ public class PostgreSQL { public static boolean createTable(AdminBase admin, Object entity, Object[] objects, EntityManager manager) { StringBuilder statement = new StringBuilder(); DataTypePostgre dataType = new DataTypePostgre(); StringBuilder colDefinition = new StringBuilder(); StringBuilder constraints = new StringBuilder(); String primaryKey = String.valueOf(((Object[])objects[1])[0]); statement.append(String.format("CREATE TABLE " + "%s (", admin.getConex().getSchema() + ".\"" + objects[0] + "\"")); String close = String.format(", CONSTRAINT pk_" + objects[0] + "_" + primaryKey + " PRIMARY KEY (%s)) " + "WITH (OIDS=FALSE);", primaryKey); Object columns[] = null; if (entity.getClass().getDeclaredAnnotations().length != 0) { columns = manager.mappingDefinition(admin, entity); } Field[] fields = entity.getClass().getDeclaredFields(); boolean primary = true; int q = 1; for (int i = 0; i < fields.length; i++, q++) { boolean withAnnotation = false; boolean ignore = false; String name = fields[i].getName(); Annotation annotations[] = fields[i].getDeclaredAnnotations(); for (Annotation a : annotations) { if (a instanceof ColumnDefinition) { withAnnotation = true; } if (a instanceof Column) { ignore = ((Column) a).ignore(); if (((Column) a).name().length() != 0) { name = ((Column) a).name(); } } } if (ignore) { ignore = false; q--; continue; } else if (primary) { primary = false; if (withAnnotation) { statement.append(String.format("%s DEFAULT nextval('" + objects[0] + "_seq')", ((ColumnDefinedPostgre) columns[1]).toString())); } else { statement.append(String.format("%s integer NOT NULL " + "DEFAULT nextval('" + objects[0] + "_seq')", primaryKey)); } continue; } else if (!(objects[q] instanceof Object[]) || !name.equalsIgnoreCase(String.valueOf(((Object[]) objects[q])[0]))) { q--; continue; } if (withAnnotation) { colDefinition.append(String.format(", %s", ((ColumnDefinedPostgre) columns[q]).toString())); if (((ColumnDefinedPostgre) columns[q]).hasConstraints()) { constraints.append(String.format(", %s", ((ColumnDefinedPostgre) columns[q]).obtainConstraints())); } } else { Object obj[] = (Object[]) objects[q]; statement.append(String.format(", %s %s NOT NULL", obj[0], dataType.getDataType(obj[1].getClass(), obj[1].toString().length()))); } } if (objects[objects.length - 2] instanceof Object[] && ((Object[]) objects[objects.length - 2])[0] == "parent_id") { colDefinition.append(", parent_id integer NOT NULL"); } statement.append(colDefinition.toString()); statement.append(constraints.toString()); statement.append(close); admin.executeQuery("CREATE SEQUENCE " + objects[0] + "_seq"); return admin.executeQuery(statement.toString()); } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/postgre/PostgreSQL.java
Java
lgpl
4,096
package quickdb.db.dbms.postgre; import java.util.HashMap; import java.sql.Date; /** * * @author Diego Sarmentero */ public class DataTypePostgre { private HashMap<Class, String> mysqlDataType; public DataTypePostgre() { this.mysqlDataType = new HashMap<Class, String>(); this.mysqlDataType.put(Integer.class, "integer"); this.mysqlDataType.put(Double.class, "double precision"); this.mysqlDataType.put(Float.class, "real"); this.mysqlDataType.put(String.class, "character varying"); this.mysqlDataType.put(Boolean.class, "boolean"); this.mysqlDataType.put(Long.class, "bigint"); this.mysqlDataType.put(Short.class, "smallint"); this.mysqlDataType.put(Date.class, "date"); } public String getDataType(Class clazz, int length) { if (clazz == String.class) { length = 150; }else if((clazz == Integer.class) && (length == 1)) { length = 11; } if (clazz == String.class) { return this.mysqlDataType.get(clazz).concat("(" + length + ")"); } else { return this.mysqlDataType.get(clazz); } } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/postgre/DataTypePostgre.java
Java
lgpl
1,184
package quickdb.db.dbms.firebird; import quickdb.annotation.Column; import quickdb.annotation.ColumnDefinition; import quickdb.db.AdminBase; import quickdb.reflection.EntityManager; import java.lang.annotation.Annotation; import java.lang.reflect.Field; /** * * @author Diego Sarmentero */ public class Firebird { public static boolean createTable(AdminBase admin, Object entity, Object[] objects, EntityManager manager){ StringBuilder statement = new StringBuilder(); DataType dataType = new DataType(); StringBuilder colDefinition = new StringBuilder(); StringBuilder constraints = new StringBuilder(); String primaryKey = String.valueOf(((Object[])objects[1])[0]); statement.append(String.format("CREATE TABLE " + "%s (", objects[0])); String close = String.format(", PRIMARY KEY (%s))", primaryKey); Object columns[] = null; if (entity.getClass().getDeclaredAnnotations().length != 0){ columns = manager.mappingDefinition(admin, entity); } Field[] fields = entity.getClass().getDeclaredFields(); boolean primary = true; int q = 1; for (int i = 0; i < fields.length; i++, q++) { boolean withAnnotation = false; boolean ignore = false; String name = fields[i].getName(); Annotation annotations[] = fields[i].getDeclaredAnnotations(); for (Annotation a : annotations) { if(a instanceof ColumnDefinition){ withAnnotation = true; } if (a instanceof Column) { ignore = ((Column) a).ignore(); if(((Column)a).name().length() != 0){ name = ((Column)a).name(); } } } if(ignore){ ignore = false; q--; continue; }else if(!(objects[q] instanceof Object[]) || !name.equalsIgnoreCase(String.valueOf(((Object[]) objects[q])[0]))){ q--; continue; }else if(primary){ primary = false; if(withAnnotation){ statement.append(String.format("%s", ((ColumnDefined) columns[1]).toString())); }else{ statement.append(String.format("%s integer NOT NULL", primaryKey)); } continue; } if(withAnnotation){ colDefinition.append(String.format(", %s", ((ColumnDefined) columns[q]).toString())); if (((ColumnDefined) columns[q]).hasConstraints()) { constraints.append(String.format(", %s", ((ColumnDefined) columns[q]).obtainConstraints())); } }else{ Object obj[] = (Object[]) objects[q]; statement.append(String.format(", %s %s NOT NULL", obj[0], dataType.getDataType(obj[1].getClass(), obj[1].toString().length()))); } } if (objects[objects.length - 2] instanceof Object[] && ((Object[]) objects[objects.length - 2])[0] == "parent_id") { colDefinition.append(", parent_id integer NOT NULL"); } statement.append(colDefinition.toString()); statement.append(constraints.toString()); statement.append(close); admin.executeQuery(statement.toString()); admin.executeQuery("CREATE GENERATOR gen_"+objects[0]+"_id;"); admin.executeQuery("SET GENERATOR gen_"+objects[0]+"_id TO 0;"); return admin.executeQuery("CREATE TRIGGER "+objects[0]+"_BI FOR "+objects[0]+" " + "ACTIVE BEFORE INSERT POSITION 0 " + "AS " + "BEGIN " + "if (NEW.ID is NULL) then NEW.ID = GEN_ID(GEN_"+objects[0]+"_ID, 1); " + "END "); } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/firebird/Firebird.java
Java
lgpl
4,140
package quickdb.db.dbms.firebird; import java.util.HashMap; import java.sql.Date; /** * * @author Diego Sarmentero */ public class DataType { private HashMap<Class, String> firebirdDataType; public DataType() { this.firebirdDataType = new HashMap<Class, String>(); this.firebirdDataType.put(Integer.class, "integer"); this.firebirdDataType.put(Double.class, "double precision"); this.firebirdDataType.put(Float.class, "float"); this.firebirdDataType.put(String.class, "varchar"); this.firebirdDataType.put(Boolean.class, "boolean"); this.firebirdDataType.put(Long.class, "bigint"); this.firebirdDataType.put(Short.class, "smallint"); this.firebirdDataType.put(Date.class, "date"); } public String getDataType(Class clazz, int length) { if (clazz == String.class) { length = 150; }else if((clazz == Integer.class) && (length == 1)) { length = 11; } if (clazz == String.class) { return this.firebirdDataType.get(clazz).concat("(" + length + ")"); } else { return this.firebirdDataType.get(clazz); } } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/firebird/DataType.java
Java
lgpl
1,198
package quickdb.db.dbms.firebird; /** * * @author Diego Sarmentero */ public class ColumnDefined { protected String name; protected String type; protected int length; protected boolean notNull; protected String defaultValue; protected boolean autoIncrement; protected boolean unique; protected boolean primary; protected String format; protected String storage; public ColumnDefined() { } public ColumnDefined(String name, String type, int length, boolean notNull, String defaultValue, boolean autoIncrement, boolean unique, boolean primary, String format, String storage) { this.name = name; this.type = type; this.length = length; this.notNull = notNull; this.defaultValue = defaultValue; this.autoIncrement = autoIncrement; this.unique = unique; this.primary = primary; this.format = format; this.storage = storage; } @Override public String toString() { StringBuilder column = new StringBuilder(); column.append(this.getName() + " " + this.getType() + " "); if (this.getLength() != -1) { column.append("(" + this.getLength() + ") "); } else if (this.getLength() == -1 && this.type.equalsIgnoreCase("varchar")) { column.append("(150) "); } if (this.isNotNull()) { column.append("not null "); } else { column.append("null "); } if (this.defaultValue.length() != 0) { column.append("default '" + this.getDefaultValue() + "' "); } return column.toString(); } public boolean hasConstraints() { return (this.isUnique() || this.isPrimary()); } public String obtainConstraints() { StringBuilder constraint = new StringBuilder(); if (this.isUnique()) { constraint.append("UNIQUE (" + this.getName() + ") "); } return constraint.toString(); } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the length */ public int getLength() { return length; } /** * @param length the length to set */ public void setLength(int length) { this.length = length; } /** * @return the notNull */ public boolean isNotNull() { return notNull; } /** * @param notNull the notNull to set */ public void setNotNull(boolean notNull) { this.notNull = notNull; } /** * @return the defaultValue */ public String getDefaultValue() { return defaultValue; } /** * @param defaultValue the defaultValue to set */ public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } /** * @return the autoIncrement */ public boolean isAutoIncrement() { return autoIncrement; } /** * @param autoIncrement the autoIncrement to set */ public void setAutoIncrement(boolean autoIncrement) { this.autoIncrement = autoIncrement; } /** * @return the unique */ public boolean isUnique() { return unique; } /** * @param unique the unique to set */ public void setUnique(boolean unique) { this.unique = unique; } /** * @return the primary */ public boolean isPrimary() { return primary; } /** * @param primary the primary to set */ public void setPrimary(boolean primary) { this.primary = primary; } /** * @return the format */ public String getFormat() { return format; } /** * @param format the format to set */ public void setFormat(String format) { this.format = format; } /** * @return the storage */ public String getStorage() { return storage; } /** * @param storage the storage to set */ public void setStorage(String storage) { this.storage = storage; } }
zzqchy-qaw1
java/src/main/java/quickdb/db/dbms/firebird/ColumnDefined.java
Java
lgpl
4,554
package quickdb.db; import quickdb.query.Query; import quickdb.reflection.ReflectionUtilities; /** * * @author Diego Sarmentero */ public class AdminBinding { private static AdminBase admin; public static void initializeAdminBase(AdminBase admin) { AdminBinding.admin = admin; } public boolean save() { return AdminBinding.admin.save(this); } public int saveGetIndex() { return AdminBinding.admin.saveGetIndex(this); } public boolean modify() { return AdminBinding.admin.modify(this); } public boolean delete() { return AdminBinding.admin.delete(this); } public boolean lazyLoad(String sql) { boolean value = false; if (sql.length() == 0) { value = AdminBinding.admin.lazyLoad(this); } else { value = AdminBinding.admin.lazyLoad(this, sql); } return value; } public boolean obtainWhere(String sql) { return AdminBinding.admin.obtainWhere(this, sql); } public boolean obtain(String sql) { return AdminBinding.admin.obtain(this, sql); } public Query obtain() { return AdminBinding.admin.obtain(this); } public boolean obtainSelect(String sql) { return AdminBinding.admin.obtainSelect(this, sql); } public void openAtomicBlock(){ this.admin.openAtomicBlock(); } public void closeAtomicBlock(){ this.admin.closeAtomicBlock(); } public void cancelAtomicBlock(){ this.admin.cancelAtomicBlock(); } public void setAutoCommit(boolean value){ this.admin.setAutoCommit(value); } /** * Return True if the specified Table exist in the Database * @param Table Name * @return Boolean */ public boolean checkTableExist() { ReflectionUtilities reflec = new ReflectionUtilities(); String name = reflec.readTableName(this.getClass()); return this.admin.checkTableExist(name); } }
zzqchy-qaw1
java/src/main/java/quickdb/db/AdminBinding.java
Java
lgpl
2,024
package quickdb.db; import quickdb.reflection.EntityManager; import java.sql.Date; import java.sql.SQLException; import java.util.ArrayList; /** * * @author Diego Sarmentero */ public class AdminSQLite extends AdminBase { AdminSQLite(DATABASE db, String... args) { super(db, args); } @Override protected int saveProcess(ArrayList array, Object object) { int index = -1; String table = ""; int i = 1; try { if (this.forceTable) { table = tableForcedName; array.set(0, table); } else { table = String.valueOf(array.get(0)); } ((Object[]) array.get(1))[1] = "NULL"; StringBuilder insert = new StringBuilder("INSERT INTO " + table + "("); StringBuilder values = new StringBuilder("VALUES("); for (; i < array.size() - 1; i++) { Object[] obj = (Object[]) array.get(i); String column = (String) obj[0]; Object value = obj[1]; if (i > 1) { insert.append(", "); values.append(", "); } insert.append(column); if ((i > 1) && ((value instanceof String) || (value instanceof Date))) { values.append("'" + value + "'"); } else { values.append(value.toString()); } } insert.append(")"); values.append(")"); index = this.conex.insertRow(insert.toString() + " " + values.toString()); if (this.getCollection()) { this.saveMany2Many(((String) array.get(0)), true, index); } } catch (SQLException ex) { int value = -1; try { this.conex.getConnection().setAutoCommit(true); if (!this.checkTableExist(table)) { if (this.createTable(object, array.toArray())) { value = this.saveProcess(array, object); } } } catch (Exception e) { } return value; } catch (Exception e) { conex.connectMySQL(); try { conex.cancelTransaction(); } catch (Exception ex) { return -1; } } return index; } @Override protected boolean modifyProcess(Object object) { ArrayList array = this.manager.entity2Array(this, object, EntityManager.OPERATION.MODIFY); try { StringBuilder update = new StringBuilder("UPDATE " + ((String) array.get(0)) + " SET "); for (int i = 1; i < array.size() - 1; i++) { Object[] obj = (Object[]) array.get(i); String column = (String) obj[0]; Object value = obj[1]; if (i > 1) { update.append(", "); } update.append(column + " = "); if ((i > 1) && ((value instanceof String) || (value instanceof Date))) { update.append("'" + value + "'"); } else { update.append(value.toString()); } } update.append(" WHERE " + String.valueOf(array.get(array.size() - 1))); this.conex.insertRow(update.toString()); int index = Integer.parseInt(String.valueOf(array.get(array.size() - 1)). substring(String.valueOf(array.get(array.size() - 1)).indexOf("=")+1)); if (this.getCollection()) { this.saveMany2Many(((String) array.get(0)), false, index); } } catch (Exception e) { try { conex.cancelTransaction(); } catch (Exception ex) { return false; } return false; } return true; } }
zzqchy-qaw1
java/src/main/java/quickdb/db/AdminSQLite.java
Java
lgpl
4,091
package quickdb.query; import quickdb.annotation.Column; import quickdb.annotation.Parent; import quickdb.annotation.Properties; import quickdb.exception.QueryException; import quickdb.reflection.ReflectionUtilities; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * * @author Diego Sarmentero */ public final class StringQuery { private static final String regObj = "(\\w+\\.\\w+)+|\\w+"; private static final String tokens = "[=!<>\\&\\|]|( LIKE )|( like )"; private static final ReflectionUtilities ref = new ReflectionUtilities(); /** * Return a String with the SQL Representation of the query expressed in * an Object Oriented way in the Condition containing the fields of the Object * @param Object to be evaluated * @param condition [String] representing the Query in an Object Oriented way * @return String with the SQL Representation of the Query */ public static String parse(Class clazz, String condition) { //Replace and, or Pattern p = Pattern.compile("( AND )|( \\&{2} )", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(condition); condition = m.replaceAll(" & "); p = Pattern.compile("( OR )|( \\|{2} )", Pattern.CASE_INSENSITIVE); m = p.matcher(condition); condition = m.replaceAll(" | "); String columns = StringQuery.mainData(clazz); String[] eval = condition.split(StringQuery.tokens); ArrayList<String> array = new ArrayList<String>(); ArrayList<String> values = new ArrayList<String>(); p = Pattern.compile(StringQuery.regObj); for (int i = 0; i < eval.length; i += 2) { m = p.matcher(eval[i].trim()); if (m.matches()) { array.add(StringQuery.selectData(clazz, eval[i].trim())); values.add(eval[i + 1].trim()); } else { throw new QueryException(); } } ArrayList<String> operators = new ArrayList<String>(); Pattern pToken = Pattern.compile(StringQuery.tokens); Matcher mToken = pToken.matcher(condition); while (mToken.find()) { operators.add(mToken.group()); } StringBuilder tables = new StringBuilder(); StringBuilder where = new StringBuilder(); int size = array.size(); int indexOper = 0; tables.append(array.get(0).substring(0, array.get(0).indexOf("|"))); for (int i = 0; i < size; i++) { String[] parts = array.get(i).split("\\|"); for (int q = 1; q < parts.length - 2; q += 2) { if (tables.indexOf(parts[q]) == -1) { tables.append(" JOIN " + parts[q + 1] + " ON " + parts[q]); } } if (i > 0) { where.append(" " + StringQuery.separator(operators.get(indexOper++)) + " "); } where.append(parts[parts.length - 1] + operators.get(indexOper++) + values.get(i)); } return "SELECT " + columns + " FROM " + tables.toString() + " WHERE " + where.toString(); } private static String separator(String evaluator) { if (evaluator.trim().equalsIgnoreCase("&")) { return "AND"; } else if (evaluator.trim().equalsIgnoreCase("|")) { return "OR"; } else { throw new QueryException(); } } private static String selectData(Class clazz, String evaluator) { String data; String[] refer = evaluator.split("\\."); data = StringQuery.evaluatorData(clazz, refer, 0); return data; } static int inheritedAttribute(Class clazz, String attr) { int inher = 0; boolean inherit = StringQuery.ref.hasParent(clazz); if (inherit) { Class value = clazz.getSuperclass(); Field[] fields = value.getDeclaredFields(); for (Field f : fields) { if (f.getName().equalsIgnoreCase(attr)) { inher++; } } if ((inher == 0)) { inher = StringQuery.inheritedAttribute(value, attr); if (inher > 0) { inher++; } } } return inher; } private static String evaluatorData(Class clazz, String[] ref, int index) { StringBuilder statement = new StringBuilder(); String table = StringQuery.ref.readTableName(clazz); Class value = StringQuery.obtainReference(clazz, ref[index]); String tableRef = StringQuery.ref.readTableName(value); String colMain = StringQuery.columnName(clazz, ref[index]); String colId = StringQuery.tableIndex(value); try { int inherit = 0; if(!table.equalsIgnoreCase(tableRef)){ inherit = StringQuery.inheritedAttribute(clazz, ref[index]); } if (index < ref.length - 1) { if (inherit == 0) { statement.append(table + "|" + table + "." + colMain + " = " + tableRef + "." + colId + "|"); index++; statement.append(StringQuery.evaluatorData(value, ref, index)); } } else { if (inherit == 0) { colMain = StringQuery.columnName(clazz, ref[index]); statement.append(table + "|" + table + "." + colMain + " |"); } } if ((inherit > 0)) { Class inher = clazz; for (int i = 0; i < inherit; i++) { table = StringQuery.ref.readTableName(inher); value = inher.getSuperclass(); tableRef = StringQuery.ref.readTableName(value); colId = StringQuery.tableIndex(value); statement.append(table + "|" + table + ".parent_id = " + tableRef + "." + colId + "|"); inher = value; } statement.append(StringQuery.evaluatorData(value, ref, index)); } } catch (Exception e) { e.printStackTrace(); } return statement.toString(); } static Class obtainReference(Class clazz, String reference) { try { Method getter = StringQuery.ref.obtainGetter(clazz, reference); if(getter.getReturnType().isPrimitive() || StringQuery.ref.checkPrimitivesExtended(getter.getReturnType(), null)){ return clazz; } Class value = getter.getReturnType(); return value; } catch (Exception e) { int inher = StringQuery.inheritedAttribute(clazz, reference); if (inher > 0) { Class value = clazz.getSuperclass(); for (int i = 0; i < inher - 1; i++) { value = value.getSuperclass(); } return StringQuery.obtainReference(value, reference); } } return clazz; } static Object[] obtainReferenceByReturn(Class clazz, Class ret) { Object[] result = new Object[2]; String field = ""; Class c = clazz; boolean found = false; while(StringQuery.ref.hasParent(c)){ Field[] fields = c.getDeclaredFields(); for(Field f : fields){ if(f.getType() == ret){ field = StringQuery.columnName(c, f.getName()); found = true; } } if(found) break; c = c.getSuperclass(); } if(!found){ Field[] fields = c.getDeclaredFields(); for(Field f : fields){ if(f.getType() == ret){ field = StringQuery.columnName(c, f.getName()); found = true; } } } result[0] = c; result[1] = field; return result; } static String mainData(Class clazz) { StringBuilder mainCol = new StringBuilder(); String table = StringQuery.ref.readTableName(clazz); String summary = ""; String as = ""; //Attributes Field fields[] = clazz.getDeclaredFields(); boolean ignore = false; for (Field f : fields) { String fieldName = f.getName(); String name = fieldName; Annotation ann[] = f.getDeclaredAnnotations(); if (ann.length == 0) { name = fieldName; } else { for (Annotation a : ann) { if (!(a instanceof Column)) { continue; } if (((Column) a).name().length() != 0) { name = ((Column) a).name(); } if(((Column) a).summary().length() != 0){ String summaryProp = ((Column) a).summary().trim(); summary = summaryProp.substring(0, 1); name = StringQuery.ref.columnName(summaryProp.substring(1), clazz); as = "'" + f.getName() + "'"; } ignore = ((Column) a).ignore(); break; } } if(summary.length() != 0){ mainCol.append(summary + table + "." + name + ") " + as + ", "); summary = ""; as = ""; }else if (!ignore && !StringQuery.ref.implementsCollection(clazz, fieldName)) { mainCol.append(table + "." + name + ", "); } } mainCol.delete(mainCol.length() - 2, mainCol.length() - 1); Annotation entity[] = clazz.getDeclaredAnnotations(); if (entity.length > 0) { for (int i = 0; i < entity.length; i++) { if (entity[i] instanceof Parent) { mainCol.append(", " + table + ".parent_id"); break; } } } else if (clazz.getPackage() == clazz.getSuperclass().getPackage()) { mainCol.append(", " + table + ".parent_id"); } return StringQuery.includeSummaryColumns(mainCol.toString()); } public static String includeSummaryColumns(String select){ String cols[] = select.split(","); StringBuilder columns = new StringBuilder(); for(String col : cols){ if(col.contains("+")){ col = col.replace("+", "SUM("); }else if(col.contains("%")){ col = col.replace("%", "AVG("); }else if(col.contains(">")){ col = col.replace(">", "MAX("); }else if(col.contains("<")){ col = col.replace("<", "MIN("); }else if(col.contains("#")){ col = col.replace("#", "COUNT("); } columns.append("," + col); } return columns.toString().substring(1); } static String columnName(Class clazz, String field) { String name = field; try { Field f = clazz.getDeclaredField(field); Annotation[] ann = f.getDeclaredAnnotations(); for (Annotation a : ann) { if ((a instanceof Column) && (((Column) a).name().length() != 0)) { name = ((Column) a).name(); } } } catch (Exception e) { int inher = StringQuery.inheritedAttribute(clazz, field); if (inher > 0) { Class value = clazz.getSuperclass(); for (int i = 0; i < inher - 1; i++) { value = value.getSuperclass(); } return StringQuery.columnName(value, field); } throw new QueryException(); } return name; } static String tableIndex(Class clazz) { String index = "id"; try { Field[] fields = clazz.getDeclaredFields(); Annotation[] ann = fields[0].getDeclaredAnnotations(); for (Annotation a : ann) { if ((a instanceof Column) && ((Column) a).type() == Properties.TYPES.PRIMARYKEY) { if (((Column) a).name().length() == 0) { index = fields[0].getName(); break; } else { index = ((Column) a).name(); break; } } } if (ann.length == 0) { index = "id"; } } catch (Exception e) { throw new QueryException(); } return index; } }
zzqchy-qaw1
java/src/main/java/quickdb/query/StringQuery.java
Java
lgpl
13,091
package quickdb.query; import java.util.ArrayList; /** * * @author Diego Sarmentero */ public interface IQuery { boolean find(); ArrayList findAll(); void dataForViews(String fields, String names, Object obj, Class... clazz); }
zzqchy-qaw1
java/src/main/java/quickdb/query/IQuery.java
Java
lgpl
249
package quickdb.query; import java.util.ArrayList; import quickdb.exception.SubQueryException; /** * * @author Diego Sarmentero */ public class Where implements IQuery { Query query; private StringBuilder condition; private DateQuery date; private boolean hasSub; private String sub; private boolean waitingForSub; private Where(Query query) { this.query = query; this.condition = new StringBuilder(); this.date = DateQuery.createDate(this); this.hasSub = false; this.waitingForSub = false; } static Where createWhere(Query query) { Where where = new Where(query); return where; } @Override public void dataForViews(String fields, String names, Object obj, Class... clazz) { this.query.dataForViews(fields, names, clazz); } void addCondition(String cond) { this.condition.append(" " + cond); } public SubQuery For(String attr, Class clazz) { if(!this.waitingForSub){ throw new SubQueryException("For was not expected."); } this.waitingForSub = false; SubQuery subQ = SubQuery.createSubQuery(this, attr, clazz); return subQ; } public Query equal(Object... object) { this.manageOperation("=", object); return this.query; } public Query greater(Object... object) { this.manageOperation(">", object); return this.query; } public Query lower(Object... object) { this.manageOperation("<", object); return this.query; } public Query equalORgreater(Object... object) { this.manageOperation(">=", object); return this.query; } public Query equalORlower(Object... object) { this.manageOperation("<=", object); return this.query; } public Query notEqual(Object... object) { this.manageOperation("<>", object); return this.query; } public Where not() { this.condition.append(" NOT "); return this; } public Query isNull() { this.condition.append(" IS NULL "); return this.query; } public Query isNotNull() { this.condition.append(" IS NOT NULL "); return this.query; } public Query inRange(Object val1, Object val2) { this.condition.append(" BETWEEN '" + val1 + "' AND '" + val2 + "'"); return this.query; } @Deprecated public Query between(Object val1, Object val2) { return this.inRange(val1, val2); } public Query in(Object... object) { if (this.hasSub) { this.manageOperation("IN", object); this.hasSub = false; }else{ this.condition.append(" IN ("); for (int i = 0; i < object.length; i++) { if (i > 0) { this.condition.append(", "); } if (object[i] instanceof String) { this.condition.append("'" + object[i] + "'"); } else { this.condition.append(object[i]); } } this.condition.append(")"); } return this.query; } public Query match(String value) { this.condition.append(" LIKE "); if (this.hasSub) { this.condition.append(" " + this.sub + " "); this.hasSub = false; }else{ if (!value.contains("_") && !value.contains("%")) { value = "%" + value + "%"; } this.condition.append("'" + value + "'"); } return this.query; } void addSubQueryCondition(String sub) { this.hasSub = true; this.sub = sub; } public DateQuery date() { int index = this.condition.lastIndexOf(" "); String lastCondition = this.condition.substring(index); this.condition.delete(index, this.condition.length()); this.date.setWhereCondition(lastCondition.trim()); return this.date; } @Override public boolean find() { return this.query.find(); } @Override public ArrayList findAll() { return this.query.findAll(); } private String stringObject(Object object) { return "'" + String.valueOf(object) + "'"; } private void manageOperation(String oper, Object[] object) { if(this.waitingForSub){ throw new SubQueryException(); } if (this.hasSub) { this.processObject(object); if(oper.contains("<")){ oper = oper.replace("<", ">"); }else if(oper.contains(">")){ oper = oper.replace(">", "<"); } this.condition.append(" " + oper + " "); this.condition.append(" " + this.sub + " "); this.hasSub = false; } else { this.condition.append(" " + oper + " "); this.processObject(object); } } private void processObject(Object... object) { if (object.length == 1) { if (object[0] instanceof String) { this.condition.append(this.stringObject(object[0])); } else { this.condition.append(String.valueOf(object[0])); } } else { String whereCondition; String field = String.valueOf(object[0]); Class clazz = (Class) object[1]; if (object.length == 3) { Object obj = object[2]; whereCondition = this.query.processRequest(field, clazz, obj); } else { whereCondition = this.query.processRequest(field, clazz); } this.addCondition(whereCondition); } } Query returnQuery() { return this.query; } @Override public String toString() { return this.condition.toString(); } public void waitForSub(){ this.waitingForSub = true; } }
zzqchy-qaw1
java/src/main/java/quickdb/query/Where.java
Java
lgpl
6,050
package quickdb.query; import quickdb.db.AdminBase; import quickdb.reflection.ReflectionUtilities; import java.lang.reflect.Field; import java.util.ArrayList; import quickdb.exception.SubQueryCloseException; /** * * @author Diego Sarmentero */ public class Query implements IQuery { AdminBase admin; protected StringBuilder select; protected StringBuilder from; protected StringBuilder groupby; protected StringBuilder order; protected Where where; protected Where having; ReflectionUtilities reflec; private Object object; protected String table; protected Query(AdminBase admin, Object object) { this.admin = admin; this.object = object; this.reflec = new ReflectionUtilities(); this.from = new StringBuilder(); this.select = new StringBuilder(); this.table = this.reflec.readTableName(this.object.getClass()); this.from.append(this.table); this.select.append(StringQuery.mainData(object.getClass())); } public static Query create(AdminBase admin, Object object) { return new Query(admin, object); } @Override public void dataForViews(String fields, String names, Object obj, Class... clazz){ String splitFields[] = fields.split(","); if(names.equalsIgnoreCase("")){ Field[] objFields = obj.getClass().getDeclaredFields(); StringBuilder strbui = new StringBuilder(); for(Field f : objFields){ strbui.append(StringQuery.columnName(obj.getClass(), f.getName())+", "); } strbui.deleteCharAt(strbui.length()-2); names = strbui.toString(); } String splitNames[] = names.split(","); this.select.delete(0, this.select.length()); for(int i = 0; i < splitFields.length; i++){ String addSelect = this.processRequest(splitFields[i].trim(), clazz[i]); if(i > 0){ this.select.append(", "); } this.select.append(addSelect+" '"+splitNames[i].trim()+"'"); } this.object = obj; } public Where If(Object... condition) { if (this.where == null) { this.where = Where.createWhere(this); } if(condition.length == 0){ this.where.waitForSub(); return this.where; }else{ String field = String.valueOf(condition[0]); Object[] clazz = new Object[condition.length-1]; for(int i = 0; i < condition.length-1; i++){ clazz[i] = condition[i+1]; } String whereCondition = this.processRequest(field, clazz); this.where.addCondition(whereCondition); } return this.where; } @Deprecated public Where where(String field, Object... clazz) { return this.If(field, clazz); } public Where and(Object... condition) { if(condition.length == 0){ this.where.addCondition("AND"); this.where.waitForSub(); return this.where; }else{ String field = String.valueOf(condition[0]); Object[] clazz = new Object[condition.length-1]; for(int i = 0; i < condition.length-1; i++){ clazz[i] = condition[i+1]; } this.where.addCondition("AND"); String whereCondition; if(field.matches("[+|%|<|>|#]\\w+")){ String summary = field.substring(0, 1); whereCondition = this.processRequest(field.substring(1), ((Object[]) clazz)); whereCondition = StringQuery.includeSummaryColumns(summary + whereCondition) + ")"; }else{ whereCondition = this.processRequest(field, clazz); } if (this.having == null) { this.where.addCondition(whereCondition); return this.where; } else { this.having.addCondition(whereCondition); return this.having; } } } public Where or(Object... condition) { if(condition.length == 0){ this.where.addCondition("OR"); this.where.waitForSub(); return this.where; }else{ String field = String.valueOf(condition[0]); Object[] clazz = new Object[condition.length-1]; for(int i = 0; i < condition.length-1; i++){ clazz[i] = condition[i+1]; } this.where.addCondition("OR"); String whereCondition; if(field.matches("[+|%|<|>|#]\\w+")){ String summary = field.substring(0, 1); whereCondition = this.processRequest(field.substring(1), ((Object[]) clazz)); whereCondition = StringQuery.includeSummaryColumns(summary + whereCondition) + ")"; }else{ whereCondition = this.processRequest(field, clazz); } if (this.having == null) { this.where.addCondition(whereCondition); return this.where; } else { this.having.addCondition(whereCondition); return this.having; } } } public Query group(String fields, Class... clazz) { if (this.groupby == null) { this.groupby = new StringBuilder(); this.groupby.append("GROUP BY "); String[] splitField = fields.split(","); if(clazz.length == 0){ clazz = new Class[splitField.length]; for(int i = 0; i < splitField.length; i++){ clazz[i] = this.obtainClassBase(); } } for (int i = 0; i < splitField.length; i++) { if (i > 0) { this.groupby.append(", "); } Class c = clazz[i]; String whereCondition = this.processRequest(splitField[i].trim(), c); if (this.select.indexOf(whereCondition) == -1) { this.select.append(", " + whereCondition); } this.groupby.append(whereCondition); } } return this; } public Where ifGroup(String field, Class... clazz) { if (this.groupby != null) { this.having = Where.createWhere(this); this.groupby.append(" HAVING "); String whereCondition; if(field.matches("[+|%|<|>|#]\\w+")){ String summary = field.substring(0, 1); whereCondition = this.processRequest(field.substring(1), ((Object[]) clazz)); whereCondition = StringQuery.includeSummaryColumns(summary + whereCondition) + ")"; }else{ whereCondition = this.processRequest(field, ((Object[]) clazz)); } this.having.addCondition(whereCondition); } return this.having; } @Deprecated public Where whereGroup(String field, Class... clazz) { return this.ifGroup(field, clazz); } public Query anyElement(){ if (this.having == null) { this.where.addCondition("ANY"); } else { this.having.addCondition("ANY"); } return this; } public Query allElements(){ if (this.having == null) { this.where.addCondition("ALL"); } else { this.having.addCondition("ALL"); } return this; } public Query sort(boolean asc, String fields, Class... clazz) { if (this.order == null) { this.order = new StringBuilder(); this.order.append("ORDER BY "); String[] splitField = fields.split(","); if(clazz.length == 0){ clazz = new Class[splitField.length]; for(int i = 0; i < splitField.length; i++){ clazz[i] = this.obtainClassBase(); } } for (int i = 0; i < splitField.length; i++) { if (i > 0) { this.order.append(", "); } Class c = clazz[i]; String whereCondition = this.processRequest(splitField[i].trim(), c); this.order.append(whereCondition); } if (!asc) { this.order.append(" DESC"); } } return this; } @Override public boolean find() { StringBuilder sql = new StringBuilder(); sql.append("SELECT " + this.select.toString() + " FROM " + this.from.toString()); if (this.where != null) { sql.append(" WHERE " + this.where.toString()); } if (this.groupby != null) { sql.append(" " + this.groupby.toString()); } if (this.having != null) { sql.append(" " + this.having.toString()); } if (this.order != null) { sql.append(" " + this.order.toString()); } return this.admin.obtainSelect(this.object, sql.toString()); } @Override public ArrayList findAll() { StringBuilder sql = new StringBuilder(); sql.append("SELECT " + this.select.toString() + " FROM " + this.from.toString()); if (this.where != null) { sql.append(" WHERE " + this.where.toString()); } if (this.groupby != null) { sql.append(" " + this.groupby.toString()); } if (this.having != null) { sql.append(" " + this.having.toString()); } if (this.order != null) { sql.append(" " + this.order.toString()); } ArrayList array = this.admin.obtainAll(this.object.getClass(), sql.toString()); return array; } protected String processRequest(String field, Object... clazz) { Class c; if (clazz.length != 0) { c = (Class) clazz[0]; } else { c = this.object.getClass(); } Class value = StringQuery.obtainReference(c, field); String tableRef = this.reflec.readTableName(value); String colMain = StringQuery.columnName(c, field); int inher = 0; if(c.isInstance(this.object)){ inher = StringQuery.inheritedAttribute(this.obtainClassBase(), field); }else{} String whereCondition; if (this.obtainClassBase() == value) { whereCondition = this.table + "." + colMain; } else if ((inher != 0)) { if ((inher > 0)) { this.addInheritanceRelation(c, inher); } whereCondition = tableRef + "." + colMain; } else { Class clazzResult; String fieldResult; if (clazz.length == 2) { fieldResult = String.valueOf(clazz[1]); clazzResult = this.obtainClassBase(); int inherRef = StringQuery.inheritedAttribute(clazzResult, fieldResult); for(int i=0; i < inherRef; i++){clazzResult = clazzResult.getSuperclass();} this.checkForCollection(clazzResult, fieldResult); } else { Object[] result = StringQuery.obtainReferenceByReturn(this.object.getClass(), c); clazzResult = (Class) result[0]; fieldResult = String.valueOf(result[1]); } if (fieldResult.length() == 0) { this.addStartFrom(this.reflec.readTableName(c) + ", "); } else if ((clazzResult != this.obtainClassBase())) { int inherit = 0; value = this.obtainClassBase(); while (value != clazzResult) { inherit++; value = value.getSuperclass(); } if (inherit > 0) { this.addInheritanceRelation( this.obtainClassBase(), inherit); } String tableBase = this.reflec.readTableName(clazzResult); String tableRefBase = this.reflec.readTableName(c); if (this.from.indexOf("JOIN " + tableRefBase + " ") == -1) { String colId = StringQuery.tableIndex(c); this.from.append(" JOIN " + tableRefBase + " ON " + tableBase + "." + fieldResult + " = " + tableRefBase + "." + colId); } }else{ String tableBase = this.reflec.readTableName(clazzResult); String tableRefBase = this.reflec.readTableName(c); if (this.from.indexOf("JOIN " + tableRefBase + " ") == -1) { String colId = StringQuery.tableIndex(c); this.from.append(" JOIN " + tableRefBase + " ON " + tableBase + "." + fieldResult + " = " + tableRefBase + "." + colId); } } int inherit = StringQuery.inheritedAttribute(c, field); if ((inherit > 0)) { this.addInheritanceRelation(c, inherit); } whereCondition = tableRef + "." + colMain; } return whereCondition; } private void checkForCollection(Class clazz, String field){ if(this.reflec.implementsCollection(clazz, field)){ String table1 = this.reflec.readTableName(clazz); Class clazz2 = this.reflec.obtainItemCollectionType(clazz, field); String table2 = this.reflec.readTableName(clazz2); String index1 = this.reflec.checkIndex(clazz); String index2 = this.reflec.checkIndex(clazz2); String tableName = table1 + table2 + field.substring(0, 1).toUpperCase() + field.substring(1); String col1 = "base"; String col2 = "related"; if(!this.admin.checkTableExist(table)){ tableName = table2 + field.substring(0, 1).toUpperCase() + field.substring(1) + table1; col1 = "related"; col2 = "base"; } this.from.append(" JOIN " + tableName + " ON " + tableName + "." + col1 + " = " + table1 + "." + index1 + " JOIN " + table2 + " ON " + table2 + "." + index2 + " = " + tableName + "." + col2); } } void addInheritanceRelation(Class clazz, int inherit) { Class inher = clazz; for (int i = 0; i < inherit; i++) { String tableInher = this.reflec.readTableName(inher); Class value = inher.getSuperclass(); String tableRef = this.reflec.readTableName(value); if (this.from.indexOf("JOIN " + tableRef + " ") == -1) { String colId = StringQuery.tableIndex(value); this.from.append(" JOIN " + tableRef + " ON " + tableInher + ".parent_id = " + tableRef + "." + colId); inher = value; } } } Class obtainClassBase() { return this.object.getClass(); } void addStartFrom(String fromTable) { if(this.from.indexOf(fromTable) == -1){ this.from.insert(0, fromTable); } } void addEndFrom(String fromTable) { this.from.append(fromTable); } public Where closeFor(){ throw new SubQueryCloseException(); } }
zzqchy-qaw1
java/src/main/java/quickdb/query/Query.java
Java
lgpl
15,629
package quickdb.query; import quickdb.db.AdminBase; import java.util.Hashtable; /** * * @author Diego Sarmentero */ public class DateQuery { private Where where; private String whereCondition; private enum OPERATIONS{ DATEDIFF, MONTH, YEAR, DAY } private Hashtable<OPERATIONS, String> mysql; private Hashtable<OPERATIONS, String> postgre; private Hashtable<OPERATIONS, String> sqlserver; private Hashtable<OPERATIONS, String> firebird; private DateQuery(Where where) { this.where = where; mysql = new Hashtable<OPERATIONS, String>(); postgre = new Hashtable<OPERATIONS, String>(); sqlserver = new Hashtable<OPERATIONS, String>(); firebird = new Hashtable<OPERATIONS, String>(); mysql.put(OPERATIONS.DAY, "DAY("); mysql.put(OPERATIONS.MONTH, "MONTH("); mysql.put(OPERATIONS.YEAR, "YEAR("); mysql.put(OPERATIONS.DATEDIFF, "DATEDIFF("); sqlserver.put(OPERATIONS.DAY, "DAY("); sqlserver.put(OPERATIONS.MONTH, "MONTH("); sqlserver.put(OPERATIONS.YEAR, "YEAR("); sqlserver.put(OPERATIONS.DATEDIFF, "DATEDIFF(dd, "); postgre.put(OPERATIONS.DAY, "date_part(day, TIMESTAMP "); postgre.put(OPERATIONS.MONTH, "date_part(month, TIMESTAMP "); postgre.put(OPERATIONS.YEAR, "date_part(year, TIMESTAMP "); postgre.put(OPERATIONS.DATEDIFF, ""); firebird.put(OPERATIONS.DAY, "EXTRACT(DAY FROM "); firebird.put(OPERATIONS.MONTH, "EXTRACT(MONTH FROM "); firebird.put(OPERATIONS.YEAR, "EXTRACT(YEAR FROM "); firebird.put(OPERATIONS.DATEDIFF, ""); } static DateQuery createDate(Where where) { return new DateQuery(where); } void setWhereCondition(String cond) { this.whereCondition = cond; } public Where differenceWith(String value, Object... clazz) { String condition2; if (clazz.length == 1) { condition2 = this.where.query.processRequest(value, clazz[0]); } else { condition2 = "'" + value + "'"; } String operation = this.obtainProperFunction(OPERATIONS.DATEDIFF); if(operation.equalsIgnoreCase("") && (this.where.query.admin.getDB() == AdminBase.DATABASE.POSTGRES)){ this.where.addCondition("TIMESTAMP " + condition2 + " - TIMESTAMP " + this.whereCondition); }else if(operation.equalsIgnoreCase("") && (this.where.query.admin.getDB() == AdminBase.DATABASE.FIREBIRD)){ this.where.addCondition(condition2 + " - " + this.whereCondition); }else{ this.where.addCondition(operation + condition2 + ", " + this.whereCondition + ")"); } return this.where; } public Where month() { String operation = this.obtainProperFunction(OPERATIONS.MONTH); this.where.addCondition(operation + this.whereCondition + ")"); return this.where; } public Where year() { String operation = this.obtainProperFunction(OPERATIONS.YEAR); this.where.addCondition(operation + this.whereCondition + ")"); return this.where; } public Where day() { String operation = this.obtainProperFunction(OPERATIONS.DAY); this.where.addCondition(operation + this.whereCondition + ")"); return this.where; } private String obtainProperFunction(OPERATIONS oper){ String value; switch(this.where.query.admin.getDB()){ case POSTGRES: value = this.postgre.get(oper);break; case SQLSERVER: value = this.sqlserver.get(oper);break; case FIREBIRD: value = this.firebird.get(oper);break; default: value = this.mysql.get(oper);break; } return value; } }
zzqchy-qaw1
java/src/main/java/quickdb/query/DateQuery.java
Java
lgpl
3,880
package quickdb.query; /** * * @author Diego Sarmentero */ public class SubQuery extends Query{ private Where whereBase; private Query tempQuery; private SubQuery(Where where, String attr, Object obj){ super(null, obj); this.whereBase = where; this.tempQuery = this.whereBase.query; this.whereBase.query = this; this.select = new StringBuilder(this.table + "." + attr); } static SubQuery createSubQuery(Where where, String attr, Class clazz){ Object obj = where.query.reflec.emptyInstance(clazz); SubQuery sub = new SubQuery(where, attr, obj); return sub; } @Override public Where closeFor(){ //hacer algo tipo FIND con addCondition StringBuilder sql = new StringBuilder(); sql.append(" (SELECT " + this.select.toString() + " FROM " + this.from.toString()); if (this.where != null) { sql.append(" WHERE " + this.where.toString()); } if (this.groupby != null) { sql.append(" " + this.groupby.toString()); } if (this.having != null) { sql.append(" " + this.having.toString()); } if (this.order != null) { sql.append(" " + this.order.toString()); } this.whereBase.addSubQueryCondition(sql.toString()+")"); this.whereBase.query = this.tempQuery; return this.whereBase; } }
zzqchy-qaw1
java/src/main/java/quickdb/query/SubQuery.java
Java
lgpl
1,455
package quickdb.modelSupport; import quickdb.annotation.Column; import quickdb.annotation.Properties.TYPES; /** * * @author Diego Sarmentero */ public class PrimitiveCollec { private int id; private int base; @Column(type=TYPES.PRIMITIVE) private Object object; public PrimitiveCollec(){} public PrimitiveCollec(Object o){ this.object = o; } public void setBase(int base) { this.base = base; } public void setId(int id) { this.id = id; } public void setObject(Object object) { this.object = object; } public int getBase() { return base; } public int getId() { return id; } public Object getObject() { return object; } }
zzqchy-qaw1
java/src/main/java/quickdb/modelSupport/PrimitiveCollec.java
Java
lgpl
767
package quickdb.modelSupport; /** * * @author Diego Sarmentero */ public class M2mTable{ private int id; private int base; private int related; public M2mTable(){} public M2mTable(int b, int r){ this.base = b; this.related = r; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getBase() { return base; } public void setBase(int base) { this.base = base; } public int getRelated() { return related; } public void setRelated(int related) { this.related = related; } }
zzqchy-qaw1
java/src/main/java/quickdb/modelSupport/M2mTable.java
Java
lgpl
657
package quickdb.modelSupport; import java.util.ArrayList; import quickdb.annotation.Column; /** * * @author Diego Sarmentero */ public class CacheManager { private int id; @Column(ignore=true) private int cacheType; @Column(ignore=true) private String tableName; @Column(ignore=true) private ArrayList data; public CacheManager() { } public CacheManager(ArrayList data) { this.data = data; } public void setCacheType(int cacheType) { this.cacheType = cacheType; } public void setId(int id) { this.id = id; } public int getCacheType() { return cacheType; } public void setData(ArrayList data) { this.data = data; } public ArrayList getData() { return data; } public int getId() { return id; } public void setTableName(String tableName) { this.tableName = tableName; } public String getTableName() { return tableName; } }
zzqchy-qaw1
java/src/main/java/quickdb/modelSupport/CacheManager.java
Java
lgpl
1,017
package quickdb.util; import quickdb.annotation.Validation; import quickdb.reflection.ReflectionUtilities; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author Diego Sarmentero */ public class Validations { public static boolean isValidField(Object obj, String f, Validation ann, ReflectionUtilities reflec){ Method getter = reflec.obtainGetter(obj.getClass(), f); Object fieldValue = null; try{ fieldValue = getter.invoke(obj, new Object[0]); }catch(Exception e){} boolean value = true; if(ann.maxLength() != -1){ value &= ( String.valueOf(fieldValue).length() <= ann.maxLength() ); } if(ann.conditionMatch().length != 0 && !ann.conditionMatch()[0].equalsIgnoreCase("")){ for(String s : ann.conditionMatch()){ Pattern p = Pattern.compile(s); Matcher m = p.matcher(String.valueOf(fieldValue)); value &= m.matches(); } } if(ann.numeric().length > 1){ double val = Double.parseDouble(String.valueOf(fieldValue)); int[] numeric = ann.numeric(); for(int i = 0; i < numeric.length; i += 2){ value &= Validations.checkCondition(numeric[i], numeric[i+1], val); } } if(ann.date().length > 2){ if(fieldValue instanceof Date){ Date date = (Date) fieldValue; int[] dates = ann.date(); for(int i = 0; i < dates.length; i += 3){ int check = dates[i+2]; int val = 0; switch(dates[i]){ //IMPROVE (erasa deprecated implementation) case Validation.YEAR: val = date.getYear() + 1900;break; case Validation.MONTH: val = date.getMonth() + 1;break; case Validation.DAY: val = date.getDate();break; /*case Validation.HOUR: val = date.getHours();break; case Validation.MINUTE: val = date.getMinutes();break; case Validation.SECOND: val = date.getSeconds();break;*/ } value &= Validations.checkCondition(dates[i+1], check, val); } } } return value; } private static boolean checkCondition(int op, double check, double val){ boolean value = false; switch(op){ case Validation.EQUAL: value = (val == check);break; case Validation.EQUALORGREATER: value = (val >= check);break; case Validation.EQUALORLOWER: value = (val <= check);break; case Validation.GREATER: value = (val > check);break; case Validation.LOWER: value = (val < check);break; } return value; } }
zzqchy-qaw1
java/src/main/java/quickdb/util/Validations.java
Java
lgpl
3,313
package quickdb.annotation; import java.lang.annotation.*; /** * * @author Diego Sarmentero */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Column { String name() default ""; Properties.TYPES type() default Properties.TYPES.PRIMITIVE; String collectionClass() default ""; String getter() default ""; String setter() default ""; boolean ignore() default false; /* * + : SUM * % : AVG * > : MAX * < : MIN * # : COUNT */ String summary() default ""; }
zzqchy-qaw1
java/src/main/java/quickdb/annotation/Column.java
Java
lgpl
559
package quickdb.annotation; import quickdb.db.AdminBase; import java.util.HashMap; /** * * @author Diego Sarmentero */ public class Definition { public enum DATATYPE { BIT, BOOLEAN, SMALLINT, INT, INTEGER, BIGINT, REAL, DOUBLE, FLOAT, DECIMAL, NUMERIC, DATE, TIME, TIMESTAMP, DATETIME, CHAR, VARCHAR, BINARY, VARBINARY, TEXT }; public enum COLUMN_FORMAT { FIXED, DYNAMIC, DEFAULT }; public enum STORAGE { DISK, MEMORY, DEFAULT }; private HashMap<DATATYPE, String> typeValue; private HashMap<COLUMN_FORMAT, String> formatValue; private HashMap<STORAGE, String> storageValue; public Definition(AdminBase.DATABASE db) { this.init(db); } private void init(AdminBase.DATABASE db) { this.typeValue = new HashMap<Definition.DATATYPE, String>(); switch(db){ case POSTGRES: this.typeValue.put(DATATYPE.BIT, "bit"); this.typeValue.put(DATATYPE.BOOLEAN, "boolean"); this.typeValue.put(DATATYPE.SMALLINT, "SMALLINT"); this.typeValue.put(DATATYPE.INT, "integer"); this.typeValue.put(DATATYPE.INTEGER, "integer"); this.typeValue.put(DATATYPE.BIGINT, "bigint"); this.typeValue.put(DATATYPE.REAL, "real"); this.typeValue.put(DATATYPE.DOUBLE, "double precision"); this.typeValue.put(DATATYPE.FLOAT, "real"); this.typeValue.put(DATATYPE.DECIMAL, "decimal"); this.typeValue.put(DATATYPE.NUMERIC, "numeric"); this.typeValue.put(DATATYPE.DATE, "date"); this.typeValue.put(DATATYPE.TIME, "time"); this.typeValue.put(DATATYPE.TIMESTAMP, "timestamp"); this.typeValue.put(DATATYPE.DATETIME, "timestamp"); this.typeValue.put(DATATYPE.CHAR, "character"); this.typeValue.put(DATATYPE.VARCHAR, "character varying"); this.typeValue.put(DATATYPE.BINARY, "bytea"); this.typeValue.put(DATATYPE.VARBINARY, "bit varying"); this.typeValue.put(DATATYPE.TEXT, "text"); break; case FIREBIRD: this.typeValue.put(DATATYPE.BIT, "bit"); this.typeValue.put(DATATYPE.BOOLEAN, "boolean"); this.typeValue.put(DATATYPE.SMALLINT, "smallint"); this.typeValue.put(DATATYPE.INT, "int"); this.typeValue.put(DATATYPE.INTEGER, "integer"); this.typeValue.put(DATATYPE.BIGINT, "bigint"); this.typeValue.put(DATATYPE.REAL, "real"); this.typeValue.put(DATATYPE.DOUBLE, "double precision"); this.typeValue.put(DATATYPE.FLOAT, "float"); this.typeValue.put(DATATYPE.DECIMAL, "decimal"); this.typeValue.put(DATATYPE.NUMERIC, "numeric"); this.typeValue.put(DATATYPE.DATE, "date"); this.typeValue.put(DATATYPE.TIME, "time"); this.typeValue.put(DATATYPE.TIMESTAMP, "timestamp"); this.typeValue.put(DATATYPE.DATETIME, "timestamp"); this.typeValue.put(DATATYPE.CHAR, "char"); this.typeValue.put(DATATYPE.VARCHAR, "varchar"); this.typeValue.put(DATATYPE.TEXT, "nchar"); break; default: this.typeValue.put(DATATYPE.BIT, "BIT"); this.typeValue.put(DATATYPE.BOOLEAN, "TINYINT"); this.typeValue.put(DATATYPE.SMALLINT, "SMALLINT"); this.typeValue.put(DATATYPE.INT, "INT"); this.typeValue.put(DATATYPE.INTEGER, "INTEGER"); this.typeValue.put(DATATYPE.BIGINT, "BIGINT"); this.typeValue.put(DATATYPE.REAL, "REAL"); this.typeValue.put(DATATYPE.DOUBLE, "DOUBLE"); this.typeValue.put(DATATYPE.FLOAT, "FLOAT"); this.typeValue.put(DATATYPE.DECIMAL, "DECIMAL"); this.typeValue.put(DATATYPE.NUMERIC, "NUMERIC"); this.typeValue.put(DATATYPE.DATE, "DATE"); this.typeValue.put(DATATYPE.TIME, "TIME"); this.typeValue.put(DATATYPE.TIMESTAMP, "TIMESTAMP"); this.typeValue.put(DATATYPE.DATETIME, "DATETIME"); this.typeValue.put(DATATYPE.CHAR, "CHAR"); this.typeValue.put(DATATYPE.VARCHAR, "VARCHAR"); this.typeValue.put(DATATYPE.BINARY, "BINARY"); this.typeValue.put(DATATYPE.VARBINARY, "VARBINARY"); this.typeValue.put(DATATYPE.TEXT, "TEXT"); break; } this.formatValue = new HashMap<COLUMN_FORMAT, String>(); this.formatValue.put(COLUMN_FORMAT.DEFAULT, "DEFAULT"); this.formatValue.put(COLUMN_FORMAT.DYNAMIC, "DYNAMIC"); this.formatValue.put(COLUMN_FORMAT.FIXED, "FIXED"); this.storageValue = new HashMap<STORAGE, String>(); this.storageValue.put(STORAGE.DEFAULT, "DEFAULT"); this.storageValue.put(STORAGE.DISK, "DISK"); this.storageValue.put(STORAGE.MEMORY, "MEMORY"); } public String obtainDataType(DATATYPE type) { return this.typeValue.get(type); } public String obtainColumnFormat(COLUMN_FORMAT format) { return this.formatValue.get(format); } public String obtainStorage(STORAGE store) { return this.storageValue.get(store); } }
zzqchy-qaw1
java/src/main/java/quickdb/annotation/Definition.java
Java
lgpl
5,509
package quickdb.annotation; import java.lang.annotation.*; /** * * @author Diego Sarmentero */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Table{ String value() default ""; boolean cache() default false; boolean cacheUpdate() default false; String[] before() default ""; String[] after() default ""; }
zzqchy-qaw1
java/src/main/java/quickdb/annotation/Table.java
Java
lgpl
365
package quickdb.annotation; import java.lang.annotation.*; /** * * @author Diego Sarmentero */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Parent{ }
zzqchy-qaw1
java/src/main/java/quickdb/annotation/Parent.java
Java
lgpl
191
package quickdb.annotation; import java.lang.annotation.*; /** * * @author Diego Sarmentero */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Validation { public static final String conditionURL = "www\\.(.+)\\.(.+)"; //IMPROVE public static final String conditionMail = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Za-z]{2,4}$"; public static final String conditionSecurePassword = "^.*(?=.{8,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(^[a-zA-Z0-9@\\$=!:.#%]+$)"; public static final String conditionNoEmpty = "((\\w)+(\\s)*(\\w)*)+"; public static final int EQUAL = 0; public static final int LOWER = 1; public static final int GREATER = 2; public static final int EQUALORGREATER = 3; public static final int EQUALORLOWER = 4; public static final int YEAR = 0; public static final int MONTH = 1; public static final int DAY = 2; /*public static final int HOUR = 3; public static final int MINUTE = 4; public static final int SECOND = 5;*/ String[] conditionMatch() default ""; int maxLength() default -1; int[] numeric() default 0; int[] date() default 0; }
zzqchy-qaw1
java/src/main/java/quickdb/annotation/Validation.java
Java
lgpl
1,175
package quickdb.annotation; import java.lang.annotation.*; /** * * @author Diego Sarmentero */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ColumnDefinition { Definition.DATATYPE type() default Definition.DATATYPE.VARCHAR; int length() default -1; boolean notNull() default true; String defaultValue() default ""; boolean autoIncrement() default false; boolean unique() default false; boolean primary() default false; Definition.COLUMN_FORMAT format() default Definition.COLUMN_FORMAT.DEFAULT; Definition.STORAGE storage() default Definition.STORAGE.DEFAULT; }
zzqchy-qaw1
java/src/main/java/quickdb/annotation/ColumnDefinition.java
Java
lgpl
646
package quickdb.annotation; /** * * @author Diego Sarmentero */ public class Properties { public static enum TYPES { PRIMITIVE, PRIMARYKEY, FOREIGNKEY, COLLECTION } }
zzqchy-qaw1
java/src/main/java/quickdb/annotation/Properties.java
Java
lgpl
187
package quickdb.reflection; import java.lang.reflect.Method; import quickdb.annotation.Properties; import quickdb.annotation.Properties.TYPES; import quickdb.annotation.Validation; /** * * @author Diego Sarmentero */ public class DictionaryBody { private String fieldName; private String colName; private Method set; private Method get; private Properties.TYPES dataType; private Class collectionClass; private Validation validation; private boolean summary; DictionaryBody() { this.validation = null; } public String colName() { return colName; } public Class collectionClass() { return collectionClass; } public TYPES dataType() { return dataType; } public String fieldName() { return fieldName; } public Method get() { return get; } public Method set() { return set; } public Validation validation() { return validation; } public void setColName(String colName) { this.colName = colName; } public void setCollectionClass(Class collectionClass) { this.collectionClass = collectionClass; } public void setDataType(TYPES dataType) { this.dataType = dataType; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public void setGet(Method get) { this.get = get; } public void setSet(Method set) { this.set = set; } public void setValidation(Validation validation) { this.validation = validation; } public boolean summary() { return summary; } public void setSummary(boolean summary) { this.summary = summary; } }
zzqchy-qaw1
java/src/main/java/quickdb/reflection/DictionaryBody.java
Java
lgpl
1,764
package quickdb.reflection; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.ResultSet; import java.util.ArrayList; import quickdb.annotation.*; import quickdb.db.AdminBase; import quickdb.db.View; import quickdb.db.dbms.mysql.ColumnDefined; import quickdb.db.dbms.postgre.ColumnDefinedPostgre; import quickdb.modelSupport.M2mTable; import quickdb.modelSupport.PrimitiveCollec; import quickdb.util.Validations; import java.lang.reflect.InvocationTargetException; import java.sql.Timestamp; import java.util.Collection; import java.util.Hashtable; import java.util.Stack; import quickdb.exception.DictionaryIncompleteException; import quickdb.modelSupport.CacheManager; /** * * @author Diego Sarmentero */ public class EntityManager { public enum OPERATION { SAVE, MODIFY, DELETE, OBTAIN, OTHER } Stack<String> primaryKey; Stack<Integer> primaryKeyValue; Stack<ArrayList> collection; Stack<Integer> sizeCollection; Stack<String> nameCollection; Stack<Object> originalChild; Stack<String[]> executeAfter; boolean hasParent; boolean dropDown; private ArrayList<String> manyRestore; private Hashtable<String, CacheManager> cacheStore; private ReflectionUtilities ref; private Table action; public EntityManager() { this.ref = new ReflectionUtilities(); this.primaryKey = new Stack<String>(); this.collection = new Stack<ArrayList>(); this.sizeCollection = new Stack<Integer>(); this.dropDown = true; this.nameCollection = new Stack<String>(); this.primaryKeyValue = new Stack<Integer>(); this.originalChild = new Stack<Object>(); this.executeAfter = new Stack<String[]>(); this.hasParent = false; this.manyRestore = new ArrayList<String>(); this.action = null; this.cacheStore = new Hashtable<String, CacheManager>(); } /** * The ArrayList returned contain in the first row the name of the Table * and then contain an String Array (Object[]) in the other rows * representing the name of the field and the data, and finally if exist a * sql statement or an empty string if there isn't a sql statement * @param object to be interpreted depending on his annotations * @return an ArrayList with the structure explained */ public ArrayList entity2Array(AdminBase admin, Object object, OPERATION oper) { EntityDictionary dictionary = new EntityDictionary(); try { if (dictionary.contains(object.getClass().getName())) { return dictionary.entity2Array(admin, this, object, oper); } } catch (DictionaryIncompleteException excep) { } ArrayList array = new ArrayList(); boolean sql = true; boolean ignore = false; String statement = ""; String tableName = this.readClassName(object, true); dictionary.newDictObject(tableName, hasParent, this.action); this.action = null; array.add(tableName); boolean tempParent = this.hasParent; this.hasParent = false; int primKeyItems = this.primaryKey.size(); int sizeCollectionInt = 0; this.primaryKey.push("id"); Field fields[] = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { DictionaryBody body = new DictionaryBody(); Object objs[] = new Object[2]; String field = fields[i].getName(); body.setFieldName(field); objs[0] = field; Annotation ann = null; Annotation annotations[] = fields[i].getAnnotations(); for (Annotation a : annotations) { if (a instanceof Column) { if (((Column) a).name().length() != 0) { objs[0] = ((Column) a).name(); } ignore = ((Column) a).ignore(); ann = a; if (((Column) a).type() == Properties.TYPES.PRIMARYKEY) { this.primaryKey.pop(); primaryKey.push(objs[0].toString()); body.setDataType(Properties.TYPES.PRIMARYKEY); continue; } if(((Column)a).summary().length() != 0){ body.setDataType(Properties.TYPES.PRIMITIVE); Method setter = this.ref.obtainSetter(object.getClass(), field); body.setSet(setter); ignore = true; } } else if (a instanceof Validation) { body.setValidation((Validation) a); if (!Validations.isValidField(object, fields[i].getName(), ((Validation)a), ref)) { return null; } } else { continue; } } body.setColName(objs[0].toString()); if (ignore) { ignore = false; continue; } try { //Assign Data to Array if (sql) { if (oper == OPERATION.MODIFY || oper == OPERATION.DELETE) { String nameSta = this.primaryKey.peek(); Method getSta = this.ref.obtainGetter(object.getClass(), nameSta); Integer valueId = (Integer) getSta.invoke(object, new Object[0]); statement = nameSta + "=" + valueId; } else { statement = this.primaryKey.peek() + " > 0"; } sql = false; } Method getter = this.ref.obtainGetter(object.getClass(), field); Method setter = this.ref.obtainSetter(object.getClass(), field); body.setGet(getter); body.setSet(setter); Object value = getter.invoke(object, new Object[0]); boolean wasNull = false; if (value == null) { wasNull = true; value = this.ref.emptyInstance(getter.getReturnType().getName()); } if (this.ref.implementsCollection(value.getClass(), ann)) { body.setDataType(Properties.TYPES.COLLECTION); admin.setCollection(true); Class clazz = this.ref.obtainItemCollectionType(object.getClass(), field); body.setCollectionClass(clazz); admin.setCollectionHasName(true); this.nameCollection.push(this.ref.readTableName(clazz) + field.substring(0, 1).toUpperCase() + field.substring(1)); if (this.ref.checkPrimitivesExtended(clazz, null)) { Object[] arrayPrimitive = ((Collection) value).toArray(); ArrayList primitiveResult = new ArrayList(); for (Object prim : arrayPrimitive) { PrimitiveCollec primitive = new PrimitiveCollec(prim); primitiveResult.add(primitive); } switch (oper) { case SAVE: case MODIFY: this.collection.push(primitiveResult); sizeCollectionInt++; break; } } else { switch (oper) { case SAVE: this.collection.push(admin.saveAll(((Collection) value))); sizeCollectionInt++; break; case MODIFY: this.collection.push(admin.modifyAll(((Collection) value))); sizeCollectionInt++; break; } } if (sizeCollectionInt == 0) { this.nameCollection.pop(); } admin.setCollectionHasName(false); } else if (!this.ref.checkPrimitivesExtended(value.getClass(), ann)) { body.setDataType(Properties.TYPES.FOREIGNKEY); if (this.dropDown && !wasNull) { boolean tempCollectionValue = admin.getCollection(); admin.setCollection(false); String nameF = this.ref.checkIndex(value.getClass()); Method getF = this.ref.obtainGetter(value.getClass(), nameF); int valueId = (Integer) getF.invoke(value, new Object[0]); switch (oper) { case SAVE: if (valueId == 0) { objs[1] = admin.saveGetIndex(value); } else { objs[1] = valueId; } array.add(objs); break; case MODIFY: if (valueId > 0) { admin.modify(value); objs[1] = valueId; } else { objs[1] = admin.saveGetIndex(value); } array.add(objs); break; } admin.setCollection(tempCollectionValue); } else { objs[1] = -1; array.add(objs); } } else { body.setDataType(Properties.TYPES.PRIMITIVE); objs[1] = value; array.add(objs); } } catch (IllegalAccessException e) { return null; } catch (java.lang.reflect.InvocationTargetException ex) { return null; } dictionary.addData(body); } dictionary.closeDictObject(object.getClass().getName()); if (sizeCollectionInt != 0) { this.sizeCollection.push(sizeCollectionInt); } this.hasParent = tempParent; boolean tempCollec = admin.getCollection(); admin.setCollection(false); if (this.hasParent && ((oper == OPERATION.SAVE) || (oper == OPERATION.MODIFY))) { this.hasParent = false; int index = this.completeParentData(admin, object, oper); array.add(new Object[]{"parent_id", index}); } admin.setCollection(tempCollec); array.add(statement); for (int i = this.primaryKey.size() - 1; i >= primKeyItems; i--) { this.primaryKey.removeElementAt(i); } this.ref.executeAction(this.executeAfter.pop(), object); return array; } public Object result2Object(AdminBase admin, Object object, ResultSet rs) { EntityDictionary dictionary = new EntityDictionary(); try { if (dictionary.contains(object.getClass().toString())) { return dictionary.result2Object(admin, this, object, rs); } } catch (DictionaryIncompleteException excep) { } String table1 = this.readClassName(object, false); dictionary.newDictObject(table1, hasParent, null); boolean tempParent = this.hasParent; this.hasParent = false; boolean searchId = true; if (View.class.isInstance(object)) { searchId = false; this.primaryKeyValue.push(1); } int primKeyItems = this.primaryKey.size(); this.primaryKey.push("id"); boolean ignore = false; Field fields[] = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { DictionaryBody body = new DictionaryBody(); String field = fields[i].getName(); body.setFieldName(field); String name = field; Annotation ann = null; Object value = null; Annotation annotations[] = fields[i].getAnnotations(); try { for (Annotation a : annotations) { if (a instanceof Validation) { body.setValidation((Validation) a); } if (!(a instanceof Column)) { continue; } if (((Column) a).name().length() != 0) { name = ((Column) a).name(); } ann = a; if (((Column) a).type() == Properties.TYPES.PRIMARYKEY) { body.setDataType(Properties.TYPES.PRIMARYKEY); value = rs.getObject(name); this.primaryKeyValue.push((Integer) value); searchId = false; } ignore = ((Column) a).ignore(); if(((Column)a).summary().length() != 0){ body.setDataType(Properties.TYPES.PRIMITIVE); body.setSummary(true); Method setter = this.ref.obtainSetter(object.getClass(), field); body.setSet(setter); try{ value = rs.getDouble(name); setter.invoke(object, new Object[]{value}); }catch(Exception e){} ignore = true; } } body.setColName(name); if (searchId) { searchId = false; value = rs.getObject("id"); this.primaryKeyValue.push((Integer) value); } if (ignore) { ignore = false; continue; } Method setter = this.ref.obtainSetter(object.getClass(), field); Method getter = this.ref.obtainGetter(object.getClass(), field); body.setGet(getter); body.setSet(setter); Object get = getter.invoke(object, new Object[0]); //When the object is not initialized if (get == null) { get = this.ref.emptyInstance(getter.getReturnType().getName()); } if (this.ref.implementsCollection(get.getClass(), ann)) { body.setDataType(Properties.TYPES.COLLECTION); Class clazz2 = this.ref.obtainItemCollectionType(object.getClass(), field); body.setCollectionClass(clazz2); String table2 = this.ref.readTableName(clazz2); String fieldName = field.substring(0, 1).toUpperCase() + field.substring(1); String tempName = table1 + table2 + fieldName; String tempTableName = table2 + table1 + fieldName; String forColumn = "base"; if (!admin.checkTableExist(tempName) && admin.checkTableExist(tempTableName)) { tempName = tempTableName; forColumn = "related"; } this.nameCollection.push(tempName); admin.setCollectionHasName(true); //Supposed that "id" was readed before ArrayList results; if (this.ref.checkPrimitivesExtended(clazz2, null)) { results = admin.obtainAll(PrimitiveCollec.class, forColumn + "=" + this.primaryKeyValue.peek()); int lengthPrimitives = results.size(); for (int q = 0; q < lengthPrimitives; q++) { results.set(q, ((PrimitiveCollec) results.get(q)).getObject()); } } else { results = admin.obtainAll(M2mTable.class, forColumn + "=" + this.primaryKeyValue.peek()); admin.setCollectionHasName(false); results = this.restoreCollection(admin, results, object, name, forColumn, tempName); } Object valueCollection = this.ref.emptyInstance(get.getClass()); ((Collection) valueCollection).addAll(results); admin.setCollectionHasName(false); setter.invoke(object, new Object[]{valueCollection}); dictionary.addData(body); continue; } else { value = rs.getObject(name); } //For Foreign Keys boolean isForeign = !this.ref.checkPrimitivesExtended(get.getClass(), ann); if (this.dropDown && isForeign) { body.setDataType(Properties.TYPES.FOREIGNKEY); Integer index = (Integer) value; String indexName = this.ref.checkIndex(get.getClass()); if (admin.obtainWhere(get, indexName + "=" + index)) { setter.invoke(object, new Object[]{get}); } } else if (!isForeign) { body.setDataType(Properties.TYPES.PRIMITIVE); if (value instanceof Timestamp) { setter.invoke(object, new Object[]{ this.ref.manageTimeData(get.getClass(), ((Timestamp) value))}); } else { setter.invoke(object, new Object[]{value}); } } else { body.setDataType(Properties.TYPES.FOREIGNKEY); } } catch (Exception e) { e.printStackTrace(); return null; } dictionary.addData(body); } dictionary.closeDictObject(object.getClass().getName()); this.hasParent = tempParent; if (this.hasParent) { this.hasParent = false; this.restoreParent(admin, object, rs); } for (int i = this.primaryKey.size() - 1; i >= primKeyItems; i--) { this.primaryKey.removeElementAt(i); this.primaryKeyValue.removeElementAt(i); } return object; } private void restoreParent(AdminBase admin, Object child, ResultSet rs) { Object parent; if ((this.originalChild.size() == 0) || (!this.originalChild.peek().getClass().isInstance(child))) { this.originalChild.push(child); } try { parent = this.ref.emptyInstance(child.getClass().getSuperclass().getName()); String sql = ""; boolean primary = true; Field fields[] = parent.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { String field = fields[i].getName(); String name = field; Annotation annotations[] = fields[i].getAnnotations(); for (Annotation a : annotations) { if (!(a instanceof Column)) { continue; } if (((Column) a).name().length() != 0) { name = ((Column) a).name(); } if (((Column) a).type() == Properties.TYPES.PRIMARYKEY) { sql = name + "=" + rs.getObject("parent_id"); admin.obtainWhere(parent, sql); } } if (sql.length() == 0) { sql = field + "='" + rs.getObject("parent_id") + "'"; admin.obtainWhere(parent, sql); } if (primary) { primary = false; String indexSon = this.ref.checkIndex(child.getClass()); String indexParent = this.ref.checkIndex(parent.getClass()); if (indexSon.equals(indexParent)) { continue; } } Method getter = this.ref.obtainGetter(parent.getClass(), field); Object value = getter.invoke(parent, new Object[0]); Method setter = this.ref.obtainSetter(parent.getClass(), field); if (child.getClass() == this.originalChild.peek().getClass()) { setter.invoke(child, new Object[]{value}); } else { setter.invoke(this.originalChild.peek(), new Object[]{value}); } } } catch (Exception e) { e.printStackTrace(); } finally { if (child.getClass() == this.originalChild.peek().getClass()) { this.originalChild.pop(); } } } public Object[] mappingDefinition(AdminBase admin, Object object) { ArrayList array = new ArrayList(); Definition def = new Definition(admin.getDB()); boolean primary = false; boolean collectionBool; array.add(this.ref.readTableName(object.getClass())); Field fields[] = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Annotation ann[] = fields[i].getAnnotations(); ColumnDefined colDef; switch (admin.getDB()) { case POSTGRES: colDef = new ColumnDefinedPostgre(); break; default: colDef = new ColumnDefined(); break; } String name = fields[i].getName(); collectionBool = false; for (int j = 0; j < ann.length; j++) { if (ann[j] instanceof Column) { if ((((Column) ann[j]).type() == Properties.TYPES.COLLECTION) || ((Column) ann[j]).ignore()) { collectionBool = true; continue; } if (((Column) ann[j]).name().length() != 0) { name = ((Column) ann[j]).name(); } } else if (ann[j] instanceof ColumnDefinition) { colDef.setType(def.obtainDataType( ((ColumnDefinition) ann[j]).type())); colDef.setLength(((ColumnDefinition) ann[j]).length()); colDef.setNotNull(((ColumnDefinition) ann[j]).notNull()); colDef.setDefaultValue( ((ColumnDefinition) ann[j]).defaultValue()); colDef.setAutoIncrement( ((ColumnDefinition) ann[j]).autoIncrement()); colDef.setUnique(((ColumnDefinition) ann[j]).unique()); colDef.setPrimary(((ColumnDefinition) ann[j]).primary()); colDef.setFormat(def.obtainColumnFormat( ((ColumnDefinition) ann[j]).format())); colDef.setStorage(def.obtainStorage( ((ColumnDefinition) ann[j]).storage())); } } colDef.setName(name); if (primary) { array.add(1, colDef); primary = false; } else if (!collectionBool) { array.add(colDef); } } return array.toArray(); } private int completeParentData(AdminBase admin, Object child, OPERATION oper) { Object parent; int index = 0; if ((this.originalChild.size() == 0) || (!child.getClass().isInstance(this.originalChild.peek()))) { this.originalChild.push(child); } try { parent = this.ref.emptyInstance(child.getClass().getSuperclass().getName()); Field fields[] = parent.getClass().getDeclaredFields(); this.primaryKey.push("id"); for (int i = 0; i < fields.length; i++) { String field = fields[i].getName(); Annotation annotations[] = fields[i].getAnnotations(); for (Annotation a : annotations) { if (!(a instanceof Column)) { continue; } if ((((Column) a).name().length() != 0) && (((Column) a).type() == Properties.TYPES.PRIMARYKEY)) { this.primaryKey.pop(); this.primaryKey.push(((Column) a).name()); } } Method getter = this.ref.obtainGetter(parent.getClass(), field); Object value; if (child.getClass() == this.originalChild.peek().getClass()) { value = getter.invoke(child, new Object[0]); } else { value = getter.invoke(this.originalChild.peek(), new Object[0]); } Method setter = this.ref.obtainSetter(parent.getClass(), field); setter.invoke(parent, new Object[]{value}); } if (oper == OPERATION.SAVE) { index = admin.saveGetIndex(parent); } else { if (oper == OPERATION.MODIFY) { admin.modify(parent); } Method getter = this.ref.obtainGetter(parent.getClass(), this.primaryKey.peek()); index = (Integer) getter.invoke(parent, new Object[0]); } } catch (Exception e) { return -1; } finally { if (child.getClass() == this.originalChild.peek().getClass()) { this.originalChild.pop(); } this.primaryKey.pop(); } return index; } private String readClassName(Object object, boolean value) { this.hasParent = false; Annotation entity[] = object.getClass().getAnnotations(); String entityName = object.getClass().getSimpleName(); for (int i = 0; i < entity.length; i++) { if (entity[i] instanceof Table){ if(((Table) entity[i]).value().length() != 0) { entityName = ((Table) entity[i]).value(); } if(value){ this.ref.executeAction(((Table) entity[i]).before(), object); this.executeAfter.push(((Table) entity[i]).after()); this.action = ((Table) entity[i]); } } else if (entity[i] instanceof Parent) { this.hasParent = true; } } if (entity.length == 0){ this.executeAfter.push(new String[]{""}); if(object.getClass().getSuperclass().getPackage() == object.getClass().getPackage()) { this.hasParent = true; } } return entityName; } public boolean isCacheable(Class clazz){ Annotation entity[] = clazz.getAnnotations(); for (int i = 0; i < entity.length; i++) { if (entity[i] instanceof Table){ return ((Table)entity[i]).cache() || ((Table)entity[i]).cacheUpdate(); } } return false; } public ArrayList obtainCache(String sql, AdminBase admin, Class clazz){ if(this.cacheStore.containsKey(clazz.getName() + sql)){ CacheManager cache = this.cacheStore.get(clazz.getName() + sql); switch(cache.getCacheType()){ case 0: return cache.getData(); case 1: CacheManager cacheUpdate = new CacheManager(); admin.setCollectionHasName(true); this.nameCollection.push(cache.getTableName()); admin.obtainWhere(cacheUpdate, "id > 0"); admin.setCollectionHasName(false); if(cacheUpdate.getId() == cache.getId()){ return cache.getData(); } this.cacheStore.remove(clazz.getName() + sql); return admin.obtainAll(clazz, sql); } } return null; } public void makeCacheable(String sql, ArrayList array, Class clazz, AdminBase admin){ CacheManager cache = new CacheManager(array); Annotation entity[] = clazz.getAnnotations(); for (int i = 0; i < entity.length; i++) { if (entity[i] instanceof Table){ if(((Table)entity[i]).cache()){ cache.setCacheType(0); }else if(((Table)entity[i]).cacheUpdate()){ cache.setCacheType(1); cache.setTableName(clazz.getSimpleName() + "CacheUpdate"); admin.setCollectionHasName(true); this.nameCollection.push(cache.getTableName()); admin.obtainWhere(cache, "id > 0"); admin.setCollectionHasName(false); } break; } } this.cacheStore.put(clazz.getName() + sql, cache); } public void updateCache(Class clazz, AdminBase admin){ Annotation entity[] = clazz.getAnnotations(); for (int i = 0; i < entity.length; i++) { if (entity[i] instanceof Table){ if(((Table)entity[i]).cacheUpdate()){ String tableName = clazz.getSimpleName() + "CacheUpdate"; CacheManager cacheUpdate = new CacheManager(); if(admin.checkTableExist(tableName)){ admin.executeQuery("DELETE FROM " + tableName); } admin.setForceTable(true); admin.setTableForcedName(tableName); admin.save(cacheUpdate); admin.setForceTable(false); } break; } } } ArrayList restoreCollection(AdminBase admin, ArrayList items, Object object, String field, String forColumn, String table) { ArrayList results = new ArrayList(); //obtain object type from array Class objCollec = this.ref.obtainItemCollectionType(object.getClass(), field); //Results size (elements related to this object) int size = items.size(); for (int q = 0; q < size; q++) { if (!this.manyRestore.contains(table + "-" + ((M2mTable) items.get(q)).getBase() + "-" + ((M2mTable) items.get(q)).getRelated())) { //Add this object to the ArrayList to avoid repetition this.manyRestore.add(table + "-" + ((M2mTable) items.get(q)).getBase() + "-" + ((M2mTable) items.get(q)).getRelated()); Object objC = this.ref.emptyInstance(objCollec.getName()); int index = ((M2mTable) items.get(q)).getRelated(); if (forColumn.equalsIgnoreCase("related")) { index = ((M2mTable) items.get(q)).getBase(); } String sql = this.ref.checkIndex(objC.getClass()) + "=" + index; admin.obtainWhere(objC, sql); results.add(objC); } } if ((size > 0) && (this.manyRestore.indexOf(table + "-" + ((M2mTable) items.get(0)).getBase() + "-" + ((M2mTable) items.get(0)).getRelated()) == 0)) { this.manyRestore.clear(); } return results; } public boolean completeLazyLoad(AdminBase admin, Object obj) { boolean result = true; Field[] fields = obj.getClass().getDeclaredFields(); try { for (Field f : fields) { String foreign = f.getName(); Annotation ann = null; Annotation annotations[] = f.getAnnotations(); if (annotations.length > 0) { for (Annotation a : annotations) { if ((a instanceof Column) && ((Column) ann).name().length() != 0) { foreign = ((Column) ann).name(); ann = a; } } } Method getter = this.ref.obtainGetter(obj.getClass(), f.getName()); Method setter = this.ref.obtainSetter(obj.getClass(), f.getName()); Object type = this.ref.emptyInstance(getter.getReturnType().getName()); if ((type != null) && !this.ref.checkPrimitivesExtended(type.getClass(), ann)) { Object value = getter.invoke(obj, new Object[0]); if (value == null) { String table1 = this.ref.readTableName(obj.getClass()); String table2 = this.ref.readTableName(type.getClass()); String idName1 = this.ref.checkIndex(obj.getClass()); String idName2 = this.ref.checkIndex(type.getClass()); Method getIdValue = this.ref.obtainGetter(obj.getClass(), idName1); int val = (Integer) getIdValue.invoke(obj, new Object[0]); String sql = "SELECT * FROM " + table1 + ", " + table2 + " WHERE " + table1 + "." + idName1 + " = " + String.valueOf(val) + " AND " + table2 + "." + idName2 + " = " + table1 + "." + foreign; admin.obtainSelect(type, sql); value = type; } else { result = admin.lazyLoad(value); } setter.invoke(obj, new Object[]{value}); } } } catch (Exception e) { result = false; e.printStackTrace(); } return result; } public ArrayList<String[]> getCollectionsTableForDelete(Object obj, AdminBase admin) { ArrayList<String[]> collec = new ArrayList<String[]>(); String tableBase = this.ref.readTableName(obj.getClass()); try { Field fields[] = obj.getClass().getDeclaredFields(); for (Field f : fields) { String tableRelated = ""; Annotation ann = null; Annotation annotations[] = f.getAnnotations(); for (Annotation a : annotations) { if (a instanceof Column) { ann = a; } else { continue; } } Method getter = this.ref.obtainGetter(obj.getClass(), f.getName()); Object value = getter.invoke(obj, new Object[0]); if (value == null) { value = this.ref.emptyInstance(getter.getReturnType().getName()); } if (this.ref.implementsCollection(value.getClass(), ann)) { String col[] = new String[2]; if (tableRelated.length() == 0) { tableRelated = this.ref.readTableName( this.ref.obtainItemCollectionType( obj.getClass(), f.getName())); col[0] = tableBase + tableRelated; col[1] = tableRelated + tableBase; } else { col[0] = tableRelated; col[1] = tableRelated; } collec.add(col); } } } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.printStackTrace(); } return collec; } public boolean deleteMany2Many(AdminBase admin, Object object, ArrayList<String> manys) { boolean value = false; try { admin.getConex().initTransaction(); for (String s : manys) { Field f = object.getClass().getDeclaredField(s); Method getter = this.ref.obtainGetter(object.getClass(), s); Object obj = getter.invoke(object, new Object[0]); Object array[] = ((Collection) obj).toArray(); if (array.length > 0) { String fieldName = s.substring(0, 1).toUpperCase() + s.substring(1); String table1 = this.ref.readTableName(object.getClass()); String table2 = this.ref.readTableName(array[0].getClass()); String relation = table1 + table2 + fieldName; if (!admin.checkTableExist(relation)) { relation = table2 + table1 + fieldName; } for (Object o2 : array) { this.modifyComponents(admin, o2); } } admin.delete(object); String idName = this.ref.checkIndex(object.getClass()); Method setter = this.ref.obtainSetter(object.getClass(), idName); setter.invoke(object, new Object[]{0}); } admin.getConex().confirmTransaction(); value = true; } catch (Exception e) { try { admin.getConex().cancelTransaction(); } catch (Exception ex) { ex.printStackTrace(); } } return value; } private void modifyComponents(AdminBase admin, Object object) { ArrayList<String> manys = this.ref.isMany2Many(object.getClass()); if (!manys.isEmpty()) { this.deleteMany2Many(admin, object, manys); } } public boolean deleteParent(AdminBase admin, Object object) throws Exception { boolean value = false; //Complete Parent Data if (this.ref.hasParent(object.getClass())) { int index = this.completeParentData(admin, object, EntityManager.OPERATION.DELETE); Object parent = this.ref.emptyInstance( object.getClass().getSuperclass().getName()); String idName = this.ref.checkIndex(parent.getClass()); Method setter = this.ref.obtainSetter(parent.getClass(), idName); setter.invoke(parent, new Object[]{index}); admin.delete(parent); value = true; } return value; } public boolean checkOptimisticLock(AdminBase admin, Object object){ boolean value = true; try{ EntityDictionary dictionary = new EntityDictionary(); if (dictionary.contains(object.getClass().getName())) { Object[] data = dictionary.obtainDataOptimisticLock(object); if(data != null){ ResultSet rs = admin.getConex().select("SELECT optimisticLock FROM " + ((String)data[0]) + " WHERE " + ((String)data[1]) + "=" + data[2].toString()); if(rs.next()){ long timestamp = rs.getLong(1); value = ( ((Long)data[3]) == timestamp ); if(value){ ((Method)data[4]).invoke(object, new Object[]{System.currentTimeMillis()}); } } } } }catch(Exception e){ } return value; } public void setDropDown(boolean dropDown) { this.dropDown = dropDown; } public ArrayList getCollection() { return collection.pop(); } public int sizeCollectionStack() { return this.sizeCollection.pop(); } public String getNameCollection() { return this.nameCollection.pop(); } public ReflectionUtilities getRef() { return ref; } public void cleanStack() { this.nameCollection.clear(); this.primaryKey.clear(); this.primaryKeyValue.clear(); } public void cleanCache(){ this.cacheStore = new Hashtable<String, CacheManager>(); } }
zzqchy-qaw1
java/src/main/java/quickdb/reflection/EntityManager.java
Java
lgpl
41,341
package quickdb.reflection; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import quickdb.annotation.Table; import quickdb.db.AdminBase; import quickdb.db.View; import quickdb.exception.DictionaryIncompleteException; import quickdb.modelSupport.M2mTable; import quickdb.modelSupport.PrimitiveCollec; import quickdb.reflection.EntityManager.OPERATION; import quickdb.util.Validations; /** * * @author Diego Sarmentero */ public class EntityDictionary { private static Hashtable<String, DictionaryData> dict = new Hashtable<String, DictionaryData>(); private DictionaryData dictObject; public boolean contains(String key){ return EntityDictionary.dict.containsKey(key); } public void newDictObject(String table, boolean hasParent, Table action){ this.dictObject = new DictionaryData(table, hasParent, action); } public void addData(DictionaryBody body){ this.dictObject.addData(body); } public void closeDictObject(String key){ if(!key.equalsIgnoreCase("quickdb.modelSupport.M2mTable") && !key.equalsIgnoreCase("quickdb.modelSupport.PrimitiveCollec")){ EntityDictionary.dict.put(key, dictObject); } } public Object[] obtainDataOptimisticLock(Object object){ Object[] data = null; try{ DictionaryData dictData = EntityDictionary.dict.get(object.getClass().getName()); for(DictionaryBody body : dictData.getData()){ if(body.fieldName().equalsIgnoreCase("optimisticLock")){ data = new Object[5]; data[0] = dictData.getTableName(); data[1] = dictData.getData().get(0).colName(); data[2] = dictData.getData().get(0).get().invoke(object, new Object[0]); data[3] = body.get().invoke(object, new Object[0]); data[4] = body.set(); } } }catch(Exception e){} return data; } public static void cleanDictionary(){ EntityDictionary.dict = new Hashtable<String, DictionaryData>(); } public ArrayList entity2Array(AdminBase admin, EntityManager manager, Object object, OPERATION oper) { DictionaryData data = EntityDictionary.dict.get(object.getClass().getName()); ArrayList array = new ArrayList(); array.add(data.getTableName()); if(data.getAction() != null){ manager.getRef().executeAction(data.getAction().before(), object); } String statement = ""; manager.hasParent = false; int primKeyItems = manager.primaryKey.size(); int sizeCollectionInt = 0; manager.primaryKey.push(data.getData().get(0).colName()); try{ for(DictionaryBody body : data.getData()){ if(body.summary()) continue; Object objs[] = new Object[2]; objs[0] = body.colName(); if(body.validation() != null){ if (!Validations.isValidField(object, body.fieldName(), body.validation(), manager.getRef())) { return null; } } Object value = body.get().invoke(object, new Object[0]); boolean wasNull = false; if (value == null) { wasNull = true; value = manager.getRef().emptyInstance(body.get().getReturnType().getName()); } switch(body.dataType()){ case COLLECTION: admin.setCollection(true); admin.setCollectionHasName(true); manager.nameCollection.push(manager.getRef().readTableName(body.collectionClass()) + body.fieldName().substring(0, 1).toUpperCase() + body.fieldName().substring(1)); if (manager.getRef().checkPrimitivesExtended(body.collectionClass(), null)) { Object[] arrayPrimitive = ((Collection) value).toArray(); ArrayList primitiveResult = new ArrayList(); for (Object prim : arrayPrimitive) { PrimitiveCollec primitive = new PrimitiveCollec(prim); primitiveResult.add(primitive); } switch (oper) { case SAVE: case MODIFY: manager.collection.push(primitiveResult); sizeCollectionInt++; break; } } else { switch (oper) { case SAVE: manager.collection.push(admin.saveAll(((Collection) value))); sizeCollectionInt++; break; case MODIFY: manager.collection.push(admin.modifyAll(((Collection) value))); sizeCollectionInt++; break; } } if (sizeCollectionInt == 0) { manager.nameCollection.pop(); } admin.setCollectionHasName(false); break; case FOREIGNKEY: if (manager.dropDown && !wasNull) { boolean tempCollectionValue = admin.getCollection(); admin.setCollection(false); if(EntityDictionary.dict.containsKey(value.getClass().getName())){ DictionaryData data2 = EntityDictionary.dict.get(value.getClass().getName()); int valueId = (Integer) data2.getData().get(0).get().invoke(value, new Object[0]); switch (oper) { case SAVE: if (valueId == 0) { objs[1] = admin.saveGetIndex(value); } else { objs[1] = valueId; } array.add(objs); break; case MODIFY: if (valueId > 0) { admin.modify(value); objs[1] = valueId; } else { objs[1] = admin.saveGetIndex(value); } array.add(objs); break; } admin.setCollection(tempCollectionValue); } } else { objs[1] = -1; array.add(objs); } break; case PRIMITIVE: objs[1] = value; array.add(objs); break; } } if (oper == OPERATION.MODIFY || oper == OPERATION.DELETE) { String nameSta = data.getData().get(0).colName(); Integer valueId = (Integer) data.getData().get(0).get().invoke(object, new Object[0]); statement = nameSta + "=" + valueId; } else { statement = manager.primaryKey.peek() + " > 0"; } }catch(Exception e){ throw new DictionaryIncompleteException(); } if (sizeCollectionInt != 0) { manager.sizeCollection.push(sizeCollectionInt); } boolean tempCollec = admin.getCollection(); admin.setCollection(false); if (data.isHasParent() && ((oper == OPERATION.SAVE) || (oper == OPERATION.MODIFY))) { int index = this.completeParentData(admin, manager, object, oper); array.add(new Object[]{"parent_id", index}); } admin.setCollection(tempCollec); array.add(statement); for (int i = manager.primaryKey.size() - 1; i >= primKeyItems; i--) { manager.primaryKey.removeElementAt(i); } if(data.getAction() != null){ manager.getRef().executeAction(data.getAction().after(), object); } return array; } public Object result2Object(AdminBase admin, EntityManager manager, Object object, ResultSet rs) { DictionaryData data = EntityDictionary.dict.get(object.getClass().getName()); ArrayList array = new ArrayList(); array.add(data.getTableName()); manager.hasParent = false; Object value = null; if (View.class.isInstance(object)) { manager.primaryKeyValue.push(1); } int primKeyItems = manager.primaryKey.size(); manager.primaryKey.push(data.getData().get(0).colName()); try{ for(DictionaryBody body : data.getData()){ if(body.summary()){ value = rs.getDouble(body.colName()); body.set().invoke(object, new Object[]{value}); continue; } Object get = body.get().invoke(object, new Object[0]); //When the object is not initialized if (get == null) { get = manager.getRef().emptyInstance(body.get().getReturnType().getName()); } switch(body.dataType()){ case COLLECTION: String table2 = manager.getRef().readTableName(body.collectionClass()); String fieldName = body.fieldName().substring(0, 1).toUpperCase() + body.fieldName().substring(1); String tempName = data.getTableName() + table2 + fieldName; String tempTableName = table2 + data.getTableName() + fieldName; String forColumn = "base"; if (!admin.checkTableExist(tempName) && admin.checkTableExist(tempTableName)) { tempName = tempTableName; forColumn = "related"; } manager.nameCollection.push(tempName); admin.setCollectionHasName(true); //Supposed that "id" was readed before ArrayList results; if (manager.getRef().checkPrimitivesExtended(body.collectionClass(), null)) { results = admin.obtainAll(PrimitiveCollec.class, forColumn + "=" + manager.primaryKeyValue.peek()); int lengthPrimitives = results.size(); for (int q = 0; q < lengthPrimitives; q++) { results.set(q, ((PrimitiveCollec) results.get(q)).getObject()); } } else { results = admin.obtainAll(M2mTable.class, forColumn + "=" + manager.primaryKeyValue.peek()); admin.setCollectionHasName(false); results = manager.restoreCollection(admin, results, object, body.colName(), forColumn, tempName); } Object valueCollection = manager.getRef().emptyInstance(get.getClass()); ((Collection) valueCollection).addAll(results); admin.setCollectionHasName(false); body.set().invoke(object, new Object[]{valueCollection}); break; case FOREIGNKEY: value = rs.getObject(body.colName()); if (manager.dropDown) { Integer index = (Integer) value; if(!this.contains(get.getClass().getName())){ throw new DictionaryIncompleteException(); } String indexName = EntityDictionary.dict.get(get.getClass().getName()). getData().get(0).colName(); if (admin.obtainWhere(get, indexName + "=" + index)) { body.set().invoke(object, new Object[]{get}); } } break; case PRIMITIVE: if (value instanceof Timestamp) { body.set().invoke(object, new Object[]{ manager.getRef().manageTimeData(get.getClass(), ((Timestamp) value))}); } else { body.set().invoke(object, new Object[]{value}); } break; } } }catch(Exception e){ throw new DictionaryIncompleteException(); } if (data.isHasParent()) { this.restoreParent(admin, manager, object, rs); } for (int i = manager.primaryKey.size() - 1; i >= primKeyItems; i--) { manager.primaryKey.removeElementAt(i); manager.primaryKeyValue.removeElementAt(i); } return object; } private int completeParentData(AdminBase admin, EntityManager manager, Object child, OPERATION oper) { Object parent; int index = 0; if ((manager.originalChild.size() == 0) || (!child.getClass().isInstance(manager.originalChild.peek()))) { manager.originalChild.push(child); } try { parent = manager.getRef().emptyInstance(child.getClass().getSuperclass().getName()); if(!this.contains(parent.getClass().getName())){ throw new DictionaryIncompleteException(); } DictionaryData data = EntityDictionary.dict.get(parent.getClass().getName()); manager.primaryKey.push(data.getData().get(0).colName()); for (DictionaryBody body : data.getData()) { Object value; if (child.getClass() == manager.originalChild.peek().getClass()) { value = body.get().invoke(child, new Object[0]); } else { value = body.get().invoke(manager.originalChild.peek(), new Object[0]); } body.set().invoke(parent, new Object[]{value}); } if (oper == OPERATION.SAVE) { index = admin.saveGetIndex(parent); } else { if (oper == OPERATION.MODIFY) { admin.modify(parent); } index = (Integer) data.getData().get(0).get().invoke(parent, new Object[0]); } } catch (Exception e) { return -1; } finally { if (child.getClass() == manager.originalChild.peek().getClass()) { manager.originalChild.pop(); } manager.primaryKey.pop(); } return index; } private void restoreParent(AdminBase admin, EntityManager manager, Object child, ResultSet rs) { Object parent; if ((manager.originalChild.size() == 0) || (!manager.originalChild.peek().getClass().isInstance(child))) { manager.originalChild.push(child); } try { parent = manager.getRef().emptyInstance(child.getClass().getSuperclass().getName()); if(!this.contains(parent.getClass().getName())){ throw new DictionaryIncompleteException(); } DictionaryData data = EntityDictionary.dict.get(parent.getClass().getName()); String sql = data.getData().get(0).colName() + "=" + rs.getObject("parent_id"); admin.obtainWhere(parent, sql); boolean primary = true; for (DictionaryBody body : data.getData()) { if (primary) { primary = false; if (data.getData().get(0).colName().equals( EntityDictionary.dict.get(parent.getClass().getName()). getData().get(0).colName())) { continue; } } Object value = body.get().invoke(parent, new Object[0]); if (child.getClass() == manager.originalChild.peek().getClass()) { body.set().invoke(child, new Object[]{value}); } else { body.set().invoke(manager.originalChild.peek(), new Object[]{value}); } } } catch (Exception e) { e.printStackTrace(); } finally { if (child.getClass() == manager.originalChild.peek().getClass()) { manager.originalChild.pop(); } } } } class DictionaryData{ private String tableName; private boolean hasParent; private Table action; private ArrayList<DictionaryBody> data; public DictionaryData(String tableName, boolean hasParent, Table action) { this.tableName = tableName; this.hasParent = hasParent; this.action = action; this.data = new ArrayList<DictionaryBody>(); } public void addData(DictionaryBody bodyData){ this.data.add(bodyData); } public Table getAction() { return action; } public ArrayList<DictionaryBody> getData() { return data; } public boolean isHasParent() { return hasParent; } public String getTableName() { return tableName; } }
zzqchy-qaw1
java/src/main/java/quickdb/reflection/EntityDictionary.java
Java
lgpl
18,788
package quickdb.reflection; import quickdb.annotation.Column; import quickdb.annotation.Parent; import quickdb.annotation.Properties; import quickdb.annotation.Table; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.Date; import java.util.ArrayList; /** * * @author Diego Sarmentero */ public class ReflectionUtilities { /** * Return an ArrayList containing the name of the fields from this Object * that represent a Many-To-Many Relation with this object. * @param Object to be evalutated * @return ArrayList with String objects */ public ArrayList<String> isMany2Many(Class clazz) { ArrayList<String> manys = new ArrayList<String>(); //Obtain the Table Name from this Object String table1 = this.readTableName(clazz); Field fields[] = clazz.getDeclaredFields(); for (Field f : fields) { Annotation ann = null; //Search if this field has the Column annotation Annotation annotations[] = f.getAnnotations(); for (Annotation a : annotations) { if (a instanceof Column) { ann = a; } } //Create an empty instance from the type of this field Class cla1 = f.getType(); if (this.implementsCollection(cla1, ann)) { Class item = this.obtainItemCollectionType(clazz, f.getName()); Field fields2[] = item.getDeclaredFields(); for (Field f2 : fields2) { Annotation ann2 = null; Annotation annotations2[] = f2.getAnnotations(); for (Annotation a : annotations2) { if (a instanceof Column) { ann2 = a; } } Class cla2 = f2.getType(); if (this.implementsCollection(cla2, ann2)) { //Obtain the collection type from the second collection Class secondItem = this.obtainItemCollectionType(item, f2.getName()); String table2 = this.readTableName(secondItem); if (table1.equalsIgnoreCase(table2)) { manys.add(f.getName()); break; } } } } } return manys; } /** * Return the Table Name representation from this Object * @param Object to be evaluated * @return a String with the Table Name */ public String readTableName(Class clazz) { Annotation entity[] = clazz.getAnnotations(); String entityName = clazz.getSimpleName(); for (int i = 0; i < entity.length; i++) { if ((entity[i] instanceof Table) && ((Table) entity[i]).value().length() != 0) { entityName = ((Table) entity[i]).value(); } } return entityName; } public Class obtainItemCollectionType(Class clazz, String field) { String className = ""; try{ Field f = clazz.getDeclaredField(field); Annotation annotations[] = f.getAnnotations(); for (Annotation a : annotations) { if (a instanceof Column) { className = ((Column) a).collectionClass(); } } }catch(Exception e){} String path = clazz.getName().substring(0, clazz.getName().lastIndexOf(".") + 1); if (className.length() == 0) { className = path + String.valueOf(field.charAt(0)).toUpperCase() + field.substring(1); } else if (!className.contains(".")) { className = path + className; } Class objCollec = this.emptyInstance(className).getClass(); return objCollec; } /** * Return an empty instance of the Object received by parameter or * the Class represented in the String. * @param (An Object) or (a String with the Class name) * @return An empty Object from the specified Class */ public Object emptyInstance(Object object) { Object obj = null; try { Class clazz; if (object instanceof String) { clazz = Class.forName(String.valueOf(object)); } else if(object instanceof Class){ clazz = Class.forName(((Class) object).getName()); }else{ clazz = Class.forName(object.getClass().getName()); } if (this.isInstanceOfDate(clazz)) { obj = this.manageTimeData(clazz, new java.sql.Timestamp(0)); } else { for (java.lang.reflect.Constructor con : clazz.getConstructors()) { if (con.getParameterTypes().length == 0) { obj = con.newInstance(); break; }else if(con.getParameterTypes().length == 1 && con.getParameterTypes()[0] == String.class){ obj = con.newInstance("0"); break; } } } } catch (Exception e) { return null; } return obj; } private boolean isInstanceOfDate(Class clazz) { if (clazz.getName().substring(clazz.getName(). lastIndexOf(".") + 1).matches("Date|Time|Timestamp")) { return true; } return false; } boolean implementsCollection(Class value, Annotation ann) { boolean collec = false; if (ann == null) { for (Class inter : value.getInterfaces()) { if (inter.getName().equalsIgnoreCase("java.util.List") || inter.getName().equalsIgnoreCase("java.util.Collection")) { collec = true; break; } } } else { collec = ((((Column) ann).type() == Properties.TYPES.COLLECTION) || !(((Column) ann).collectionClass().equalsIgnoreCase(""))); } return collec; } public boolean implementsCollection(Class value, String reference) { boolean collec = false; try { Field f = value.getDeclaredField(reference); Annotation[] ann = f.getAnnotations(); if (ann.length == 0) { for (Class inter : f.getType().getInterfaces()) { if (inter.getName().equalsIgnoreCase("java.util.List") || inter.getName().equalsIgnoreCase("java.util.Collection")) { collec = true; break; } } } else { for (Annotation a : ann) { if (a instanceof Column) { collec = (((Column) a).type() == Properties.TYPES.COLLECTION || !((Column) a).collectionClass().equalsIgnoreCase("")); break; } } } } catch (Exception e) { e.printStackTrace(); } return collec; } /** * Return a Method object that represent the getter method for * the specified field in this object * @param Object that contain the field * @param The field to obtain the Getter Method * @return Method Object [java.lang.reflect.Method] */ public Method obtainGetter(Class object, String field) { try { Field f = object.getDeclaredField(field); Annotation ann = null; for (Annotation a : f.getAnnotations()) { if (a instanceof Column) { ann = a; break; } } String getterName = "get" + String.valueOf(field.charAt(0)).toUpperCase() + field.substring(1); if (ann != null && (((Column) ann).getter().length() != 0)) { getterName = ((Column) ann).getter(); } Method getter = object.getMethod(getterName); return getter; } catch (Exception e) { return null; } } /** * Return a Method object that represent the setter method for * the specified field in this object * @param Object that contain the field * @param The field to obtain the Setter Method * @return Method Object [java.lang.reflect.Method] */ public Method obtainSetter(Class object, String field) { try { Field f = object.getDeclaredField(field); Annotation ann = null; for (Annotation a : f.getAnnotations()) { if (a instanceof Column) { ann = a; break; } } String setterName = "set" + String.valueOf(field.charAt(0)).toUpperCase() + field.substring(1); if (ann != null && (((Column) ann).setter().length() != 0)) { setterName = ((Column) ann).setter(); } Method setter = object.getMethod(setterName, f.getType()); return setter; } catch (Exception e) { return null; } } public String checkIndex(Class clazz) { Field fieldsForeign[] = clazz.getDeclaredFields(); for (int q = 0; q < fieldsForeign.length; q++) { Annotation annForeign[] = fieldsForeign[q].getAnnotations(); if (annForeign.length > 0) { for (Annotation ann : annForeign) { if (((Column) ann).type() == Properties.TYPES.PRIMARYKEY) { return fieldsForeign[q].getName(); } } } } return "id"; } public int checkIndexValue(Object object){ int index = 0; try{ Field fields[] = object.getClass().getDeclaredFields(); String field = fields[0].getName(); Method getter = this.obtainGetter(object.getClass(), field); index = (Integer) getter.invoke(object, new Object[0]); }catch(Exception e){} return index; } public boolean checkPrimitivesExtended(Class clazz, Annotation a) { if (a == null) { if (clazz == Integer.class || clazz == Byte.class || clazz == Short.class || clazz == Long.class || clazz == Float.class || clazz == Double.class || clazz == Boolean.class || clazz == String.class || clazz == Date.class) { return true; } } else { if (((Column) a).type() != Properties.TYPES.FOREIGNKEY) { return true; } } return false; } Object manageTimeData(Class value, java.sql.Timestamp time) throws Exception { Object obj = null; try { for (java.lang.reflect.Constructor constructor : value.getConstructors()) { if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].getName().equalsIgnoreCase("long")) { obj = constructor.newInstance(time.getTime()); break; } } } catch (Exception e) { e.printStackTrace(); } return obj; } public boolean hasParent(Class clazz) { boolean value = false; Annotation entity[] = clazz.getAnnotations(); for (int i = 0; i < entity.length; i++) { if (entity[i] instanceof Parent) { value = true; } } if (entity.length == 0 && clazz.getSuperclass().getPackage() == clazz.getPackage()) { value = true; } return value; } public void executeAction(String action[], Object object){ if(action[0].length() != 0){ Object master = object; if(action.length > 1){ if(action[1].contains(".")){ master = this.emptyInstance(action[1]); }else{ String packageName = object.getClass().getPackage().getName(); master = this.emptyInstance(packageName + "." + action[1]); } } try{ if(action.length > 2 && action[2].equalsIgnoreCase("this")){ Method method = master.getClass().getMethod(action[0], new Class[]{object.getClass()}); method.invoke(master, new Object[]{object}); }else{ Method method = master.getClass().getMethod(action[0]); method.invoke(master, new Object[0]); } }catch(Exception e){ e.printStackTrace(); } } } public String columnName(String field, Class clazz){ try{ Field f = clazz.getDeclaredField(field); Annotation[] ann = f.getDeclaredAnnotations(); for(Annotation a : ann){ if(a instanceof Column && ((Column)a).name().length() != 0){ return ((Column)a).name(); } } return f.getName(); }catch(Exception e){ return ""; } } }
zzqchy-qaw1
java/src/main/java/quickdb/reflection/ReflectionUtilities.java
Java
lgpl
13,917
package quickdb.exception; /** * * @author Diego Sarmentero */ public class DictionaryIncompleteException extends RuntimeException{ public DictionaryIncompleteException() { super("Dictionary Incomplete exception"); } public DictionaryIncompleteException(Throwable t) { super("Query malformed exception", t); } }
zzqchy-qaw1
java/src/main/java/quickdb/exception/DictionaryIncompleteException.java
Java
lgpl
351
package quickdb.exception; /** * * @author Diego Sarmentero */ public class OptimisticLockException extends RuntimeException{ public OptimisticLockException() { super("Optimistic Lock Exception, the object has been modified outside this session."); } public OptimisticLockException(Throwable t) { super("Optimistic Lock Exception, the object has been modified outside this session.", t); } }
zzqchy-qaw1
java/src/main/java/quickdb/exception/OptimisticLockException.java
Java
lgpl
431
package quickdb.exception; /** * * @author Diego Sarmentero */ public class ConnectionException extends Exception { public ConnectionException(String msg) { super(msg); } public ConnectionException(String msg, Throwable t) { super(msg, t); } }
zzqchy-qaw1
java/src/main/java/quickdb/exception/ConnectionException.java
Java
lgpl
281
package quickdb.exception; /** * * @author Diego Sarmentero */ public class LoggerException extends RuntimeException{ public LoggerException() { super("Logger exception, Logger could not be initialized"); } public LoggerException(Throwable t) { super("Logger exception, Logger could not be initialized", t); } }
zzqchy-qaw1
java/src/main/java/quickdb/exception/LoggerException.java
Java
lgpl
351
package quickdb.exception; /** * * @author Diego Sarmentero */ public class SubQueryException extends RuntimeException{ public SubQueryException() { super("For was expected"); } public SubQueryException(String s){ super(s); } public SubQueryException(Throwable t) { super("For was expected", t); } }
zzqchy-qaw1
java/src/main/java/quickdb/exception/SubQueryException.java
Java
lgpl
356
package quickdb.exception; /** * * @author Diego Sarmentero */ public class InvalidParametersException extends RuntimeException{ public InvalidParametersException() { super("Invalid Parameters exception"); } public InvalidParametersException(Throwable t) { super("Invalid Parameters exception", t); } }
zzqchy-qaw1
java/src/main/java/quickdb/exception/InvalidParametersException.java
Java
lgpl
343
package quickdb.exception; /** * * @author Diego Sarmentero */ public class QueryException extends RuntimeException{ public QueryException() { super("Query malformed exception"); } public QueryException(Throwable t) { super("Query malformed exception", t); } }
zzqchy-qaw1
java/src/main/java/quickdb/exception/QueryException.java
Java
lgpl
300
package quickdb.exception; /** * * @author Diego Sarmentero */ public class SubQueryCloseException extends RuntimeException{ public SubQueryCloseException() { super("SubQuery For closed without being initialized"); } public SubQueryCloseException(Throwable t) { super("SubQuery For closed without being initialized", t); } }
zzqchy-qaw1
java/src/main/java/quickdb/exception/SubQueryCloseException.java
Java
lgpl
364
using System; namespace cat.quickdb.db { public class AdminBase { public AdminBase() { } } }
zzqchy-qaw1
csharp/quickdb/db/AdminBase.cs
C#
lgpl
110
using System; namespace cat.quickdb.attribute { [AttributeUsage(AttributeTargets.Field)] public class ParentAttribute : Attribute { } }
zzqchy-qaw1
csharp/quickdb/attribute/ParentAttribute.cs
C#
lgpl
143
using System; namespace cat.quickdb.attribute { [AttributeUsage(AttributeTargets.Property)] public class ColumnAttribute : Attribute { private string name; private Properties.TYPES type; private string getter; private string setter; private string table; private string collectionClass; private bool ignore; public ColumnAttribute() { this.name = ""; this.type = Properties.TYPES.PRIMITIVE; this.getter = ""; this.setter = ""; this.table = ""; this.collectionClass = ""; this.ignore = false; } public string Name { get { return this.name; } set { this.name = value; } } public Properties.TYPES Type { get { return this.type; } set { this.type = value; } } public string Getter { get { return this.getter; } set { this.getter = value; } } public string Setter { get { return this.setter; } set { this.setter = value; } } public string Table { get { return this.table; } set { this.table = value; } } public bool Ignore { get{return this.ignore;} set{this.ignore = value;} } public string CollectionClass { get{return this.collectionClass;} set{this.collectionClass = value;} } } }
zzqchy-qaw1
csharp/quickdb/attribute/ColumnAttribute.cs
C#
lgpl
1,340
using System; namespace cat.quickdb.attribute { [AttributeUsage(AttributeTargets.Field)] public class ColumnDefinitionAttribute : Attribute { private Definition.DATATYPE type; private int length; private bool notNull; private string defaultValue; private bool autoIncrement; private bool unique; private bool primary; private Definition.COLUMN_FORMAT format; private Definition.STORAGE storage; public ColumnDefinitionAttribute() { this.type = Definition.DATATYPE.VARCHAR; this.length = -1; this.notNull = true; this.defaultValue = ""; this.autoIncrement = false; this.unique = false; this.primary = false; this.format = Definition.COLUMN_FORMAT.DEFAULT; this.storage = Definition.STORAGE.DEFAULT; } public Definition.DATATYPE Type { get{return this.type;} set{this.type = value;} } public int Length { get{return this.length;} set{this.length = value;} } public bool NotNull { get{return this.notNull;} set{this.notNull = value;} } public string DefaultValue { get{return this.defaultValue;} set{this.defaultValue = value;} } public bool AutoIncrement { get{return this.autoIncrement;} set{this.autoIncrement = value;} } public bool Unique { get{return this.unique;} set{this.unique = value;} } public bool Primary { get{return this.primary;} set{this.primary = value;} } public Definition.COLUMN_FORMAT Format { get{return this.format;} set{this.format = value;} } public Definition.STORAGE Storage { get{return this.storage;} set{this.storage = value;} } } }
zzqchy-qaw1
csharp/quickdb/attribute/ColumnDefinitionAttribute.cs
C#
lgpl
1,662
using System; using System.Collections; namespace cat.quickdb.attribute { public class Definition { public enum DATATYPE { BIT, TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT, REAL, DOUBLE, FLOAT, DECIMAL, NUMERIC, DATE, TIME, TIMESTAMP, DATETIME, YEAR, CHAR, VARCHAR, BINARY, VARBINARY, TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB, TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT, ENUM, SET }; public enum COLUMN_FORMAT { FIXED, DYNAMIC, DEFAULT }; public enum STORAGE { DISK, MEMORY, DEFAULT }; private Hashtable typeValue; private Hashtable formatValue; private Hashtable storageValue; public Definition() { this.init(); } private void init() { this.typeValue = new Hashtable(); this.typeValue.Add(DATATYPE.BIT, "BIT"); this.typeValue.Add(DATATYPE.TINYINT, "TINYINT"); this.typeValue.Add(DATATYPE.SMALLINT, "SMALLINT"); this.typeValue.Add(DATATYPE.MEDIUMINT, "MEDIUMINT"); this.typeValue.Add(DATATYPE.INT, "INT"); this.typeValue.Add(DATATYPE.INTEGER, "INTEGER"); this.typeValue.Add(DATATYPE.BIGINT, "BIGINT"); this.typeValue.Add(DATATYPE.REAL, "REAL"); this.typeValue.Add(DATATYPE.DOUBLE, "DOUBLE"); this.typeValue.Add(DATATYPE.FLOAT, "FLOAT"); this.typeValue.Add(DATATYPE.DECIMAL, "DECIMAL"); this.typeValue.Add(DATATYPE.NUMERIC, "NUMERIC"); this.typeValue.Add(DATATYPE.DATE, "DATE"); this.typeValue.Add(DATATYPE.TIME, "TIME"); this.typeValue.Add(DATATYPE.TIMESTAMP, "TIMESTAMP"); this.typeValue.Add(DATATYPE.DATETIME, "DATETIME"); this.typeValue.Add(DATATYPE.YEAR, "YEAR"); this.typeValue.Add(DATATYPE.CHAR, "CHAR"); this.typeValue.Add(DATATYPE.VARCHAR, "VARCHAR"); this.typeValue.Add(DATATYPE.BINARY, "BINARY"); this.typeValue.Add(DATATYPE.VARBINARY, "VARBINARY"); this.typeValue.Add(DATATYPE.TINYBLOB, "TINYBLOB"); this.typeValue.Add(DATATYPE.BLOB, "BLOB"); this.typeValue.Add(DATATYPE.MEDIUMBLOB, "MEDIUMBLOB"); this.typeValue.Add(DATATYPE.LONGBLOB, "LONGBLOB"); this.typeValue.Add(DATATYPE.TINYTEXT, "TINYTEXT"); this.typeValue.Add(DATATYPE.TEXT, "TEXT"); this.typeValue.Add(DATATYPE.MEDIUMTEXT, "MEDIUMTEXT"); this.typeValue.Add(DATATYPE.LONGTEXT, "LONGTEXT"); this.typeValue.Add(DATATYPE.ENUM, "ENUM"); this.typeValue.Add(DATATYPE.SET, "SET"); this.formatValue = new Hashtable(); this.formatValue.Add(COLUMN_FORMAT.DEFAULT, "DEFAULT"); this.formatValue.Add(COLUMN_FORMAT.DYNAMIC, "DYNAMIC"); this.formatValue.Add(COLUMN_FORMAT.FIXED, "FIXED"); this.storageValue = new Hashtable(); this.storageValue.Add(STORAGE.DEFAULT, "DEFAULT"); this.storageValue.Add(STORAGE.DISK, "DISK"); this.storageValue.Add(STORAGE.MEMORY, "MEMORY"); } public String obtainDataType(DATATYPE type) { return this.typeValue[type].ToString(); } public String obtainColumnFormat(COLUMN_FORMAT format) { return this.formatValue[format].ToString(); } public String obtainStorage(STORAGE store) { return this.storageValue[store].ToString(); } } }
zzqchy-qaw1
csharp/quickdb/attribute/Definition.cs
C#
lgpl
3,363
using System; namespace cat.quickdb.attribute { [AttributeUsage(AttributeTargets.Field)] public class TableAttribute : Attribute { private string name; private bool cache; private bool cacheUpdate; private string[] before; private string[] after; public TableAttribute(){} public string Name { get{return this.name;} set{this.name = value;} } } }
zzqchy-qaw1
csharp/quickdb/attribute/TableAttribute.cs
C#
lgpl
384
using System; namespace cat.quickdb.attribute { public class Properties { public enum TYPES { PRIMITIVE, PRIMARYKEY, FOREIGNKEY, COLLECTION } } }
zzqchy-qaw1
csharp/quickdb/attribute/Properties.cs
C#
lgpl
170
using System; using System.Runtime.Remoting; using System.Reflection; using System.Collections; using System.Collections.Generic; using cat.quickdb.attribute; namespace cat.quickdb.reflection { public class ReflectionUtilities { public ReflectionUtilities() { } public List<string> isMany2Many(object obj) { List<string> manys = new List<string>(); //Obtain the Table Name from this Object string table1 = this.readTableName(obj); PropertyInfo[] properties = obj.GetType().GetProperties(); foreach(PropertyInfo prop in properties) { Attribute att = null; //Search if this field has the Column annotation Attribute[] attributes = (Attribute[]) prop.GetCustomAttributes(false); foreach(Attribute a in attributes) { if(a is ColumnAttribute) { att = a; } } //Create an empty instance from the type of this field object result = this.emptyInstance(prop.PropertyType); if((result != null) && this.implementsCollection(obj, att)) { } } return manys; } object obtainItemCollectionType(ICollection array, object obj, string field) { string className = ""; object objCollec; if(array.Count != 0) { object[] objects = new object[array.Count]; array.CopyTo(objects, 0); objCollec = objects[0]; } else { PropertyInfo prop = obj.GetType().GetProperty(field); Attribute[] attributes = (Attribute[]) prop.GetCustomAttributes(false); foreach(Attribute a in attributes) { if(a is ColumnAttribute) { className = ((ColumnAttribute) a).CollectionClass; } } string path = obj.GetType().Namespace; if(className.Length == 0) { className = path + prop.Name; } else if(className.Contains(".")) { className = path + className; } objCollec = this.emptyInstance(className, obj.GetType()); } return objCollec; } public string readTableName(object obj) { Attribute[] attributes = (Attribute[]) obj.GetType().GetCustomAttributes(false); string entityName = obj.GetType().Name; for(int i = 0; i < attributes.Length; i++) { if((attributes[i] is TableAttribute) && (((TableAttribute) attributes[i]).Name.Length != 0)) { entityName = ((TableAttribute) attributes[i]).Name; } } return entityName; } public object emptyInstance(params object[] type) { object result = null; try { if(this.isInstanceOfDate(type[0].GetType())) { result = DateTime.Now; } else if(type.Length == 1) { result = Activator.CreateInstance(((Type) type[0])); } else { result = Activator.CreateInstance(((Type)type[1]).GetType().Assembly.FullName, type[0].ToString()); } } catch(Exception e) { return null; } return result; } private bool isInstanceOfDate(Type t) { if(t.IsInstanceOfType(DateTime.Now)) { return true; } return false; } bool implementsCollection(object obj, Attribute att) { bool collec = false; if(att == null) { if((obj.GetType().GetInterface("IList") != null) || (obj.GetType().GetInterface("ICollection") != null)) { collec = true; } } else { collec = (((ColumnAttribute) att).Type == Properties.TYPES.COLLECTION); } return collec; } } }
zzqchy-qaw1
csharp/quickdb/reflection/ReflectionUtilities.cs
C#
lgpl
3,428
using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using cat.quickdb.db; using cat.quickdb.attribute; namespace cat.quickdb.reflection { public class EntityManager { public enum OPERATION { SAVE, MODIFY, DELETE, OBTAIN, OTHER } private Stack<string> primaryKey; private Stack<int> primaryKeyValue; private Stack<ArrayList> collection; private Stack<string> nameCollection; private List<string> manyRestore; private bool dropDown; private bool hasParent; private Object originalChild; private int inheritance; private ReflectionUtilities reflec; public EntityManager() { this.reflec = new ReflectionUtilities(); this.primaryKey = new Stack<string>(); this.collection = new Stack<ArrayList>(); this.dropDown = true; this.nameCollection = new Stack<string>(); this.primaryKeyValue = new Stack<int>(); this.hasParent = false; this.inheritance = 0; this.manyRestore = new List<string>(); } /// <summary> /// The ArrayList returned contain in the firste row the name of the Table /// and then contain an String Array (Object[]) in the other rows /// representing the name of the field and the data, and finally if exist a /// sql statement or an empty string if there isn't a sql statement /// </summary> /// <param name="admin"> /// A <see cref="AdminBase"/> /// </param> /// <param name="obj"> /// A <see cref="System.Object"/> /// </param> /// <param name="oper"> /// A <see cref="OPERATION"/> /// </param> /// <returns> /// A <see cref="ArrayList"/> /// </returns> public ArrayList entity2Array(AdminBase admin, object obj, OPERATION oper) { ArrayList array = new ArrayList(); bool sql = true; bool ignore = false; string statement = ""; array.Add(this.readClassName(obj)); bool tempParent = this.hasParent; this.hasParent = false; this.primaryKey.Push("id"); PropertyInfo[] properties = obj.GetType().GetProperties(); for(int i = 0; i < properties.Length; i++) { object[] objs = new object[2]; string field = properties[i].Name; objs[0] = field; Attribute att = null; Attribute[] attributes = (Attribute[]) properties[i].GetCustomAttributes(false); foreach(Attribute a in attributes) { if(a is ColumnAttribute) { if(((ColumnAttribute) a).Name.Length != 0) { objs[0] = ((ColumnAttribute) a).Name; } ignore = ((ColumnAttribute) a).Ignore; att = a; if(((ColumnAttribute) a).Type == Properties.TYPES.PRIMARYKEY) { this.primaryKey.Pop(); this.primaryKey.Push(objs[0].ToString()); continue; } } else { continue; } } if(ignore) { ignore = false; continue; } if(sql) { if(oper == OPERATION.MODIFY || oper == OPERATION.DELETE) { string nameF = this.primaryKey.Peek(); int valueId = (int) properties[i].GetValue(obj, new object[0]); statement = nameF + "=" + valueId; } else { statement = this.primaryKey.Peek() + " > 0"; } sql = false; } object result = properties[i].GetValue(obj, new object[0]); } return array; } private string readClassName(object obj) { this.hasParent = false; Attribute[] entity = Attribute.GetCustomAttributes(obj.GetType()); string entityName = obj.GetType().Name; for(int i = 0; i < entity.Length; i++) { if((entity[i] is TableAttribute) && (((TableAttribute) entity[i]).Name.Length != 0)) { entityName = ((TableAttribute) entity[i]).Name; } else if(entity[i] is ParentAttribute) { this.hasParent = true; } } if((entity.Length == 0) && (obj.GetType().BaseType.Namespace == obj.GetType().Namespace)) { this.hasParent = true; } return entityName; } } }
zzqchy-qaw1
csharp/quickdb/reflection/EntityManager.cs
C#
lgpl
3,972
using System; namespace cat.quickdb.exception { public class ConnectionException : Exception { public ConnectionException() : base(){} public ConnectionException(string message) : base(message){} } }
zzqchy-qaw1
csharp/quickdb/exception/ConnectionException.cs
C#
lgpl
217
using System; namespace cat.quickdb.exception { public class QueryException : Exception { public QueryException() : base(){} public QueryException(string message) : base(message){} } }
zzqchy-qaw1
csharp/quickdb/exception/QueryException.cs
C#
lgpl
201
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("quickdb")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")]
zzqchy-qaw1
csharp/quickdb/AssemblyInfo.cs
C#
lgpl
968
# NSIS file to create a self-installing exe for Vim. # It requires NSIS version 2.0 or later. # Last Change: 2010 Jul 30 # WARNING: if you make changes to this script, look out for $0 to be valid, # because uninstall deletes most files in $0. # Location of gvim_ole.exe, vimd32.exe, GvimExt/*, etc. !define VIMSRC "..\src" # Location of runtime files !define VIMRT ".." # Location of extra tools: diff.exe !define VIMTOOLS ..\.. # Comment the next line if you don't have UPX. # Get it at http://upx.sourceforge.net !define HAVE_UPX # comment the next line if you do not want to add Native Language Support !define HAVE_NLS !define VER_MAJOR 7 !define VER_MINOR 3 # ----------- No configurable settings below this line ----------- !include UpgradeDLL.nsh # for VisVim.dll !include LogicLib.nsh !include x64.nsh Name "Vim ${VER_MAJOR}.${VER_MINOR}" OutFile gvim${VER_MAJOR}${VER_MINOR}.exe CRCCheck force SetCompressor lzma SetDatablockOptimize on RequestExecutionLevel highest ComponentText "This will install Vim ${VER_MAJOR}.${VER_MINOR} on your computer." DirText "Choose a directory to install Vim (must end in 'vim')" Icon icons\vim_16c.ico # NSIS2 uses a different strategy with six diferent images in a strip... #EnabledBitmap icons\enabled.bmp #DisabledBitmap icons\disabled.bmp UninstallText "This will uninstall Vim ${VER_MAJOR}.${VER_MINOR} from your system." UninstallIcon icons\vim_uninst_16c.ico # On NSIS 2 using the BGGradient causes trouble on Windows 98, in combination # with the BringToFront. # BGGradient 004000 008200 FFFFFF LicenseText "You should read the following before installing:" LicenseData ${VIMRT}\doc\uganda.nsis.txt !ifdef HAVE_UPX !packhdr temp.dat "upx --best --compress-icons=1 temp.dat" !endif # This adds '\vim' to the user choice automagically. The actual value is # obtained below with ReadINIStr. InstallDir "$PROGRAMFILES\Vim" # Types of installs we can perform: InstType Typical InstType Minimal InstType Full SilentInstall normal # These are the pages we use Page license Page components Page directory "" "" CheckInstallDir Page instfiles UninstPage uninstConfirm UninstPage instfiles ########################################################## # Functions Function .onInit MessageBox MB_YESNO|MB_ICONQUESTION \ "This will install Vim ${VER_MAJOR}.${VER_MINOR} on your computer.$\n Continue?" \ IDYES NoAbort Abort ; causes installer to quit. NoAbort: # run the install program to check for already installed versions SetOutPath $TEMP File /oname=install.exe ${VIMSRC}\installw32.exe ExecWait "$TEMP\install.exe -uninstall-check" Delete $TEMP\install.exe # We may have been put to the background when uninstall did something. BringToFront # Install will have created a file for us that contains the directory where # we should install. This is $VIM if it's set. This appears to be the only # way to get the value of $VIM here!? ReadINIStr $INSTDIR $TEMP\vimini.ini vimini dir Delete $TEMP\vimini.ini # If ReadINIStr failed or did not find a path: use the default dir. StrCmp $INSTDIR "" 0 IniOK StrCpy $INSTDIR "$PROGRAMFILES\Vim" IniOK: # Should check for the value of $VIM and use it. Unfortunately I don't know # how to obtain the value of $VIM # IfFileExists "$VIM" 0 No_Vim # StrCpy $INSTDIR "$VIM" # No_Vim: # User variables: # $0 - holds the directory the executables are installed to # $1 - holds the parameters to be passed to install.exe. Starts with OLE # registration (since a non-OLE gvim will not complain, and we want to # always register an OLE gvim). # $2 - holds the names to create batch files for StrCpy $0 "$INSTDIR\vim${VER_MAJOR}${VER_MINOR}" StrCpy $1 "-register-OLE" StrCpy $2 "gvim evim gview gvimdiff vimtutor" FunctionEnd Function .onUserAbort MessageBox MB_YESNO|MB_ICONQUESTION "Abort install?" IDYES NoCancelAbort Abort ; causes installer to not quit. NoCancelAbort: FunctionEnd # We only accept the directory if it ends in "vim". Using .onVerifyInstDir has # the disadvantage that the browse dialog is difficult to use. Function CheckInstallDir StrCpy $0 $INSTDIR 3 -3 StrCmp $0 "vim" PathGood MessageBox MB_OK "The path must end in 'vim'." Abort PathGood: FunctionEnd Function .onInstSuccess WriteUninstaller vim${VER_MAJOR}${VER_MINOR}\uninstall-gui.exe MessageBox MB_YESNO|MB_ICONQUESTION \ "The installation process has been successful. Happy Vimming! \ $\n$\n Do you want to see the README file now?" IDNO NoReadme Exec '$0\gvim.exe -R "$0\README.txt"' NoReadme: FunctionEnd Function .onInstFailed MessageBox MB_OK|MB_ICONEXCLAMATION "Installation failed. Better luck next time." FunctionEnd Function un.onUnInstSuccess MessageBox MB_OK|MB_ICONINFORMATION \ "Vim ${VER_MAJOR}.${VER_MINOR} has been (partly) removed from your system" FunctionEnd Function un.GetParent Exch $0 ; old $0 is on top of stack Push $1 Push $2 StrCpy $1 -1 loop: StrCpy $2 $0 1 $1 StrCmp $2 "" exit StrCmp $2 "\" exit IntOp $1 $1 - 1 Goto loop exit: StrCpy $0 $0 $1 Pop $2 Pop $1 Exch $0 ; put $0 on top of stack, restore $0 to original value FunctionEnd ########################################################## Section "Vim executables and runtime files" SectionIn 1 2 3 # we need also this here if the user changes the instdir StrCpy $0 "$INSTDIR\vim${VER_MAJOR}${VER_MINOR}" SetOutPath $0 File /oname=gvim.exe ${VIMSRC}\gvim_ole.exe File /oname=install.exe ${VIMSRC}\installw32.exe File /oname=uninstal.exe ${VIMSRC}\uninstalw32.exe File ${VIMSRC}\vimrun.exe File /oname=xxd.exe ${VIMSRC}\xxdw32.exe File ${VIMTOOLS}\diff.exe File ${VIMRT}\vimtutor.bat File ${VIMRT}\README.txt File ..\uninstal.txt File ${VIMRT}\*.vim File ${VIMRT}\rgb.txt SetOutPath $0\colors File ${VIMRT}\colors\*.* SetOutPath $0\compiler File ${VIMRT}\compiler\*.* SetOutPath $0\doc File ${VIMRT}\doc\*.txt File ${VIMRT}\doc\tags SetOutPath $0\ftplugin File ${VIMRT}\ftplugin\*.* SetOutPath $0\indent File ${VIMRT}\indent\*.* SetOutPath $0\macros File ${VIMRT}\macros\*.* SetOutPath $0\plugin File ${VIMRT}\plugin\*.* SetOutPath $0\autoload File ${VIMRT}\autoload\*.* SetOutPath $0\autoload\xml File ${VIMRT}\autoload\xml\*.* SetOutPath $0\syntax File ${VIMRT}\syntax\*.* SetOutPath $0\spell File ${VIMRT}\spell\*.txt File ${VIMRT}\spell\*.vim File ${VIMRT}\spell\*.spl File ${VIMRT}\spell\*.sug SetOutPath $0\tools File ${VIMRT}\tools\*.* SetOutPath $0\tutor File ${VIMRT}\tutor\*.* SectionEnd ########################################################## Section "Vim console program (vim.exe)" SectionIn 1 3 SetOutPath $0 ReadRegStr $R0 HKLM \ "SOFTWARE\Microsoft\Windows NT\CurrentVersion" CurrentVersion IfErrors 0 lbl_winnt # Windows 95/98/ME File /oname=vim.exe ${VIMSRC}\vimd32.exe Goto lbl_done lbl_winnt: # Windows NT/2000/XT File /oname=vim.exe ${VIMSRC}\vimw32.exe lbl_done: StrCpy $2 "$2 vim view vimdiff" SectionEnd ########################################################## Section "Create .bat files for command line use" SectionIn 3 StrCpy $1 "$1 -create-batfiles $2" SectionEnd ########################################################## Section "Create icons on the Desktop" SectionIn 1 3 StrCpy $1 "$1 -install-icons" SectionEnd ########################################################## Section "Add Vim to the Start Menu" SectionIn 1 3 StrCpy $1 "$1 -add-start-menu" SectionEnd ########################################################## Section "Add an Edit-with-Vim context menu entry" SectionIn 1 3 # Be aware of this sequence of events: # - user uninstalls Vim, gvimext.dll can't be removed (it's in use) and # is scheduled to be removed at next reboot. # - user installs Vim in same directory, gvimext.dll still exists. # If we now skip installing gvimext.dll, it will disappear at the next # reboot. Thus when copying gvimext.dll fails always schedule it to be # installed at the next reboot. Can't use UpgradeDLL! # We don't ask the user to reboot, the old dll will keep on working. SetOutPath $0 ClearErrors SetOverwrite try ${If} ${RunningX64} File /oname=gvimext.dll ${VIMSRC}\GvimExt\gvimext64.dll ${Else} File /oname=gvimext.dll ${VIMSRC}\GvimExt\gvimext.dll ${EndIf} IfErrors 0 GvimExtDone # Can't copy gvimext.dll, create it under another name and rename it on # next reboot. GetTempFileName $3 $0 ${If} ${RunningX64} File /oname=$3 ${VIMSRC}\GvimExt\gvimext64.dll ${Else} File /oname=$3 ${VIMSRC}\GvimExt\gvimext.dll ${EndIf} Rename /REBOOTOK $3 $0\gvimext.dll GvimExtDone: SetOverwrite lastused # We don't have a separate entry for the "Open With..." menu, assume # the user wants either both or none. StrCpy $1 "$1 -install-popup -install-openwith" SectionEnd ########################################################## Section "Create a _vimrc if it doesn't exist" SectionIn 1 3 StrCpy $1 "$1 -create-vimrc" SectionEnd ########################################################## Section "Create plugin directories in HOME or VIM" SectionIn 1 3 StrCpy $1 "$1 -create-directories home" SectionEnd ########################################################## Section "Create plugin directories in VIM" SectionIn 3 StrCpy $1 "$1 -create-directories vim" SectionEnd ########################################################## Section "VisVim Extension for MS Visual Studio" SectionIn 3 SetOutPath $0 !insertmacro UpgradeDLL "${VIMSRC}\VisVim\VisVim.dll" "$0\VisVim.dll" "$0" File ${VIMSRC}\VisVim\README_VisVim.txt SectionEnd ########################################################## !ifdef HAVE_NLS Section "Native Language Support" SectionIn 1 3 SetOutPath $0\lang File /r ${VIMRT}\lang\*.* SetOutPath $0\keymap File ${VIMRT}\keymap\README.txt File ${VIMRT}\keymap\*.vim SetOutPath $0 File ${VIMRT}\libintl.dll SectionEnd !endif ########################################################## Section -call_install_exe SetOutPath $0 ExecWait "$0\install.exe $1" SectionEnd ########################################################## Section -post BringToFront SectionEnd ########################################################## Section Uninstall # Apparently $INSTDIR is set to the directory where the uninstaller is # created. Thus the "vim61" directory is included in it. StrCpy $0 "$INSTDIR" # If VisVim was installed, unregister the DLL. IfFileExists "$0\VisVim.dll" Has_VisVim No_VisVim Has_VisVim: ExecWait "regsvr32.exe /u /s $0\VisVim.dll" No_VisVim: # delete the context menu entry and batch files ExecWait "$0\uninstal.exe -nsis" # We may have been put to the background when uninstall did something. BringToFront # ask the user if the Vim version dir must be removed MessageBox MB_YESNO|MB_ICONQUESTION \ "Would you like to delete $0?$\n \ $\nIt contains the Vim executables and runtime files." IDNO NoRemoveExes Delete /REBOOTOK $0\*.dll ClearErrors # Remove everything but *.dll files. Avoids that # a lot remains when gvimext.dll cannot be deleted. RMDir /r $0\autoload RMDir /r $0\colors RMDir /r $0\compiler RMDir /r $0\doc RMDir /r $0\ftplugin RMDir /r $0\indent RMDir /r $0\macros RMDir /r $0\plugin RMDir /r $0\spell RMDir /r $0\syntax RMDir /r $0\tools RMDir /r $0\tutor RMDir /r $0\VisVim RMDir /r $0\lang RMDir /r $0\keymap Delete $0\*.exe Delete $0\*.bat Delete $0\*.vim Delete $0\*.txt IfErrors ErrorMess NoErrorMess ErrorMess: MessageBox MB_OK|MB_ICONEXCLAMATION \ "Some files in $0 have not been deleted!$\nYou must do it manually." NoErrorMess: # No error message if the "vim62" directory can't be removed, the # gvimext.dll may still be there. RMDir $0 NoRemoveExes: # get the parent dir of the installation Push $INSTDIR Call un.GetParent Pop $0 StrCpy $1 $0 # if a plugin dir was created at installation ask the user to remove it # first look in the root of the installation then in HOME IfFileExists $1\vimfiles AskRemove 0 ReadEnvStr $1 "HOME" StrCmp $1 "" NoRemove 0 IfFileExists $1\vimfiles 0 NoRemove AskRemove: MessageBox MB_YESNO|MB_ICONQUESTION \ "Remove all files in your $1\vimfiles directory?$\n \ $\nCAREFUL: If you have created something there that you want to keep, click No" IDNO Fin RMDir /r $1\vimfiles NoRemove: # ask the user if the Vim root dir must be removed MessageBox MB_YESNO|MB_ICONQUESTION \ "Would you like to remove $0?$\n \ $\nIt contains your Vim configuration files!" IDNO NoDelete RMDir /r $0 ; skipped if no NoDelete: Fin: Call un.onUnInstSuccess SectionEnd
zyz2011-vim
nsis/gvim.nsi
NSIS
gpl2
12,751
# This Makefile has two purposes: # 1. Starting the compilation of Vim for Unix. # 2. Creating the various distribution files. ######################################################################### # 1. Starting the compilation of Vim for Unix. # # Using this Makefile without an argument will compile Vim for Unix. # "make install" is also possible. # # NOTE: If this doesn't work properly, first change directory to "src" and use # the Makefile there: # cd src # make [arguments] # Noticed on AIX systems when using this Makefile: Trying to run "cproto" or # something else after Vim has been compiled. Don't know why... # Noticed on OS/390 Unix: Restarts configure. # # The first (default) target is "first". This will result in running # "make first", so that the target from "src/auto/config.mk" is picked # up properly when config didn't run yet. Doing "make all" before configure # has run can result in compiling with $(CC) empty. first: @if test ! -f src/auto/config.mk; then \ cp src/config.mk.dist src/auto/config.mk; \ fi @echo "Starting make in the src directory." @echo "If there are problems, cd to the src directory and run make there" cd src && $(MAKE) $@ # Some make programs use the last target for the $@ default; put the other # targets separately to always let $@ expand to "first" by default. all install uninstall tools config configure reconfig proto depend lint tags types test testclean clean distclean: @if test ! -f src/auto/config.mk; then \ cp src/config.mk.dist src/auto/config.mk; \ fi @echo "Starting make in the src directory." @echo "If there are problems, cd to the src directory and run make there" cd src && $(MAKE) $@ ######################################################################### # 2. Creating the various distribution files. # # TARGET PRODUCES CONTAINS # unixall vim-#.#.tar.bz2 All runtime files and sources, for Unix # # html vim##html.zip HTML docs # # dossrc vim##src.zip sources for MS-DOS # dosrt vim##rt.zip runtime for MS-DOS # dosbin vim##d16.zip binary for MS-DOS 16 bits # vim##d32.zip binary for MS-DOS 32 bits # vim##w32.zip binary for Win32 # gvim##.zip binary for GUI Win32 # gvim##ole.zip OLE exe for Win32 GUI # gvim##_s.zip exe for Win32s GUI # # OBSOLETE # amisrc vim##src.tgz sources for Amiga # amirt vim##rt.tgz runtime for Amiga # amibin vim##bin.tgz binary for Amiga # # os2bin vim##os2.zip binary for OS/2 # (use RT from dosrt) # # farsi farsi##.zip Farsi fonts # # All output files are created in the "dist" directory. Existing files are # overwritten! # To do all this you need the Unix archive and compiled binaries. # Before creating an archive first delete all backup files, *.orig, etc. MAJOR = 7 MINOR = 3 # Uncomment this line if the Win32s version is to be included. DOSBIN_S = dosbin_s # Uncomment this line if the 16 bit DOS version is to be included. # DOSBIN_D16 = dosbin_d16 # CHECKLIST for creating a new version: # # - Update Vim version number. For a test version in: src/version.h, Contents, # MAJOR/MINOR above, VIMMAJOR and VIMMINOR in src/Makefile, README*.txt, # runtime/doc/*.txt and nsis/gvim.nsi. Other things in README_os2.txt. For a # minor/major version: src/GvimExt/GvimExt.reg, src/vim.def, src/vim16.def, # src/gvim.exe.mnf. # - Adjust the date and other info in src/version.h. # - Correct included_patches[] in src/version.c. # - Compile Vim with GTK, Perl, Python, Python3, TCL, Ruby, MZscheme, Lua (if # you can make it all work), Cscope and "huge" features. Exclude workshop # and SNiFF. # - With these features: "make proto" (requires cproto and Motif installed; # ignore warnings for missing include files, fix problems for syntax errors). # - With these features: "make depend" (works best with gcc). # - If you have a lint program: "make lint" and check the output (ignore GTK # warnings). # - Enable the efence library in "src/Makefile" and run "make test". Disable # Python and Ruby to avoid trouble with threads (efence is not threadsafe). # - Check for missing entries in runtime/makemenu.vim (with checkmenu script). # - Check for missing options in runtime/optwin.vim et al. (with check.vim). # - Do "make menu" to update the runtime/synmenu.vim file. # - Add remarks for changes to runtime/doc/version7.txt. # - Check that runtime/doc/help.txt doesn't contain entries in "LOCAL # ADDITIONS". # - In runtime/doc run "make" and "make html" to check for errors. # - Check if src/Makefile and src/feature.h don't contain any personal # preferences or the GTK, Perl, etc. mentioned above. # - Check file protections to be "644" for text and "755" for executables (run # the "check" script). # - Check compiling on Amiga, MS-DOS and MS-Windows. # - Delete all *~, *.sw?, *.orig, *.rej files # - "make unixall", "make html" # - Make diff files against the previous release: "makediff7 7.1 7.2" # # Amiga: (OBSOLETE, Amiga files are no longer distributed) # - "make amisrc", move the archive to the Amiga and compile: # "make -f Make_manx.mak" (will use "big" features by default). # - Run the tests: "make -f Make_manx.mak test" # - Place the executables Vim and Xxd in this directory (set the executable # flag). # - "make amirt", "make amibin". # # PC: # - Run make on Unix to update the ".mo" files. # - "make dossrc" and "make dosrt". Unpack the archives on a PC. # 16 bit DOS version: (OBSOLETE, 16 bit version doesn't build) # - Set environment for compiling with Borland C++ 3.1. # - "bmake -f Make_bc3.mak BOR=E:\borlandc" (compiling xxd might fail, in that # case set environment for compiling with Borland C++ 4.0 and do # "make -f make_bc3.mak BOR=E:\BC4 xxd/xxd.exe"). # NOTE: this currently fails because Vim is too big. # - "make test" and check the output. # - Rename the executables to "vimd16.exe", "xxdd16.exe", "installd16.exe" and # "uninstald16.exe". # 32 bit DOS version: # - Set environment for compiling with DJGPP; "gmake -f Make_djg.mak". # - "rm testdir/*.out", "gmake -f Make_djg.mak test" and check the output for # "ALL DONE". # - Rename the executables to "vimd32.exe", "xxdd32.exe", "installd32.exe" and # "uninstald32.exe". # Win32 console version: # - Set environment for Visual C++ 2008, e.g.: # "E:\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat". Or, when using the # Visual C++ Toolkit 2003: "msvcsetup.bat" (adjust the paths when necessary). # For Windows 98/ME the 2003 version is required, but then it won't work on # Windows 7 and 64 bit. # - "nmake -f Make_mvc.mak" # - "rm testdir/*.out", "nmake -f Make_mvc.mak test" and check the output. # - Rename the executables to "vimw32.exe", "xxdw32.exe". # - Rename vim.pdb to vimw32.pdb. # - When building the Win32s version later, delete vimrun.exe, install.exe and # uninstal.exe. Otherwise rename executables to installw32.exe and # uninstalw32.exe. # Win32 GUI version: # - "nmake -f Make_mvc.mak GUI=yes. # - move "gvim.exe" to here (otherwise the OLE version will overwrite it). # - Move gvim.pdb to here. # - Delete vimrun.exe, install.exe and uninstal.exe. # - Copy "GvimExt/gvimext.dll" to here. # Win32 GUI version with OLE, PERL, TCL, PYTHON and dynamic IME: # - Run src/bigvim.bat ("nmake -f Make_mvc.mak GUI=yes OLE=yes IME=yes ...) # - Rename "gvim.exe" to "gvim_ole.exe". # - Rename gvim.pdb to "gvim_ole.pdb". # - Delete install.exe and uninstal.exe. # - If building the Win32s version delete vimrun.exe. # Win32s GUI version: # - Set environment for Visual C++ 4.1 (requires a new console window): # "vcvars32.bat" (use the path for VC 4.1 e:\msdev\bin) # - "nmake -f Make_mvc.mak GUI=yes INTL=no clean" (use the path for VC 4.1) # - "nmake -f Make_mvc.mak GUI=yes INTL=no" (use the path for VC 4.1) # - Rename "gvim.exe" to "gvim_w32s.exe". # - Rename "install.exe" to "installw32.exe" # - Rename "uninstal.exe" to "uninstalw32.exe" # - The produced uninstalw32.exe and vimrun.exe are used. # Create the archives: # - Copy all the "*.exe" files to where this Makefile is. # - Copy all the "*.pdb" files to where this Makefile is. # - "make dosbin". # NSIS self installing exe: # - To get NSIS see http://nsis.sourceforge.net # - Make sure gvim_ole.exe, vimd32.exe, vimw32.exe, installw32.exe, # uninstalw32.exe and xxdw32.exe have been build as mentioned above. # - copy these files (get them from a binary archive or build them): # gvimext.dll in src/GvimExt # gvimext64.dll in src/GvimExt # VisVim.dll in src/VisVim # Note: VisVim needs to be build with MSVC 5, newer versions don't work. # gvimext64.dll can be obtained from http://code.google.com/p/vim-win3264/ # It is part of vim72.zip as vim72/gvimext.dll. # - make sure there is a diff.exe two levels up # - go to ../nsis and do "makensis gvim.nsi" (takes a few minutes). # - Copy gvim##.exe to the dist directory. # # OS/2: (OBSOLETE, OS/2 version is no longer distributed) # - Unpack the Unix archive. # - "make -f Make_os2.mak". # - Rename the executables to vimos2.exe, xxdos2.exe and teeos2.exe and copy # them to here. # - "make os2bin". VIMVER = vim-$(MAJOR).$(MINOR) VERSION = $(MAJOR)$(MINOR) VDOT = $(MAJOR).$(MINOR) VIMRTDIR = vim$(VERSION) # Vim used for conversion from "unix" to "dos" VIM = vim # How to include Filelist depends on the version of "make" you have. # If the current choice doesn't work, try the other one. include Filelist #.include "Filelist" # All output is put in the "dist" directory. dist: mkdir dist # Clean up some files to avoid they are included. prepare: if test -f runtime/doc/uganda.nsis.txt; then \ rm runtime/doc/uganda.nsis.txt; fi # For the zip files we need to create a file with the comment line dist/comment: mkdir dist/comment COMMENT_RT = comment/$(VERSION)-rt COMMENT_D16 = comment/$(VERSION)-bin-d16 COMMENT_D32 = comment/$(VERSION)-bin-d32 COMMENT_W32 = comment/$(VERSION)-bin-w32 COMMENT_GVIM = comment/$(VERSION)-bin-gvim COMMENT_OLE = comment/$(VERSION)-bin-ole COMMENT_W32S = comment/$(VERSION)-bin-w32s COMMENT_SRC = comment/$(VERSION)-src COMMENT_OS2 = comment/$(VERSION)-bin-os2 COMMENT_HTML = comment/$(VERSION)-html COMMENT_FARSI = comment/$(VERSION)-farsi dist/$(COMMENT_RT): dist/comment echo "Vim - Vi IMproved - v$(VDOT) runtime files for MS-DOS and MS-Windows" > dist/$(COMMENT_RT) dist/$(COMMENT_D16): dist/comment echo "Vim - Vi IMproved - v$(VDOT) binaries for MS-DOS 16 bit real mode" > dist/$(COMMENT_D16) dist/$(COMMENT_D32): dist/comment echo "Vim - Vi IMproved - v$(VDOT) binaries for MS-DOS 32 bit protected mode" > dist/$(COMMENT_D32) dist/$(COMMENT_W32): dist/comment echo "Vim - Vi IMproved - v$(VDOT) binaries for MS-Windows NT/95" > dist/$(COMMENT_W32) dist/$(COMMENT_GVIM): dist/comment echo "Vim - Vi IMproved - v$(VDOT) GUI binaries for MS-Windows NT/95" > dist/$(COMMENT_GVIM) dist/$(COMMENT_OLE): dist/comment echo "Vim - Vi IMproved - v$(VDOT) MS-Windows GUI binaries with OLE support" > dist/$(COMMENT_OLE) dist/$(COMMENT_W32S): dist/comment echo "Vim - Vi IMproved - v$(VDOT) GUI binaries for MS-Windows 3.1/3.11" > dist/$(COMMENT_W32S) dist/$(COMMENT_SRC): dist/comment echo "Vim - Vi IMproved - v$(VDOT) sources for MS-DOS and MS-Windows" > dist/$(COMMENT_SRC) dist/$(COMMENT_OS2): dist/comment echo "Vim - Vi IMproved - v$(VDOT) binaries + runtime files for OS/2" > dist/$(COMMENT_OS2) dist/$(COMMENT_HTML): dist/comment echo "Vim - Vi IMproved - v$(VDOT) documentation in HTML" > dist/$(COMMENT_HTML) dist/$(COMMENT_FARSI): dist/comment echo "Vim - Vi IMproved - v$(VDOT) Farsi language files" > dist/$(COMMENT_FARSI) unixall: dist prepare -rm -f dist/$(VIMVER).tar.bz2 -rm -rf dist/$(VIMRTDIR) mkdir dist/$(VIMRTDIR) tar cf - \ $(RT_ALL) \ $(RT_ALL_BIN) \ $(RT_UNIX) \ $(RT_UNIX_DOS_BIN) \ $(RT_SCRIPTS) \ $(LANG_GEN) \ $(LANG_GEN_BIN) \ $(SRC_ALL) \ $(SRC_UNIX) \ $(SRC_DOS_UNIX) \ $(EXTRA) \ $(LANG_SRC) \ | (cd dist/$(VIMRTDIR); tar xf -) # Need to use a "distclean" config.mk file cp -f src/config.mk.dist dist/$(VIMRTDIR)/src/auto/config.mk # Create an empty config.h file, make dependencies require it touch dist/$(VIMRTDIR)/src/auto/config.h # Make sure configure is newer than config.mk to force it to be generated touch dist/$(VIMRTDIR)/src/configure # Make sure ja.sjis.po is newer than ja.po to avoid it being regenerated. # Same for cs.cp1250.po, pl.cp1250.po and sk.cp1250.po. touch dist/$(VIMRTDIR)/src/po/ja.sjis.po touch dist/$(VIMRTDIR)/src/po/cs.cp1250.po touch dist/$(VIMRTDIR)/src/po/pl.cp1250.po touch dist/$(VIMRTDIR)/src/po/sk.cp1250.po touch dist/$(VIMRTDIR)/src/po/zh_CN.cp936.po touch dist/$(VIMRTDIR)/src/po/ru.cp1251.po touch dist/$(VIMRTDIR)/src/po/uk.cp1251.po # Create the archive. cd dist && tar cf $(VIMVER).tar $(VIMRTDIR) bzip2 dist/$(VIMVER).tar # Amiga runtime - OBSOLETE amirt: dist prepare -rm -f dist/vim$(VERSION)rt.tar.gz -rm -rf dist/Vim mkdir dist/Vim mkdir dist/Vim/$(VIMRTDIR) tar cf - \ $(ROOT_AMI) \ $(RT_ALL) \ $(RT_ALL_BIN) \ $(RT_SCRIPTS) \ $(RT_AMI) \ $(RT_NO_UNIX) \ $(RT_AMI_DOS) \ | (cd dist/Vim/$(VIMRTDIR); tar xf -) mv dist/Vim/$(VIMRTDIR)/vimdir.info dist/Vim.info mv dist/Vim/$(VIMRTDIR)/runtime.info dist/Vim/$(VIMRTDIR).info mv dist/Vim/$(VIMRTDIR)/runtime/* dist/Vim/$(VIMRTDIR) rmdir dist/Vim/$(VIMRTDIR)/runtime cd dist && tar cf vim$(VERSION)rt.tar Vim Vim.info gzip -9 dist/vim$(VERSION)rt.tar mv dist/vim$(VERSION)rt.tar.gz dist/vim$(VERSION)rt.tgz # Amiga binaries - OBSOLETE amibin: dist prepare -rm -f dist/vim$(VERSION)bin.tar.gz -rm -rf dist/Vim mkdir dist/Vim mkdir dist/Vim/$(VIMRTDIR) tar cf - \ $(ROOT_AMI) \ $(BIN_AMI) \ Vim \ Xxd \ | (cd dist/Vim/$(VIMRTDIR); tar xf -) mv dist/Vim/$(VIMRTDIR)/vimdir.info dist/Vim.info mv dist/Vim/$(VIMRTDIR)/runtime.info dist/Vim/$(VIMRTDIR).info cd dist && tar cf vim$(VERSION)bin.tar Vim Vim.info gzip -9 dist/vim$(VERSION)bin.tar mv dist/vim$(VERSION)bin.tar.gz dist/vim$(VERSION)bin.tgz # Amiga sources - OBSOLETE amisrc: dist prepare -rm -f dist/vim$(VERSION)src.tar.gz -rm -rf dist/Vim mkdir dist/Vim mkdir dist/Vim/$(VIMRTDIR) tar cf - \ $(ROOT_AMI) \ $(SRC_ALL) \ $(SRC_AMI) \ $(SRC_AMI_DOS) \ | (cd dist/Vim/$(VIMRTDIR); tar xf -) mv dist/Vim/$(VIMRTDIR)/vimdir.info dist/Vim.info mv dist/Vim/$(VIMRTDIR)/runtime.info dist/Vim/$(VIMRTDIR).info cd dist && tar cf vim$(VERSION)src.tar Vim Vim.info gzip -9 dist/vim$(VERSION)src.tar mv dist/vim$(VERSION)src.tar.gz dist/vim$(VERSION)src.tgz no_title.vim: Makefile echo "set notitle noicon nocp nomodeline viminfo=" >no_title.vim # MS-DOS sources dossrc: dist no_title.vim dist/$(COMMENT_SRC) runtime/doc/uganda.nsis.txt -rm -rf dist/vim$(VERSION)src.zip -rm -rf dist/vim mkdir dist/vim mkdir dist/vim/$(VIMRTDIR) tar cf - \ $(SRC_ALL) \ $(SRC_DOS) \ $(SRC_AMI_DOS) \ $(SRC_DOS_UNIX) \ runtime/doc/uganda.nsis.txt \ | (cd dist/vim/$(VIMRTDIR); tar xf -) mv dist/vim/$(VIMRTDIR)/runtime/* dist/vim/$(VIMRTDIR) rmdir dist/vim/$(VIMRTDIR)/runtime find dist/vim/$(VIMRTDIR) -type f -exec $(VIM) -e -X -u no_title.vim -c ":set tx|wq" {} \; tar cf - \ $(SRC_DOS_BIN) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) cd dist && zip -9 -rD -z vim$(VERSION)src.zip vim <$(COMMENT_SRC) runtime/doc/uganda.nsis.txt: runtime/doc/uganda.txt cd runtime/doc && $(MAKE) uganda.nsis.txt dosrt: dist dist/$(COMMENT_RT) dosrt_unix2dos -rm -rf dist/vim$(VERSION)rt.zip cd dist && zip -9 -rD -z vim$(VERSION)rt.zip vim <$(COMMENT_RT) # Split in two parts to avoid an "argument list too long" error. dosrt_unix2dos: dist prepare no_title.vim -rm -rf dist/vim mkdir dist/vim mkdir dist/vim/$(VIMRTDIR) mkdir dist/vim/$(VIMRTDIR)/lang cd src && MAKEMO=yes $(MAKE) languages tar cf - \ $(RT_ALL) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) tar cf - \ $(RT_SCRIPTS) \ $(RT_DOS) \ $(RT_NO_UNIX) \ $(RT_AMI_DOS) \ $(LANG_GEN) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) find dist/vim/$(VIMRTDIR) -type f -exec $(VIM) -e -X -u no_title.vim -c ":set tx|wq" {} \; tar cf - \ $(RT_UNIX_DOS_BIN) \ $(RT_ALL_BIN) \ $(RT_DOS_BIN) \ $(LANG_GEN_BIN) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) mv dist/vim/$(VIMRTDIR)/runtime/* dist/vim/$(VIMRTDIR) rmdir dist/vim/$(VIMRTDIR)/runtime # Add the message translations. Trick: skip ja.mo and use ja.sjis.mo instead. # Same for cs.mo / cs.cp1250.mo, pl.mo / pl.cp1250.mo, sk.mo / sk.cp1250.mo, # zh_CN.mo / zh_CN.cp936.mo, uk.mo / uk.cp1251.mo and ru.mo / ru.cp1251.mo. for i in $(LANG_DOS); do \ if test "$$i" != "src/po/ja.mo" -a "$$i" != "src/po/pl.mo" -a "$$i" != "src/po/cs.mo" -a "$$i" != "src/po/sk.mo" -a "$$i" != "src/po/zh_CN.mo" -a "$$i" != "src/po/ru.mo" -a "$$i" != "src/po/uk.mo"; then \ n=`echo $$i | sed -e "s+src/po/\([-a-zA-Z0-9_]*\(.UTF-8\)*\)\(.sjis\)*\(.cp1250\)*\(.cp1251\)*\(.cp936\)*.mo+\1+"`; \ mkdir dist/vim/$(VIMRTDIR)/lang/$$n; \ mkdir dist/vim/$(VIMRTDIR)/lang/$$n/LC_MESSAGES; \ cp $$i dist/vim/$(VIMRTDIR)/lang/$$n/LC_MESSAGES/vim.mo; \ fi \ done cp libintl.dll dist/vim/$(VIMRTDIR)/ # Convert runtime files from Unix fileformat to dos fileformat. # Used before uploading. Don't delete the AAPDIR/sign files! runtime_unix2dos: dosrt_unix2dos -rm -rf `find runtime/dos -type f -print | sed -e /AAPDIR/d` cd dist/vim/$(VIMRTDIR); tar cf - * \ | (cd ../../../runtime/dos; tar xf -) dosbin: prepare dosbin_gvim dosbin_w32 dosbin_d32 dosbin_ole $(DOSBIN_S) $(DOSBIN_D16) # make Win32 gvim dosbin_gvim: dist no_title.vim dist/$(COMMENT_GVIM) -rm -rf dist/gvim$(VERSION).zip -rm -rf dist/vim mkdir dist/vim mkdir dist/vim/$(VIMRTDIR) tar cf - \ $(BIN_DOS) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) find dist/vim/$(VIMRTDIR) -type f -exec $(VIM) -e -X -u no_title.vim -c ":set tx|wq" {} \; cp gvim.exe dist/vim/$(VIMRTDIR)/gvim.exe cp xxdw32.exe dist/vim/$(VIMRTDIR)/xxd.exe cp vimrun.exe dist/vim/$(VIMRTDIR)/vimrun.exe cp installw32.exe dist/vim/$(VIMRTDIR)/install.exe cp uninstalw32.exe dist/vim/$(VIMRTDIR)/uninstal.exe cp gvimext.dll dist/vim/$(VIMRTDIR)/gvimext.dll cd dist && zip -9 -rD -z gvim$(VERSION).zip vim <$(COMMENT_GVIM) cp gvim.pdb dist/gvim$(VERSION).pdb # make Win32 console dosbin_w32: dist no_title.vim dist/$(COMMENT_W32) -rm -rf dist/vim$(VERSION)w32.zip -rm -rf dist/vim mkdir dist/vim mkdir dist/vim/$(VIMRTDIR) tar cf - \ $(BIN_DOS) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) find dist/vim/$(VIMRTDIR) -type f -exec $(VIM) -e -X -u no_title.vim -c ":set tx|wq" {} \; cp vimw32.exe dist/vim/$(VIMRTDIR)/vim.exe cp xxdw32.exe dist/vim/$(VIMRTDIR)/xxd.exe cp installw32.exe dist/vim/$(VIMRTDIR)/install.exe cp uninstalw32.exe dist/vim/$(VIMRTDIR)/uninstal.exe cd dist && zip -9 -rD -z vim$(VERSION)w32.zip vim <$(COMMENT_W32) cp vimw32.pdb dist/vim$(VERSION)w32.pdb # make 32bit DOS dosbin_d32: dist no_title.vim dist/$(COMMENT_D32) -rm -rf dist/vim$(VERSION)d32.zip -rm -rf dist/vim mkdir dist/vim mkdir dist/vim/$(VIMRTDIR) tar cf - \ $(BIN_DOS) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) find dist/vim/$(VIMRTDIR) -type f -exec $(VIM) -e -X -u no_title.vim -c ":set tx|wq" {} \; cp vimd32.exe dist/vim/$(VIMRTDIR)/vim.exe cp xxdd32.exe dist/vim/$(VIMRTDIR)/xxd.exe cp installd32.exe dist/vim/$(VIMRTDIR)/install.exe cp uninstald32.exe dist/vim/$(VIMRTDIR)/uninstal.exe cp csdpmi4b.zip dist/vim/$(VIMRTDIR) cd dist && zip -9 -rD -z vim$(VERSION)d32.zip vim <$(COMMENT_D32) # make 16bit DOS dosbin_d16: dist no_title.vim dist/$(COMMENT_D16) -rm -rf dist/vim$(VERSION)d16.zip -rm -rf dist/vim mkdir dist/vim mkdir dist/vim/$(VIMRTDIR) tar cf - \ $(BIN_DOS) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) find dist/vim/$(VIMRTDIR) -type f -exec $(VIM) -e -X -u no_title.vim -c ":set tx|wq" {} \; cp vimd16.exe dist/vim/$(VIMRTDIR)/vim.exe cp xxdd16.exe dist/vim/$(VIMRTDIR)/xxd.exe cp installd16.exe dist/vim/$(VIMRTDIR)/install.exe cp uninstald16.exe dist/vim/$(VIMRTDIR)/uninstal.exe cd dist && zip -9 -rD -z vim$(VERSION)d16.zip vim <$(COMMENT_D16) # make Win32 gvim with OLE dosbin_ole: dist no_title.vim dist/$(COMMENT_OLE) -rm -rf dist/gvim$(VERSION)ole.zip -rm -rf dist/vim mkdir dist/vim mkdir dist/vim/$(VIMRTDIR) tar cf - \ $(BIN_DOS) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) find dist/vim/$(VIMRTDIR) -type f -exec $(VIM) -e -X -u no_title.vim -c ":set tx|wq" {} \; cp gvim_ole.exe dist/vim/$(VIMRTDIR)/gvim.exe cp xxdw32.exe dist/vim/$(VIMRTDIR)/xxd.exe cp vimrun.exe dist/vim/$(VIMRTDIR)/vimrun.exe cp installw32.exe dist/vim/$(VIMRTDIR)/install.exe cp uninstalw32.exe dist/vim/$(VIMRTDIR)/uninstal.exe cp gvimext.dll dist/vim/$(VIMRTDIR)/gvimext.dll cp README_ole.txt dist/vim/$(VIMRTDIR) cp src/VisVim/VisVim.dll dist/vim/$(VIMRTDIR)/VisVim.dll cp src/VisVim/README_VisVim.txt dist/vim/$(VIMRTDIR) cd dist && zip -9 -rD -z gvim$(VERSION)ole.zip vim <$(COMMENT_OLE) cp gvim_ole.pdb dist/gvim$(VERSION)ole.pdb # make Win32s gvim dosbin_s: dist no_title.vim dist/$(COMMENT_W32S) -rm -rf dist/gvim$(VERSION)_s.zip -rm -rf dist/vim mkdir dist/vim mkdir dist/vim/$(VIMRTDIR) tar cf - \ $(BIN_DOS) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) find dist/vim/$(VIMRTDIR) -type f -exec $(VIM) -e -X -u no_title.vim -c ":set tx|wq" {} \; cp gvim_w32s.exe dist/vim/$(VIMRTDIR)/gvim.exe cp xxdd32.exe dist/vim/$(VIMRTDIR)/xxd.exe cp README_w32s.txt dist/vim/$(VIMRTDIR) cp installw32.exe dist/vim/$(VIMRTDIR)/install.exe cp uninstalw32.exe dist/vim/$(VIMRTDIR)/uninstal.exe cd dist && zip -9 -rD -z gvim$(VERSION)_s.zip vim <$(COMMENT_W32S) os2bin: dist no_title.vim dist/$(COMMENT_OS2) -rm -rf dist/vim$(VERSION)os2.zip -rm -rf dist/vim mkdir dist/vim mkdir dist/vim/$(VIMRTDIR) tar cf - \ $(BIN_OS2) \ | (cd dist/vim/$(VIMRTDIR); tar xf -) find dist/vim/$(VIMRTDIR) -type f -exec $(VIM) -e -X -u no_title.vim -c ":set tx|wq" {} \; cp vimos2.exe dist/vim/$(VIMRTDIR)/vim.exe cp xxdos2.exe dist/vim/$(VIMRTDIR)/xxd.exe cp teeos2.exe dist/vim/$(VIMRTDIR)/tee.exe cp emx.dll emxlibcs.dll dist/vim/$(VIMRTDIR) cd dist && zip -9 -rD -z vim$(VERSION)os2.zip vim <$(COMMENT_OS2) html: dist dist/$(COMMENT_HTML) -rm -rf dist/vim$(VERSION)html.zip cd runtime/doc && zip -9 -z ../../dist/vim$(VERSION)html.zip *.html <../../dist/$(COMMENT_HTML) farsi: dist dist/$(COMMENT_FARSI) -rm -f dist/farsi$(VERSION).zip zip -9 -rD -z dist/farsi$(VERSION).zip farsi < dist/$(COMMENT_FARSI)
zyz2011-vim
Makefile
Makefile
gpl2
22,365
:: Start Vim on a copy of the tutor file. @echo off :: Usage: vimtutor [-console] [xx] :: :: -console means gvim will not be used :: xx is a language code like "es" or "nl". :: When an xx argument is given, it tries loading that tutor. :: When this fails or no xx argument was given, it tries using 'v:lang' :: When that also fails, it uses the English version. :: Use Vim to copy the tutor, it knows the value of $VIMRUNTIME FOR %%d in (. %TMP% %TEMP%) DO IF EXIST %%d\nul SET TUTORCOPY=%%d\$tutor$ SET xx=%1 IF NOT .%1==.-console GOTO use_gui SHIFT SET xx=%1 GOTO use_vim :use_gui :: Try making a copy of tutor with gvim. If gvim cannot be found, try using :: vim instead. If vim cannot be found, alert user to check environment and :: installation. :: The script tutor.vim tells Vim which file to copy. :: For Windows NT "start" works a bit differently. IF .%OS%==.Windows_NT GOTO ntaction start /w gvim -u NONE -c "so $VIMRUNTIME/tutor/tutor.vim" IF ERRORLEVEL 1 GOTO use_vim :: Start gvim without any .vimrc, set 'nocompatible' start /w gvim -u NONE -c "set nocp" %TUTORCOPY% GOTO end :ntaction start "dummy" /b /w gvim -u NONE -c "so $VIMRUNTIME/tutor/tutor.vim" IF ERRORLEVEL 1 GOTO use_vim :: Start gvim without any .vimrc, set 'nocompatible' start "dummy" /b /w gvim -u NONE -c "set nocp" %TUTORCOPY% GOTO end :use_vim :: The script tutor.vim tells Vim which file to copy vim -u NONE -c "so $VIMRUNTIME/tutor/tutor.vim" IF ERRORLEVEL 1 GOTO no_executable :: Start vim without any .vimrc, set 'nocompatible' vim -u NONE -c "set nocp" %TUTORCOPY% GOTO end :no_executable ECHO. ECHO. ECHO No vim or gvim found in current directory or PATH. ECHO Check your installation or re-run install.exe :end :: remove the copy of the tutor IF EXIST %TUTORCOPY% DEL %TUTORCOPY% SET xx=
zyz2011-vim
vimtutor.bat
Batchfile
gpl2
1,798
$ ! $ !===================================================================== $ ! $ ! VimTutor.com version 29-Aug-2002 $ ! $ ! Author: Tom Wyant <Thomas.R.Wyant-III@usa.dupont.com> $ ! $ ! This DCL command procedure executes the vimtutor command $ ! (suprise, suprise!) which gives you a brief tutorial on the VIM $ ! editor. Languages other than the default are supported in the $ ! usual way, as are at least some of the command qualifiers, $ ! though you'll need to play some fairly serious games with DCL $ ! to specify ones that need quoting. $ ! $ ! Copyright (c) 2002 E. I. DuPont de Nemours and Company, Inc $ ! $ ! This program is free software; you can redistribute it and/or $ ! modify it under the terms of the VIM license as available from $ ! the vim 6.1 ":help license" command or (at your option) the $ ! license from any later version of vim. $ ! $ ! This program is distributed in the hope that it will be useful, $ ! but WITHOUT ANY WARRANTY; without even the implied warranty of $ ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ ! $ !===================================================================== $ ! $ ! $ ! Check for the existence of VIM, and die if it isn't there. $ ! $ if f$search ("vim:vim.exe") .eqs. "" $ then $ write sys$error "Error - Can't run tutoral. VIM not found." $ exit $ endif $ ! $ ! $ ! Pick up the argument, if any. $ ! $ inx = 0 $ arg_loop: $ inx = inx + 1 $ if f$type (p'inx') .nes. "" $ then $ if p'inx' .nes. "" .and. f$locate ("-", p'inx') .ne. 0 $ then $ xx = p'inx' $ assign/nolog "''xx'" xx $ p'inx' = "" $ endif $ goto arg_loop $ endif $ ! $ ! $ ! Make sure we clean up our toys when we're through playing. $ ! $ on error then goto exit $ ! $ ! $ ! Create the VIM foreign command if needed $ ! $ if f$type (vim) .eqs. "" then vim := $vim:vim $ ! $ ! $ ! Build the name for our temp file. $ ! $ tutfil = "sys$login:vimtutor_" + - f$edit (f$getjpi (0, "pid"), "trim") + "." $ assign/nolog 'tutfil' TUTORCOPY $ ! $ ! $ ! Copy the selected file to the temp file $ ! $ assign/nolog/user nla0: sys$error $ assign/nolog/user nla0: sys$output $ vim -u "NONE" -c "so $VIMRUNTIME/tutor/tutor.vim" $ ! $ ! $ ! Run the tutorial $ ! $ assign/nolog/user sys$command sys$input $ vim -u "NONE" -c "set nocp" 'p1' 'p2' 'p3' 'p4' 'p5' 'p6' 'p7' 'p8' 'tutfil' $ ! $ ! $ ! Ditch the copy. $ ! $ exit: $ if f$type (tutfil) .nes. "" .and. f$search (tutfil) .nes. "" then - $ delete 'tutfil';* $ if f$type (xx) .nes. "" then deassign xx $ deassign TUTORCOPY $ exit $ ! $ !===================================================================== $ ! $ ! Modification history $ ! $ ! 29-Aug-2002 T. R. Wyant $ ! Changed license to vim. $ ! Fix error "input is not from a terminal" $ ! Juggle documentation (copyright and contact to front, $ ! modification history to end). $ ! 25-Jul-2002 T. R. Wyant $ ! Initial version
zyz2011-vim
vimtutor.com
DIGITAL Command Language
gpl2
2,898
# # Makefile for Vim. # Compiler: Borland C++ 5.0 and later 32-bit compiler # Targets: Dos16 or Win32 (Windows NT and Windows 95) (with/without GUI) # # Contributed by Ben Singer. # Updated 4/1997 by Ron Aaron # 6/1997 - added support for 16 bit DOS # Note: this has been tested, and works, for BC5. Your mileage may vary. # Has been reported NOT to work with BC 4.52. Maybe it can be fixed? # 10/1997 - ron - fixed bugs w/ BC 5.02 # 8/1998 - ron - updated with new targets, fixed some stuff # 3/2000 - Bram: Made it work with BC 5.5 free command line compiler, # cleaned up variables. # 6/2001 - Dan - Added support for compiling Python and TCL # 7/2001 - Dan - Added support for compiling Ruby # # It builds on Windows 95 and NT-Intel, producing the same binary in either # case. To build using Microsoft Visual C++, use Make_mvc.mak. # # This should work with the free Borland command line compiler, version 5.5. # You need at least sp1 (service pack 1). With sp2 it compiles faster. # Use a command like this: # <path>\bin\make /f Make_bc5.mak BOR=<path> # # let the make utility do the hard work: .AUTODEPEND .CACHEAUTODEPEND # VARIABLES: # name value (default) # # BOR path to root of Borland C install (c:\bc5) # LINK name of the linker ($(BOR)\bin\ilink if OSTYPE is DOS16, # $(BOR)\bin\ilink32 otherwise) # GUI no or yes: set to yes if you want the GUI version (yes) # LUA define to path to Lua dir to get Lua support (not defined) # LUA_VER define to version of Lua being used (51) # DYNAMIC_LUA no or yes: set to yes to load the Lua DLL dynamically (no) # PERL define to path to Perl dir to get Perl support (not defined) # PERL_VER define to version of Perl being used (56) # DYNAMIC_PERL no or yes: set to yes to load the Perl DLL dynamically (no) # PYTHON define to path to Python dir to get PYTHON support (not defined) # PYTHON_VER define to version of Python being used (22) # DYNAMIC_PYTHON no or yes: use yes to load the Python DLL dynamically (no) # PYTHON3 define to path to Python3 dir to get PYTHON3 support (not defined) # PYTHON3_VER define to version of Python3 being used (31) # DYNAMIC_PYTHON3 no or yes: use yes to load the Python3 DLL dynamically (no) # TCL define to path to TCL dir to get TCL support (not defined) # TCL_VER define to version of TCL being used (83) # DYNAMIC_TCL no or yes: use yes to load the TCL DLL dynamically (no) # RUBY define to path to Ruby dir to get Ruby support (not defined) # NOTE: You may have to remove the defines for uid_t and gid_t # from the Ruby config.h header file. # RUBY_VER define to version of Ruby being used (16) # NOTE: compilation on WinNT/2K/XP requires # at least version 1.6.5 of Ruby. Earlier versions # of Ruby will cause a compile error on these systems. # RUBY_VER_LONG same, but in format with dot. (1.6) # DYNAMIC_RUBY no or yes: use yes to load the Ruby DLL dynamically (no) # MBYTE no or yes: set to yes for multi-byte support (yes) # NOTE: multi-byte support is broken in the Borland libraries, # not everything will work properly! Esp. handling multi-byte # file names. # IME no or yes: set to yes for multi-byte IME support (yes) # DYNAMIC_IME no or yes: set to yes to load imm32.dll dynamically (yes) # GETTEXT no or yes: set to yes for multi-language support (yes) # ICONV no or yes: set to yes for dynamic iconv support (yes) # OLE no or yes: set to yes to make OLE gvim (no) # OSTYPE DOS16 or WIN32 (WIN32) # DEBUG no or yes: set to yes if you wish a DEBUGging build (no) # CODEGUARD no or yes: set to yes if you want to use CODEGUARD (no) # CPUNR 1 through 6: select -CPU argument to compile with (3) # 3 for 386, 4 for 486, 5 for pentium, 6 for pentium pro. # USEDLL no or yes: set to yes to use the Runtime library DLL (no) # For USEDLL=yes the cc3250.dll is required to run Vim. # VIMDLL no or yes: create vim32.dll, and stub (g)vim.exe (no) # ALIGN 1, 2 or 4: Alignment to use (4 for Win32, 2 for DOS16) # FASTCALL no or yes: set to yes to use register-based function protocol (yes) # OPTIMIZE SPACE, SPEED, or MAXSPEED: type of optimization (MAXSPEED) # POSTSCRIPT no or yes: set to yes for PostScript printing # FEATURES TINY, SMALL, NORMAL, BIG or HUGE # (BIG for WIN32, SMALL for DOS16) # WINVER 0x0400 or 0x0500: minimum Win32 version to support (0x0400) # CSCOPE no or yes: include support for Cscope interface (yes) # NETBEANS no or yes: include support for Netbeans interface (yes if GUI # is yes) # NBDEBUG no or yes: include support for debugging Netbeans interface (no) # XPM define to path to XPM dir to get support for loading XPM images. ### BOR: root of the BC installation !if ("$(BOR)"=="") BOR = c:\bc5 !endif ### LINK: Name of the linker: tlink or ilink32 (this is below, depends on # $(OSTYPE) ### GUI: yes for GUI version, no for console version !if ("$(GUI)"=="") GUI = yes !endif ### MBYTE: yes for multibyte support, no to disable it. !if ("$(MBYTE)"=="") MBYTE = yes !endif ### IME: yes for multibyte support, no to disable it. !if ("$(IME)"=="") IME = yes !endif !if ("$(DYNAMIC_IME)"=="") DYNAMIC_IME = yes !endif ### GETTEXT: yes for multilanguage support, no to disable it. !if ("$(GETTEXT)"=="") GETTEXT = yes !endif ### ICONV: yes to enable dynamic-iconv support, no to disable it !if ("$(ICONV)"=="") ICONV = yes !endif ### CSCOPE: yes to enable Cscope support, no to disable it !if ("$(CSCOPE)"=="") CSCOPE = yes !endif ### NETBEANS: yes to enable NetBeans interface support, no to disable it !if ("$(NETBEANS)"=="") && ("$(GUI)"=="yes") NETBEANS = yes !endif ### LUA: uncomment this line if you want lua support in vim # LUA=c:\lua ### PERL: uncomment this line if you want perl support in vim # PERL=c:\perl ### PYTHON: uncomment this line if you want python support in vim # PYTHON=c:\python22 ### PYTHON3: uncomment this line if you want python3 support in vim # PYTHON3=c:\python31 ### RUBY: uncomment this line if you want ruby support in vim # RUBY=c:\ruby ### TCL: uncomment this line if you want tcl support in vim # TCL=c:\tcl ### OLE: no for normal gvim, yes for OLE-capable gvim (only works with GUI) #OLE = yes ### OSTYPE: DOS16 for Windows 3.1 version, WIN32 for Windows 95/98/NT/2000 # version !if ("$(OSTYPE)"=="") OSTYPE = WIN32 !endif ### DEBUG: Uncomment to make an executable for debugging # DEBUG = yes !if ("$(DEBUG)"=="yes") DEBUG_FLAG = -v !endif ### CODEGUARD: Uncomment to use the CODEGUARD stuff (BC 5.0 or later): # CODEGUARD = yes !if ("$(CODEGUARD)"=="yes") CODEGUARD_FLAG = -vG !endif ### CPUNR: set your target processor (3 to 6) !if ("$(CPUNR)" == "i386") || ("$(CPUNR)" == "3") CPUNR = 3 !elif ("$(CPUNR)" == "i486") || ("$(CPUNR)" == "4") CPUNR = 4 !elif ("$(CPUNR)" == "i586") || ("$(CPUNR)" == "5") CPUNR = 5 !elif ("$(CPUNR)" == "i686") || ("$(CPUNR)" == "6") CPUNR = 6 !else CPUNR = 3 !endif ### Comment out to use precompiled headers (faster, but uses lots of disk!) HEADERS = -H -H=vim.csm -Hc ### USEDLL: no for statically linked version of run-time, yes for DLL runtime !if ("$(USEDLL)"=="") USEDLL = no !endif ### VIMDLL: yes for a DLL version of VIM (NOT RECOMMENDED), no otherwise #VIMDLL = yes ### ALIGN: alignment you desire: (1,2 or 4: s/b 4 for Win32, 2 for DOS) !if ("$(ALIGN)"=="") !if ($(OSTYPE)==DOS16) ALIGN = 2 !else ALIGN = 4 !endif !endif ### FASTCALL: yes to use FASTCALL calling convention (RECOMMENDED!), no otherwise # Incompatible when calling external functions (like MSVC-compiled DLLs), so # don't use FASTCALL when linking with external libs. !if ("$(FASTCALL)"=="") && \ ("$(LUA)"=="") && \ ("$(PYTHON)"=="") && \ ("$(PYTHON3)"=="") && \ ("$(PERL)"=="") && \ ("$(TCL)"=="") && \ ("$(RUBY)"=="") && \ ("$(ICONV)"!="yes") && \ ("$(IME)"!="yes") && \ ("$(MBYTE)"!="yes") && \ ("$(XPM)"=="") FASTCALL = yes !endif ### OPTIMIZE: SPEED to optimize for speed, SPACE otherwise (SPEED RECOMMENDED) !if ("$(OPTIMIZE)"=="") OPTIMIZE = MAXSPEED !endif ### FEATURES: TINY, SMALL, NORMAL, BIG or HUGE (BIG for WIN32, SMALL for DOS16) !if ("$(FEATURES)"=="") ! if ($(OSTYPE)==DOS16) FEATURES = SMALL ! else FEATURES = BIG ! endif !endif ### POSTSCRIPT: uncomment this line if you want PostScript printing #POSTSCRIPT = yes ### # If you have a fixed directory for $VIM or $VIMRUNTIME, other than the normal # default, use these lines. #VIMRCLOC = somewhere #VIMRUNTIMEDIR = somewhere ### Set the default $(WINVER) to make it work with Bcc 5.5. !ifndef WINVER WINVER = 0x0400 !endif # # Sanity checks for the above options: # !if ($(OSTYPE)==DOS16) !if (($(CPUNR)+0)>4) !error CPUNR Must be less than or equal to 4 for DOS16 !endif !if (($(ALIGN)+0)>2) !error ALIGN Must be less than or equal to 2 for DOS16 !endif !else # not DOS16 !if (($(CPUNR)+0)<3) !error CPUNR Must be greater or equal to 3 for WIN32 !endif !endif !if ($(OSTYPE)!=WIN32) && ($(OSTYPE)!=DOS16) !error Check the OSTYPE variable again: $(OSTYPE) is not supported! !endif # # Optimizations: change as desired (RECOMMENDATION: Don't change!): # !if ("$(DEBUG)"=="yes") OPT = -Od -N !else !if ("$(OPTIMIZE)"=="SPACE") OPT = -O1 -f- -d !elif ("$(OPTIMIZE)"=="MAXSPEED") OPT = -O2 -f- -d -Ocavi -O !else OPT = -O2 -f- -d -Oc -O !endif !if ("$(FASTCALL)"=="yes") OPT = $(OPT) -pr !endif !if ("$(CODEGUARD)"!="yes") OPT = $(OPT) -vi- !endif !endif !if ($(OSTYPE)==DOS16) !undef GUI !undef VIMDLL !undef USEDLL !endif # shouldn't have to change: LIB = $(BOR)\lib INCLUDE = $(BOR)\include;.;proto DEFINES = -DFEAT_$(FEATURES) -DWIN32 -DHAVE_PATHDEF \ -DWINVER=$(WINVER) -D_WIN32_WINNT=$(WINVER) !ifdef LUA INTERP_DEFINES = $(INTERP_DEFINES) -DFEAT_LUA INCLUDE = $(LUA)\include;$(INCLUDE) ! ifndef LUA_VER LUA_VER = 51 ! endif ! if ("$(DYNAMIC_LUA)" == "yes") INTERP_DEFINES = $(INTERP_DEFINES) -DDYNAMIC_LUA -DDYNAMIC_LUA_DLL=\"lua$(LUA_VER).dll\" LUA_LIB_FLAG = /nodefaultlib: ! endif !endif !ifdef PERL INTERP_DEFINES = $(INTERP_DEFINES) -DFEAT_PERL INCLUDE = $(PERL)\lib\core;$(INCLUDE) ! ifndef PERL_VER PERL_VER = 56 ! endif ! if ("$(DYNAMIC_PERL)" == "yes") ! if ($(PERL_VER) > 55) INTERP_DEFINES = $(INTERP_DEFINES) -DDYNAMIC_PERL -DDYNAMIC_PERL_DLL=\"perl$(PERL_VER).dll\" PERL_LIB_FLAG = /nodefaultlib: ! else ! message "Cannot dynamically load Perl versions less than 5.6. Loading statically..." ! endif ! endif !endif !ifdef PYTHON !ifdef PYTHON3 DYNAMIC_PYTHON=yes DYNAMIC_PYTHON3=yes !endif !endif !ifdef PYTHON INTERP_DEFINES = $(INTERP_DEFINES) -DFEAT_PYTHON !ifndef PYTHON_VER PYTHON_VER = 22 !endif !if "$(DYNAMIC_PYTHON)" == "yes" INTERP_DEFINES = $(INTERP_DEFINES) -DDYNAMIC_PYTHON -DDYNAMIC_PYTHON_DLL=\"python$(PYTHON_VER).dll\" PYTHON_LIB_FLAG = /nodefaultlib: !endif !endif !ifdef PYTHON3 INTERP_DEFINES = $(INTERP_DEFINES) -DFEAT_PYTHON3 !ifndef PYTHON3_VER PYTHON3_VER = 31 !endif !if "$(DYNAMIC_PYTHON3)" == "yes" INTERP_DEFINES = $(INTERP_DEFINES) -DDYNAMIC_PYTHON3 -DDYNAMIC_PYTHON3_DLL=\"python$(PYTHON3_VER).dll\" PYTHON3_LIB_FLAG = /nodefaultlib: !endif !endif !ifdef RUBY !ifndef RUBY_VER RUBY_VER = 16 !endif !ifndef RUBY_VER_LONG RUBY_VER_LONG = 1.6 !endif !if "$(RUBY_VER)" == "16" !ifndef RUBY_PLATFORM RUBY_PLATFORM = i586-mswin32 !endif !ifndef RUBY_INSTALL_NAME RUBY_INSTALL_NAME = mswin32-ruby$(RUBY_VER) !endif !else !ifndef RUBY_PLATFORM RUBY_PLATFORM = i386-mswin32 !endif !ifndef RUBY_INSTALL_NAME RUBY_INSTALL_NAME = msvcrt-ruby$(RUBY_VER) !endif !endif INTERP_DEFINES = $(INTERP_DEFINES) -DFEAT_RUBY INCLUDE = $(RUBY)\lib\ruby\$(RUBY_VER_LONG)\$(RUBY_PLATFORM);$(INCLUDE) !if "$(DYNAMIC_RUBY)" == "yes" INTERP_DEFINES = $(INTERP_DEFINES) -DDYNAMIC_RUBY -DDYNAMIC_RUBY_DLL=\"$(RUBY_INSTALL_NAME).dll\" INTERP_DEFINES = $(INTERP_DEFINES) -DDYNAMIC_RUBY_VER=$(RUBY_VER) RUBY_LIB_FLAG = /nodefaultlib: !endif !endif !ifdef TCL INTERP_DEFINES = $(INTERP_DEFINES) -DFEAT_TCL INCLUDE = $(TCL)\include;$(INCLUDE) !ifndef TCL_VER TCL_VER = 83 !endif TCL_LIB = $(TCL)\lib\tcl$(TCL_VER).lib TCL_LIB_FLAG = !if "$(DYNAMIC_TCL)" == "yes" INTERP_DEFINES = $(INTERP_DEFINES) -DDYNAMIC_TCL -DDYNAMIC_TCL_DLL=\"tcl$(TCL_VER).dll\" TCL_LIB = tclstub$(TCL_VER)-bor.lib TCL_LIB_FLAG = !endif !endif # # DO NOT change below: # CPUARG = -$(CPUNR) ALIGNARG = -a$(ALIGN) # !if ("$(DEBUG)"=="yes") DEFINES=$(DEFINES) -DDEBUG !endif # !if ("$(OLE)"=="yes") DEFINES = $(DEFINES) -DFEAT_OLE !endif # !if ("$(MBYTE)"=="yes") MBDEFINES = $(MBDEFINES) -DFEAT_MBYTE !endif !if ("$(IME)"=="yes") MBDEFINES = $(MBDEFINES) -DFEAT_MBYTE_IME !if ("$(DYNAMIC_IME)" == "yes") MBDEFINES = $(MBDEFINES) -DDYNAMIC_IME !endif !endif !if ("$(ICONV)"=="yes") MBDEFINES = $(MBDEFINES) -DDYNAMIC_ICONV !endif !if ("$(GETTEXT)"=="yes") MBDEFINES = $(MBDEFINES) -DDYNAMIC_GETTEXT !endif !if ("$(CSCOPE)"=="yes") DEFINES = $(DEFINES) -DFEAT_CSCOPE !endif !if ("$(GUI)"=="yes") DEFINES = $(DEFINES) -DFEAT_GUI_W32 -DFEAT_CLIPBOARD !if ("$(DEBUG)"=="yes") TARGET = gvimd.exe !else TARGET = gvim.exe !endif !if ("$(VIMDLL)"=="yes") EXETYPE=-WD DEFINES = $(DEFINES) -DVIMDLL !else EXETYPE=-W !endif STARTUPOBJ = c0w32.obj LINK2 = -aa RESFILE = vim.res !else !undef NETBEANS !undef XPM !undef VIMDLL !if ("$(DEBUG)"=="yes") TARGET = vimd.exe !else # for now, anyway: VIMDLL is only for the GUI version TARGET = vim.exe !endif !if ($(OSTYPE)==DOS16) DEFINES= -DFEAT_$(FEATURES) -DMSDOS EXETYPE=-ml STARTUPOBJ = c0l.obj LINK2 = !else EXETYPE=-WC STARTUPOBJ = c0x32.obj LINK2 = -ap -OS -o -P !endif RESFILE = vim.res !endif !if ("$(NETBEANS)"=="yes") DEFINES = $(DEFINES) -DFEAT_NETBEANS_INTG !if ("$(NBDEBUG)"=="yes") DEFINES = $(DEFINES) -DNBDEBUG NBDEBUG_DEP = nbdebug.h nbdebug.c !endif !endif !ifdef XPM !if ("$(GUI)"=="yes") DEFINES = $(DEFINES) -DFEAT_XPM_W32 INCLUDE = $(XPM)\include;$(INCLUDE) !endif !endif !if ("$(USEDLL)"=="yes") DEFINES = $(DEFINES) -D_RTLDLL !endif !if ("$(DEBUG)"=="yes") OBJDIR = $(OSTYPE)\objdbg !else !if ("$(GUI)"=="yes") !if ("$(OLE)"=="yes") OBJDIR = $(OSTYPE)\oleobj !else OBJDIR = $(OSTYPE)\gobj !endif !else OBJDIR = $(OSTYPE)\obj !endif !endif !if ("$(POSTSCRIPT)"=="yes") DEFINES = $(DEFINES) -DMSWINPS !endif ##### BASE COMPILER/TOOLS RULES ##### MAKE = $(BOR)\bin\make CFLAGS = -w-aus -w-par -w-pch -w-ngu -w-csu -I$(INCLUDE) !if ($(OSTYPE)==DOS16) BRC = !if ("$(LINK)"=="") LINK = $(BOR)\BIN\TLink !endif CC = $(BOR)\BIN\Bcc LFLAGS = -Tde -c -m -L$(LIB) $(DEBUG_FLAG) $(LINK2) LFLAGSDLL = CFLAGS = $(CFLAGS) -H- $(HEADERS) !else BRC = $(BOR)\BIN\brc32 !if ("$(LINK)"=="") LINK = $(BOR)\BIN\ILink32 !endif CC = $(BOR)\BIN\Bcc32 LFLAGS = -OS -Tpe -c -m -L$(LIB) $(DEBUG_FLAG) $(LINK2) LFLAGSDLL = -Tpd -c -m -L$(LIB) $(DEBUG_FLAG) $(LINK2) CFLAGS = $(CFLAGS) -d -RT- -k- -Oi $(HEADERS) -f- !endif CC1 = -c CC2 = -o CCARG = +$(OBJDIR)\bcc.cfg # implicit rules: # Without the following, the implicit rule in BUILTINS.MAK is picked up # for a rule for .c.obj rather than the local implicit rule .SUFFIXES .SUFFIXES .c .obj .path.c = . {.}.c{$(OBJDIR)}.obj: $(CC) $(CCARG) $(CC1) -n$(OBJDIR)\ {$< } .cpp.obj: $(CC) $(CCARG) $(CC1) $(CC2)$@ $*.cpp !if ($(OSTYPE)==DOS16) !else # win32: vimmain = \ $(OBJDIR)\os_w32exe.obj !if ("$(VIMDLL)"=="yes") vimwinmain = \ $(OBJDIR)\os_w32dll.obj !else vimwinmain = \ $(OBJDIR)\os_w32exe.obj !endif !endif vimobj = \ $(OBJDIR)\blowfish.obj \ $(OBJDIR)\buffer.obj \ $(OBJDIR)\charset.obj \ $(OBJDIR)\diff.obj \ $(OBJDIR)\digraph.obj \ $(OBJDIR)\edit.obj \ $(OBJDIR)\eval.obj \ $(OBJDIR)\ex_cmds.obj \ $(OBJDIR)\ex_cmds2.obj \ $(OBJDIR)\ex_docmd.obj \ $(OBJDIR)\ex_eval.obj \ $(OBJDIR)\ex_getln.obj \ $(OBJDIR)\fileio.obj \ $(OBJDIR)\fold.obj \ $(OBJDIR)\getchar.obj \ $(OBJDIR)\hardcopy.obj \ $(OBJDIR)\hashtab.obj \ $(OBJDIR)\main.obj \ $(OBJDIR)\mark.obj \ $(OBJDIR)\memfile.obj \ $(OBJDIR)\memline.obj \ $(OBJDIR)\menu.obj \ $(OBJDIR)\message.obj \ $(OBJDIR)\misc1.obj \ $(OBJDIR)\misc2.obj \ $(OBJDIR)\move.obj \ $(OBJDIR)\mbyte.obj \ $(OBJDIR)\normal.obj \ $(OBJDIR)\ops.obj \ $(OBJDIR)\option.obj \ $(OBJDIR)\popupmnu.obj \ $(OBJDIR)\quickfix.obj \ $(OBJDIR)\regexp.obj \ $(OBJDIR)\screen.obj \ $(OBJDIR)\search.obj \ $(OBJDIR)\sha256.obj \ $(OBJDIR)\spell.obj \ $(OBJDIR)\syntax.obj \ $(OBJDIR)\tag.obj \ $(OBJDIR)\term.obj \ $(OBJDIR)\ui.obj \ $(OBJDIR)\undo.obj \ $(OBJDIR)\version.obj \ $(OBJDIR)\window.obj \ $(OBJDIR)\pathdef.obj !if ("$(OLE)"=="yes") vimobj = $(vimobj) \ $(OBJDIR)\if_ole.obj !endif !ifdef LUA vimobj = $(vimobj) \ $(OBJDIR)\if_lua.obj !endif !ifdef PERL vimobj = $(vimobj) \ $(OBJDIR)\if_perl.obj !endif !ifdef PYTHON vimobj = $(vimobj) \ $(OBJDIR)\if_python.obj !endif !ifdef PYTHON3 vimobj = $(vimobj) \ $(OBJDIR)\if_python3.obj !endif !ifdef RUBY vimobj = $(vimobj) \ $(OBJDIR)\if_ruby.obj !endif !ifdef TCL vimobj = $(vimobj) \ $(OBJDIR)\if_tcl.obj !endif !if ("$(CSCOPE)"=="yes") vimobj = $(vimobj) \ $(OBJDIR)\if_cscope.obj !endif !if ("$(NETBEANS)"=="yes") vimobj = $(vimobj) \ $(OBJDIR)\netbeans.obj !endif !ifdef XPM vimobj = $(vimobj) \ $(OBJDIR)\xpm_w32.obj !endif !if ("$(VIMDLL)"=="yes") vimdllobj = $(vimobj) !if ("$(DEBUG)"=="yes") DLLTARGET = vim32d.dll !else DLLTARGET = vim32.dll !endif !else DLLTARGET = joebob !endif !if ("$(GUI)"=="yes") vimobj = $(vimobj) \ $(vimwinmain) \ $(OBJDIR)\gui.obj \ $(OBJDIR)\gui_beval.obj \ $(OBJDIR)\gui_w32.obj !endif !if ($(OSTYPE)==WIN32) vimobj = $(vimobj) \ $(OBJDIR)\os_win32.obj $(OBJDIR)\os_mswin.obj !elif ($(OSTYPE)==DOS16) vimobj = $(vimobj) \ $(OBJDIR)\os_msdos.obj !endif # Blab what we are going to do: MSG = Compiling $(OSTYPE) $(TARGET) $(OLETARGET), with: !if ("$(GUI)"=="yes") MSG = $(MSG) GUI !endif !if ("$(OLE)"=="yes") MSG = $(MSG) OLE !endif !if ("$(USEDLL)"=="yes") MSG = $(MSG) USEDLL !endif !if ("$(VIMDLL)"=="yes") MSG = $(MSG) VIMDLL !endif !if ("$(FASTCALL)"=="yes") MSG = $(MSG) FASTCALL !endif !if ("$(MBYTE)"=="yes") MSG = $(MSG) MBYTE !endif !if ("$(IME)"=="yes") MSG = $(MSG) IME ! if "$(DYNAMIC_IME)" == "yes" MSG = $(MSG)(dynamic) ! endif !endif !if ("$(GETTEXT)"=="yes") MSG = $(MSG) GETTEXT !endif !if ("$(ICONV)"=="yes") MSG = $(MSG) ICONV !endif !if ("$(DEBUG)"=="yes") MSG = $(MSG) DEBUG !endif !if ("$(CODEGUARD)"=="yes") MSG = $(MSG) CODEGUARD !endif !if ("$(CSCOPE)"=="yes") MSG = $(MSG) CSCOPE !endif !if ("$(NETBEANS)"=="yes") MSG = $(MSG) NETBEANS !endif !ifdef XPM MSG = $(MSG) XPM !endif !ifdef LUA MSG = $(MSG) LUA ! if "$(DYNAMIC_LUA)" == "yes" MSG = $(MSG)(dynamic) ! endif !endif !ifdef PERL MSG = $(MSG) PERL ! if "$(DYNAMIC_PERL)" == "yes" MSG = $(MSG)(dynamic) ! endif !endif !ifdef PYTHON MSG = $(MSG) PYTHON ! if "$(DYNAMIC_PYTHON)" == "yes" MSG = $(MSG)(dynamic) ! endif !endif !ifdef PYTHON3 MSG = $(MSG) PYTHON3 ! if "$(DYNAMIC_PYTHON3)" == "yes" MSG = $(MSG)(dynamic) ! endif !endif !ifdef RUBY MSG = $(MSG) RUBY ! if "$(DYNAMIC_RUBY)" == "yes" MSG = $(MSG)(dynamic) ! endif !endif !ifdef TCL MSG = $(MSG) TCL ! if "$(DYNAMIC_TCL)" == "yes" MSG = $(MSG)(dynamic) ! endif !endif MSG = $(MSG) cpu=$(CPUARG) MSG = $(MSG) Align=$(ALIGNARG) !message $(MSG) !if ($(OSTYPE)==DOS16) TARGETS = $(TARGET) !else !if ("$(VIMDLL)"=="yes") TARGETS = $(DLLTARGET) !endif TARGETS = $(TARGETS) $(TARGET) !endif # Targets: all: vim vimrun.exe install.exe xxd uninstal.exe GvimExt/gvimext.dll vim: $(OSTYPE) $(OBJDIR) $(OBJDIR)\bcc.cfg $(TARGETS) @if exist $(OBJDIR)\version.obj del $(OBJDIR)\version.obj @if exist auto\pathdef.c del auto\pathdef.c $(OSTYPE): -@md $(OSTYPE) $(OBJDIR): -@md $(OBJDIR) xxd: @cd xxd $(MAKE) /f Make_bc5.mak BOR="$(BOR)" BCC="$(CC)" @cd .. GvimExt/gvimext.dll: GvimExt/gvimext.cpp GvimExt/gvimext.rc GvimExt/gvimext.h cd GvimExt $(MAKE) /f Make_bc5.mak USEDLL=$(USEDLL) BOR=$(BOR) cd .. install.exe: dosinst.c $(OBJDIR)\bcc.cfg !if ($(OSTYPE)==WIN32) $(CC) $(CCARG) -WC -DWIN32 -einstall dosinst.c !else $(CC) $(CCARG) -WC -einstall dosinst.c !endif uninstal.exe: uninstal.c $(OBJDIR)\bcc.cfg !if ($(OSTYPE)==WIN32) $(CC) $(CCARG) -WC -DWIN32 -O2 -euninstal uninstal.c !else $(CC) $(CCARG) -WC -O2 -euninstal uninstal.c !endif clean: !if "$(OS)" == "Windows_NT" # For Windows NT/2000, doesn't work on Windows 95/98... # $(COMSPEC) needed to ensure rmdir.exe is not run -@$(COMSPEC) /C rmdir /Q /S $(OBJDIR) !else # For Windows 95/98, doesn't work on Windows NT/2000... -@deltree /y $(OBJDIR) !endif -@del *.res -@del vim32*.dll -@del vim32*.lib -@del *vim*.exe -@del *install*.exe -@del *.csm -@del *.map -@del *.ilc -@del *.ild -@del *.ilf -@del *.ils -@del *.tds !ifdef LUA -@del lua.lib !endif !ifdef PERL -@del perl.lib !endif !ifdef PYTHON -@del python.lib !endif !ifdef PYTHON3 -@del python3.lib !endif !ifdef RUBY -@del ruby.lib !endif !ifdef TCL -@del tcl.lib !endif !ifdef XPM -@del xpm.lib !endif cd xxd $(MAKE) /f Make_bc5.mak BOR="$(BOR)" clean cd .. cd GvimExt $(MAKE) /f Make_bc5.mak BOR="$(BOR)" clean cd .. $(DLLTARGET): $(OBJDIR) $(vimdllobj) $(LINK) @&&| $(LFLAGSDLL) + c0d32.obj + $(vimdllobj) $<,$* !if ("$(CODEGUARD)"=="yes") cg32.lib+ !endif # $(OSTYPE)==WIN32 causes os_mswin.c compilation. FEAT_SHORTCUT in it needs OLE !if ("$(OLE)"=="yes" || $(OSTYPE)==WIN32) ole2w32.lib + !endif !if ($(OSTYPE)==WIN32) import32.lib+ !ifdef LUA $(LUA_LIB_FLAG)lua.lib+ !endif !ifdef PERL $(PERL_LIB_FLAG)perl.lib+ !endif !ifdef PYTHON $(PYTHON_LIB_FLAG)python.lib+ !endif !ifdef PYTHON3 $(PYTHON3_LIB_FLAG)python3.lib+ !endif !ifdef RUBY $(RUBY_LIB_FLAG)ruby.lib+ !endif !ifdef TCL $(TCL_LIB_FLAG)tcl.lib+ !endif !ifdef XPM xpm.lib+ !endif !if ("$(USEDLL)"=="yes") cw32i.lib !else cw32.lib !endif vim.def !else cl.lib !endif | !if ("$(VIMDLL)"=="yes") $(TARGET): $(OBJDIR) $(DLLTARGET) $(vimmain) $(OBJDIR)\$(RESFILE) !else $(TARGET): $(OBJDIR) $(vimobj) $(OBJDIR)\$(RESFILE) !endif $(LINK) @&&| $(LFLAGS) + $(STARTUPOBJ) + !if ("$(VIMDLL)"=="yes") $(vimmain) !else $(vimobj) !endif $<,$* !if ($(OSTYPE)==WIN32) !if ("$(CODEGUARD)"=="yes") cg32.lib+ !endif # $(OSTYPE)==WIN32 causes os_mswin.c compilation. FEAT_SHORTCUT in it needs OLE !if ("$(OLE)"=="yes" || $(OSTYPE)==WIN32) ole2w32.lib + !endif import32.lib+ !ifdef LUA $(LUA_LIB_FLAG)lua.lib+ !endif !ifdef PERL $(PERL_LIB_FLAG)perl.lib+ !endif !ifdef PYTHON $(PYTHON_LIB_FLAG)python.lib+ !endif !ifdef PYTHON3 $(PYTHON3_LIB_FLAG)python3.lib+ !endif !ifdef RUBY $(RUBY_LIB_FLAG)ruby.lib+ !endif !ifdef TCL $(TCL_LIB_FLAG)tcl.lib+ !endif !ifdef XPM xpm.lib+ !endif !if ("$(USEDLL)"=="yes") cw32i.lib !else cw32.lib !endif $(OBJDIR)\$(RESFILE) !else emu.lib + cl.lib !endif | test: cd testdir $(MAKE) /NOLOGO -f Make_dos.mak win32 cd .. $(OBJDIR)\ex_docmd.obj: ex_docmd.c ex_cmds.h $(OBJDIR)\ex_eval.obj: ex_eval.c ex_cmds.h $(OBJDIR)\if_ole.obj: if_ole.cpp $(OBJDIR)\if_lua.obj: if_lua.c lua.lib $(CC) $(CCARG) $(CC1) $(CC2)$@ -pc if_lua.c $(OBJDIR)\if_perl.obj: if_perl.c perl.lib $(CC) $(CCARG) $(CC1) $(CC2)$@ -pc if_perl.c if_perl.c: if_perl.xs typemap $(PERL)\bin\perl.exe $(PERL)\lib\ExtUtils\xsubpp -prototypes -typemap \ $(PERL)\lib\ExtUtils\typemap if_perl.xs > $@ $(OBJDIR)\if_python.obj: if_python.c python.lib $(CC) -I$(PYTHON)\include $(CCARG) $(CC1) $(CC2)$@ -pc if_python.c $(OBJDIR)\if_python3.obj: if_python3.c python3.lib $(CC) -I$(PYTHON3)\include $(CCARG) $(CC1) $(CC2)$@ -pc if_python3.c $(OBJDIR)\if_ruby.obj: if_ruby.c ruby.lib $(CC) $(CCARG) $(CC1) $(CC2)$@ -pc if_ruby.c $(OBJDIR)\if_tcl.obj: if_tcl.c tcl.lib $(CC) $(CCARG) $(CC1) $(CC2)$@ -pc if_tcl.c $(OBJDIR)\xpm_w32.obj: xpm_w32.c xpm.lib $(CC) $(CCARG) $(CC1) $(CC2)$@ -pc xpm_w32.c $(OBJDIR)\netbeans.obj: netbeans.c $(NBDEBUG_DEP) $(CC) $(CCARG) $(CC1) $(CC2)$@ netbeans.c $(OBJDIR)\vim.res: vim.rc version.h tools.bmp tearoff.bmp \ vim.ico vim_error.ico vim_alert.ico vim_info.ico vim_quest.ico $(BRC) -fo$(OBJDIR)\vim.res -i $(BOR)\include -w32 -r vim.rc @&&| $(DEFINES) | $(OBJDIR)\pathdef.obj: auto\pathdef.c $(CC) $(CCARG) $(CC1) $(CC2)$@ auto\pathdef.c # Need to escape both quotes and backslashes in $INTERP_DEFINES INTERP_DEFINES_ESC_BKS=$(INTERP_DEFINES:\=\\) INTERP_DEFINES_ESC=$(INTERP_DEFINES_ESC_BKS:"=\") # Note: the silly /*"*/ below are there to trick make into accepting # the # character as something other than a comment without messing up # the preprocessor directive. auto\pathdef.c:: -@md auto @echo creating auto/pathdef.c @copy /y &&| /* pathdef.c */ /*"*/#include "vim.h"/*"*/ char_u *default_vim_dir = (char_u *)"$(VIMRCLOC:\=\\)"; char_u *default_vimruntime_dir = (char_u *)"$(VIMRUNTIMEDIR:\=\\)"; char_u *all_cflags = (char_u *)"$(CC:\=\\) $(CFLAGS:\=\\) $(DEFINES) $(MBDEFINES) $(INTERP_DEFINES_ESC) $(OPT) $(EXETYPE) $(CPUARG) $(ALIGNARG) $(DEBUG_FLAG) $(CODEGUARD_FLAG)"; char_u *all_lflags = (char_u *)"$(LINK:\=\\) $(LFLAGS:\=\\)"; char_u *compiled_user = (char_u *)"$(USERNAME)"; char_u *compiled_sys = (char_u *)"$(USERDOMAIN)"; | auto\pathdef.c lua.lib: $(LUA)\lib\lua$(LUA_VER).lib coff2omf $(LUA)\lib\lua$(LUA_VER).lib $@ perl.lib: $(PERL)\lib\CORE\perl$(PERL_VER).lib coff2omf $(PERL)\lib\CORE\perl$(PERL_VER).lib $@ python.lib: $(PYTHON)\libs\python$(PYTHON_VER).lib coff2omf $(PYTHON)\libs\python$(PYTHON_VER).lib $@ python3.lib: $(PYTHON3)\libs\python$(PYTHON3_VER).lib coff2omf $(PYTHON3)\libs\python$(PYTHON3_VER).lib $@ ruby.lib: $(RUBY)\lib\$(RUBY_INSTALL_NAME).lib coff2omf $(RUBY)\lib\$(RUBY_INSTALL_NAME).lib $@ # For some reason, the coff2omf method doesn't work on libXpm.lib, so # we have to manually generate an import library straight from the DLL. xpm.lib: $(XPM)\lib\libXpm.lib implib -a $@ $(XPM)\bin\libXpm.dll tcl.lib: $(TCL_LIB) !if ("$(DYNAMIC_TCL)" == "yes") copy $(TCL_LIB) $@ !else coff2omf $(TCL_LIB) $@ !endif !if ("$(DYNAMIC_TCL)" == "yes") tclstub$(TCL_VER)-bor.lib: -@IF NOT EXIST $@ ECHO You must download tclstub$(TCL_VER)-bor.lib separately and\ place it in the src directory in order to compile a dynamic TCL-enabled\ (g)vim with the Borland compiler. You can get the tclstub$(TCL_VER)-bor.lib file\ at http://mywebpage.netscape.com/sharppeople/vim/tclstub$(TCL_VER)-bor.lib !endif # vimrun.exe: vimrun.exe: vimrun.c !if ("$(USEDLL)"=="yes") $(CC) -WC -O1 -I$(INCLUDE) -L$(LIB) -D_RTLDLL vimrun.c cw32mti.lib !else $(CC) -WC -O1 -I$(INCLUDE) -L$(LIB) vimrun.c !endif # The dependency on $(OBJDIR) is to have bcc.cfg generated each time. $(OBJDIR)\bcc.cfg: Make_bc5.mak $(OBJDIR) copy /y &&| $(CFLAGS) -L$(LIB) $(DEFINES) $(MBDEFINES) $(INTERP_DEFINES) $(EXETYPE) $(DEBUG_FLAG) $(OPT) $(CODEGUARD_FLAG) $(CPUARG) $(ALIGNARG) | $@ # vi:set sts=4 sw=4:
zyz2011-vim
src/Make_bc5.mak
Makefile
gpl2
26,532
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * syntax.c: code for syntax highlighting */ #include "vim.h" /* * Structure that stores information about a highlight group. * The ID of a highlight group is also called group ID. It is the index in * the highlight_ga array PLUS ONE. */ struct hl_group { char_u *sg_name; /* highlight group name */ char_u *sg_name_u; /* uppercase of sg_name */ /* for normal terminals */ int sg_term; /* "term=" highlighting attributes */ char_u *sg_start; /* terminal string for start highl */ char_u *sg_stop; /* terminal string for stop highl */ int sg_term_attr; /* Screen attr for term mode */ /* for color terminals */ int sg_cterm; /* "cterm=" highlighting attr */ int sg_cterm_bold; /* bold attr was set for light color */ int sg_cterm_fg; /* terminal fg color number + 1 */ int sg_cterm_bg; /* terminal bg color number + 1 */ int sg_cterm_attr; /* Screen attr for color term mode */ #ifdef FEAT_GUI /* for when using the GUI */ guicolor_T sg_gui_fg; /* GUI foreground color handle */ guicolor_T sg_gui_bg; /* GUI background color handle */ guicolor_T sg_gui_sp; /* GUI special color handle */ GuiFont sg_font; /* GUI font handle */ #ifdef FEAT_XFONTSET GuiFontset sg_fontset; /* GUI fontset handle */ #endif char_u *sg_font_name; /* GUI font or fontset name */ int sg_gui_attr; /* Screen attr for GUI mode */ #endif #if defined(FEAT_GUI) || defined(FEAT_EVAL) /* Store the sp color name for the GUI or synIDattr() */ int sg_gui; /* "gui=" highlighting attributes */ char_u *sg_gui_fg_name;/* GUI foreground color name */ char_u *sg_gui_bg_name;/* GUI background color name */ char_u *sg_gui_sp_name;/* GUI special color name */ #endif int sg_link; /* link to this highlight group ID */ int sg_set; /* combination of SG_* flags */ #ifdef FEAT_EVAL scid_T sg_scriptID; /* script in which the group was last set */ #endif }; #define SG_TERM 1 /* term has been set */ #define SG_CTERM 2 /* cterm has been set */ #define SG_GUI 4 /* gui has been set */ #define SG_LINK 8 /* link has been set */ static garray_T highlight_ga; /* highlight groups for 'highlight' option */ #define HL_TABLE() ((struct hl_group *)((highlight_ga.ga_data))) #define MAX_HL_ID 20000 /* maximum value for a highlight ID. */ #ifdef FEAT_CMDL_COMPL /* Flags to indicate an additional string for highlight name completion. */ static int include_none = 0; /* when 1 include "None" */ static int include_default = 0; /* when 1 include "default" */ static int include_link = 0; /* when 2 include "link" and "clear" */ #endif /* * The "term", "cterm" and "gui" arguments can be any combination of the * following names, separated by commas (but no spaces!). */ static char *(hl_name_table[]) = {"bold", "standout", "underline", "undercurl", "italic", "reverse", "inverse", "NONE"}; static int hl_attr_table[] = {HL_BOLD, HL_STANDOUT, HL_UNDERLINE, HL_UNDERCURL, HL_ITALIC, HL_INVERSE, HL_INVERSE, 0}; static int get_attr_entry __ARGS((garray_T *table, attrentry_T *aep)); static void syn_unadd_group __ARGS((void)); static void set_hl_attr __ARGS((int idx)); static void highlight_list_one __ARGS((int id)); static int highlight_list_arg __ARGS((int id, int didh, int type, int iarg, char_u *sarg, char *name)); static int syn_add_group __ARGS((char_u *name)); static int syn_list_header __ARGS((int did_header, int outlen, int id)); static int hl_has_settings __ARGS((int idx, int check_link)); static void highlight_clear __ARGS((int idx)); #ifdef FEAT_GUI static void gui_do_one_color __ARGS((int idx, int do_menu, int do_tooltip)); static int set_group_colors __ARGS((char_u *name, guicolor_T *fgp, guicolor_T *bgp, int do_menu, int use_norm, int do_tooltip)); static guicolor_T color_name2handle __ARGS((char_u *name)); static GuiFont font_name2handle __ARGS((char_u *name)); # ifdef FEAT_XFONTSET static GuiFontset fontset_name2handle __ARGS((char_u *name, int fixed_width)); # endif static void hl_do_font __ARGS((int idx, char_u *arg, int do_normal, int do_menu, int do_tooltip)); #endif /* * An attribute number is the index in attr_table plus ATTR_OFF. */ #define ATTR_OFF (HL_ALL + 1) #if defined(FEAT_SYN_HL) || defined(PROTO) #define SYN_NAMELEN 50 /* maximum length of a syntax name */ /* different types of offsets that are possible */ #define SPO_MS_OFF 0 /* match start offset */ #define SPO_ME_OFF 1 /* match end offset */ #define SPO_HS_OFF 2 /* highl. start offset */ #define SPO_HE_OFF 3 /* highl. end offset */ #define SPO_RS_OFF 4 /* region start offset */ #define SPO_RE_OFF 5 /* region end offset */ #define SPO_LC_OFF 6 /* leading context offset */ #define SPO_COUNT 7 static char *(spo_name_tab[SPO_COUNT]) = {"ms=", "me=", "hs=", "he=", "rs=", "re=", "lc="}; /* * The patterns that are being searched for are stored in a syn_pattern. * A match item consists of one pattern. * A start/end item consists of n start patterns and m end patterns. * A start/skip/end item consists of n start patterns, one skip pattern and m * end patterns. * For the latter two, the patterns are always consecutive: start-skip-end. * * A character offset can be given for the matched text (_m_start and _m_end) * and for the actually highlighted text (_h_start and _h_end). */ typedef struct syn_pattern { char sp_type; /* see SPTYPE_ defines below */ char sp_syncing; /* this item used for syncing */ int sp_flags; /* see HL_ defines below */ #ifdef FEAT_CONCEAL int sp_cchar; /* conceal substitute character */ #endif struct sp_syn sp_syn; /* struct passed to in_id_list() */ short sp_syn_match_id; /* highlight group ID of pattern */ char_u *sp_pattern; /* regexp to match, pattern */ regprog_T *sp_prog; /* regexp to match, program */ int sp_ic; /* ignore-case flag for sp_prog */ short sp_off_flags; /* see below */ int sp_offsets[SPO_COUNT]; /* offsets */ short *sp_cont_list; /* cont. group IDs, if non-zero */ short *sp_next_list; /* next group IDs, if non-zero */ int sp_sync_idx; /* sync item index (syncing only) */ int sp_line_id; /* ID of last line where tried */ int sp_startcol; /* next match in sp_line_id line */ } synpat_T; /* The sp_off_flags are computed like this: * offset from the start of the matched text: (1 << SPO_XX_OFF) * offset from the end of the matched text: (1 << (SPO_XX_OFF + SPO_COUNT)) * When both are present, only one is used. */ #define SPTYPE_MATCH 1 /* match keyword with this group ID */ #define SPTYPE_START 2 /* match a regexp, start of item */ #define SPTYPE_END 3 /* match a regexp, end of item */ #define SPTYPE_SKIP 4 /* match a regexp, skip within item */ #define SYN_ITEMS(buf) ((synpat_T *)((buf)->b_syn_patterns.ga_data)) #define NONE_IDX -2 /* value of sp_sync_idx for "NONE" */ /* * Flags for b_syn_sync_flags: */ #define SF_CCOMMENT 0x01 /* sync on a C-style comment */ #define SF_MATCH 0x02 /* sync by matching a pattern */ #define SYN_STATE_P(ssp) ((bufstate_T *)((ssp)->ga_data)) #define MAXKEYWLEN 80 /* maximum length of a keyword */ /* * The attributes of the syntax item that has been recognized. */ static int current_attr = 0; /* attr of current syntax word */ #ifdef FEAT_EVAL static int current_id = 0; /* ID of current char for syn_get_id() */ static int current_trans_id = 0; /* idem, transparency removed */ #endif #ifdef FEAT_CONCEAL static int current_flags = 0; static int current_seqnr = 0; static int current_sub_char = 0; #endif typedef struct syn_cluster_S { char_u *scl_name; /* syntax cluster name */ char_u *scl_name_u; /* uppercase of scl_name */ short *scl_list; /* IDs in this syntax cluster */ } syn_cluster_T; /* * Methods of combining two clusters */ #define CLUSTER_REPLACE 1 /* replace first list with second */ #define CLUSTER_ADD 2 /* add second list to first */ #define CLUSTER_SUBTRACT 3 /* subtract second list from first */ #define SYN_CLSTR(buf) ((syn_cluster_T *)((buf)->b_syn_clusters.ga_data)) /* * Syntax group IDs have different types: * 0 - 19999 normal syntax groups * 20000 - 20999 ALLBUT indicator (current_syn_inc_tag added) * 21000 - 21999 TOP indicator (current_syn_inc_tag added) * 22000 - 22999 CONTAINED indicator (current_syn_inc_tag added) * 23000 - 32767 cluster IDs (subtract SYNID_CLUSTER for the cluster ID) */ #define SYNID_ALLBUT MAX_HL_ID /* syntax group ID for contains=ALLBUT */ #define SYNID_TOP 21000 /* syntax group ID for contains=TOP */ #define SYNID_CONTAINED 22000 /* syntax group ID for contains=CONTAINED */ #define SYNID_CLUSTER 23000 /* first syntax group ID for clusters */ #define MAX_SYN_INC_TAG 999 /* maximum before the above overflow */ #define MAX_CLUSTER_ID (32767 - SYNID_CLUSTER) /* * Annoying Hack(TM): ":syn include" needs this pointer to pass to * expand_filename(). Most of the other syntax commands don't need it, so * instead of passing it to them, we stow it here. */ static char_u **syn_cmdlinep; /* * Another Annoying Hack(TM): To prevent rules from other ":syn include"'d * files from leaking into ALLBUT lists, we assign a unique ID to the * rules in each ":syn include"'d file. */ static int current_syn_inc_tag = 0; static int running_syn_inc_tag = 0; /* * In a hashtable item "hi_key" points to "keyword" in a keyentry. * This avoids adding a pointer to the hashtable item. * KE2HIKEY() converts a var pointer to a hashitem key pointer. * HIKEY2KE() converts a hashitem key pointer to a var pointer. * HI2KE() converts a hashitem pointer to a var pointer. */ static keyentry_T dumkey; #define KE2HIKEY(kp) ((kp)->keyword) #define HIKEY2KE(p) ((keyentry_T *)((p) - (dumkey.keyword - (char_u *)&dumkey))) #define HI2KE(hi) HIKEY2KE((hi)->hi_key) /* * To reduce the time spent in keepend(), remember at which level in the state * stack the first item with "keepend" is present. When "-1", there is no * "keepend" on the stack. */ static int keepend_level = -1; /* * For the current state we need to remember more than just the idx. * When si_m_endpos.lnum is 0, the items other than si_idx are unknown. * (The end positions have the column number of the next char) */ typedef struct state_item { int si_idx; /* index of syntax pattern or KEYWORD_IDX */ int si_id; /* highlight group ID for keywords */ int si_trans_id; /* idem, transparency removed */ int si_m_lnum; /* lnum of the match */ int si_m_startcol; /* starting column of the match */ lpos_T si_m_endpos; /* just after end posn of the match */ lpos_T si_h_startpos; /* start position of the highlighting */ lpos_T si_h_endpos; /* end position of the highlighting */ lpos_T si_eoe_pos; /* end position of end pattern */ int si_end_idx; /* group ID for end pattern or zero */ int si_ends; /* if match ends before si_m_endpos */ int si_attr; /* attributes in this state */ long si_flags; /* HL_HAS_EOL flag in this state, and * HL_SKIP* for si_next_list */ #ifdef FEAT_CONCEAL int si_seqnr; /* sequence number */ int si_cchar; /* substitution character for conceal */ #endif short *si_cont_list; /* list of contained groups */ short *si_next_list; /* nextgroup IDs after this item ends */ reg_extmatch_T *si_extmatch; /* \z(...\) matches from start * pattern */ } stateitem_T; #define KEYWORD_IDX -1 /* value of si_idx for keywords */ #define ID_LIST_ALL (short *)-1 /* valid of si_cont_list for containing all but contained groups */ #ifdef FEAT_CONCEAL static int next_seqnr = 0; /* value to use for si_seqnr */ #endif /* * Struct to reduce the number of arguments to get_syn_options(), it's used * very often. */ typedef struct { int flags; /* flags for contained and transparent */ int keyword; /* TRUE for ":syn keyword" */ int *sync_idx; /* syntax item for "grouphere" argument, NULL if not allowed */ char has_cont_list; /* TRUE if "cont_list" can be used */ short *cont_list; /* group IDs for "contains" argument */ short *cont_in_list; /* group IDs for "containedin" argument */ short *next_list; /* group IDs for "nextgroup" argument */ } syn_opt_arg_T; /* * The next possible match in the current line for any pattern is remembered, * to avoid having to try for a match in each column. * If next_match_idx == -1, not tried (in this line) yet. * If next_match_col == MAXCOL, no match found in this line. * (All end positions have the column of the char after the end) */ static int next_match_col; /* column for start of next match */ static lpos_T next_match_m_endpos; /* position for end of next match */ static lpos_T next_match_h_startpos; /* pos. for highl. start of next match */ static lpos_T next_match_h_endpos; /* pos. for highl. end of next match */ static int next_match_idx; /* index of matched item */ static long next_match_flags; /* flags for next match */ static lpos_T next_match_eos_pos; /* end of start pattn (start region) */ static lpos_T next_match_eoe_pos; /* pos. for end of end pattern */ static int next_match_end_idx; /* ID of group for end pattn or zero */ static reg_extmatch_T *next_match_extmatch = NULL; /* * A state stack is an array of integers or stateitem_T, stored in a * garray_T. A state stack is invalid if it's itemsize entry is zero. */ #define INVALID_STATE(ssp) ((ssp)->ga_itemsize == 0) #define VALID_STATE(ssp) ((ssp)->ga_itemsize != 0) /* * The current state (within the line) of the recognition engine. * When current_state.ga_itemsize is 0 the current state is invalid. */ static win_T *syn_win; /* current window for highlighting */ static buf_T *syn_buf; /* current buffer for highlighting */ static synblock_T *syn_block; /* current buffer for highlighting */ static linenr_T current_lnum = 0; /* lnum of current state */ static colnr_T current_col = 0; /* column of current state */ static int current_state_stored = 0; /* TRUE if stored current state * after setting current_finished */ static int current_finished = 0; /* current line has been finished */ static garray_T current_state /* current stack of state_items */ = {0, 0, 0, 0, NULL}; static short *current_next_list = NULL; /* when non-zero, nextgroup list */ static int current_next_flags = 0; /* flags for current_next_list */ static int current_line_id = 0; /* unique number for current line */ #define CUR_STATE(idx) ((stateitem_T *)(current_state.ga_data))[idx] static void syn_sync __ARGS((win_T *wp, linenr_T lnum, synstate_T *last_valid)); static int syn_match_linecont __ARGS((linenr_T lnum)); static void syn_start_line __ARGS((void)); static void syn_update_ends __ARGS((int startofline)); static void syn_stack_alloc __ARGS((void)); static int syn_stack_cleanup __ARGS((void)); static void syn_stack_free_entry __ARGS((synblock_T *block, synstate_T *p)); static synstate_T *syn_stack_find_entry __ARGS((linenr_T lnum)); static synstate_T *store_current_state __ARGS((void)); static void load_current_state __ARGS((synstate_T *from)); static void invalidate_current_state __ARGS((void)); static int syn_stack_equal __ARGS((synstate_T *sp)); static void validate_current_state __ARGS((void)); static int syn_finish_line __ARGS((int syncing)); static int syn_current_attr __ARGS((int syncing, int displaying, int *can_spell, int keep_state)); static int did_match_already __ARGS((int idx, garray_T *gap)); static stateitem_T *push_next_match __ARGS((stateitem_T *cur_si)); static void check_state_ends __ARGS((void)); static void update_si_attr __ARGS((int idx)); static void check_keepend __ARGS((void)); static void update_si_end __ARGS((stateitem_T *sip, int startcol, int force)); static short *copy_id_list __ARGS((short *list)); static int in_id_list __ARGS((stateitem_T *item, short *cont_list, struct sp_syn *ssp, int contained)); static int push_current_state __ARGS((int idx)); static void pop_current_state __ARGS((void)); static void syn_stack_apply_changes_block __ARGS((synblock_T *block, buf_T *buf)); static void find_endpos __ARGS((int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_endpos, long *flagsp, lpos_T *end_endpos, int *end_idx, reg_extmatch_T *start_ext)); static void clear_syn_state __ARGS((synstate_T *p)); static void clear_current_state __ARGS((void)); static void limit_pos __ARGS((lpos_T *pos, lpos_T *limit)); static void limit_pos_zero __ARGS((lpos_T *pos, lpos_T *limit)); static void syn_add_end_off __ARGS((lpos_T *result, regmmatch_T *regmatch, synpat_T *spp, int idx, int extra)); static void syn_add_start_off __ARGS((lpos_T *result, regmmatch_T *regmatch, synpat_T *spp, int idx, int extra)); static char_u *syn_getcurline __ARGS((void)); static int syn_regexec __ARGS((regmmatch_T *rmp, linenr_T lnum, colnr_T col)); static int check_keyword_id __ARGS((char_u *line, int startcol, int *endcol, long *flags, short **next_list, stateitem_T *cur_si, int *ccharp)); static void syn_cmd_case __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_spell __ARGS((exarg_T *eap, int syncing)); static void syntax_sync_clear __ARGS((void)); static void syn_remove_pattern __ARGS((synblock_T *block, int idx)); static void syn_clear_pattern __ARGS((synblock_T *block, int i)); static void syn_clear_cluster __ARGS((synblock_T *block, int i)); static void syn_cmd_clear __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_conceal __ARGS((exarg_T *eap, int syncing)); static void syn_clear_one __ARGS((int id, int syncing)); static void syn_cmd_on __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_enable __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_reset __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_manual __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_off __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_onoff __ARGS((exarg_T *eap, char *name)); static void syn_cmd_list __ARGS((exarg_T *eap, int syncing)); static void syn_lines_msg __ARGS((void)); static void syn_match_msg __ARGS((void)); static void syn_stack_free_block __ARGS((synblock_T *block)); static void syn_list_one __ARGS((int id, int syncing, int link_only)); static void syn_list_cluster __ARGS((int id)); static void put_id_list __ARGS((char_u *name, short *list, int attr)); static void put_pattern __ARGS((char *s, int c, synpat_T *spp, int attr)); static int syn_list_keywords __ARGS((int id, hashtab_T *ht, int did_header, int attr)); static void syn_clear_keyword __ARGS((int id, hashtab_T *ht)); static void clear_keywtab __ARGS((hashtab_T *ht)); static void add_keyword __ARGS((char_u *name, int id, int flags, short *cont_in_list, short *next_list, int conceal_char)); static char_u *get_group_name __ARGS((char_u *arg, char_u **name_end)); static char_u *get_syn_options __ARGS((char_u *arg, syn_opt_arg_T *opt, int *conceal_char)); static void syn_cmd_include __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_keyword __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_match __ARGS((exarg_T *eap, int syncing)); static void syn_cmd_region __ARGS((exarg_T *eap, int syncing)); #ifdef __BORLANDC__ static int _RTLENTRYF syn_compare_stub __ARGS((const void *v1, const void *v2)); #else static int syn_compare_stub __ARGS((const void *v1, const void *v2)); #endif static void syn_cmd_cluster __ARGS((exarg_T *eap, int syncing)); static int syn_scl_name2id __ARGS((char_u *name)); static int syn_scl_namen2id __ARGS((char_u *linep, int len)); static int syn_check_cluster __ARGS((char_u *pp, int len)); static int syn_add_cluster __ARGS((char_u *name)); static void init_syn_patterns __ARGS((void)); static char_u *get_syn_pattern __ARGS((char_u *arg, synpat_T *ci)); static void syn_cmd_sync __ARGS((exarg_T *eap, int syncing)); static int get_id_list __ARGS((char_u **arg, int keylen, short **list)); static void syn_combine_list __ARGS((short **clstr1, short **clstr2, int list_op)); static void syn_incl_toplevel __ARGS((int id, int *flagsp)); /* * Start the syntax recognition for a line. This function is normally called * from the screen updating, once for each displayed line. * The buffer is remembered in syn_buf, because get_syntax_attr() doesn't get * it. Careful: curbuf and curwin are likely to point to another buffer and * window. */ void syntax_start(wp, lnum) win_T *wp; linenr_T lnum; { synstate_T *p; synstate_T *last_valid = NULL; synstate_T *last_min_valid = NULL; synstate_T *sp, *prev = NULL; linenr_T parsed_lnum; linenr_T first_stored; int dist; static int changedtick = 0; /* remember the last change ID */ #ifdef FEAT_CONCEAL current_sub_char = NUL; #endif /* * After switching buffers, invalidate current_state. * Also do this when a change was made, the current state may be invalid * then. */ if (syn_block != wp->w_s || changedtick != syn_buf->b_changedtick) { invalidate_current_state(); syn_buf = wp->w_buffer; syn_block = wp->w_s; } changedtick = syn_buf->b_changedtick; syn_win = wp; /* * Allocate syntax stack when needed. */ syn_stack_alloc(); if (syn_block->b_sst_array == NULL) return; /* out of memory */ syn_block->b_sst_lasttick = display_tick; /* * If the state of the end of the previous line is useful, store it. */ if (VALID_STATE(&current_state) && current_lnum < lnum && current_lnum < syn_buf->b_ml.ml_line_count) { (void)syn_finish_line(FALSE); if (!current_state_stored) { ++current_lnum; (void)store_current_state(); } /* * If the current_lnum is now the same as "lnum", keep the current * state (this happens very often!). Otherwise invalidate * current_state and figure it out below. */ if (current_lnum != lnum) invalidate_current_state(); } else invalidate_current_state(); /* * Try to synchronize from a saved state in b_sst_array[]. * Only do this if lnum is not before and not to far beyond a saved state. */ if (INVALID_STATE(&current_state) && syn_block->b_sst_array != NULL) { /* Find last valid saved state before start_lnum. */ for (p = syn_block->b_sst_first; p != NULL; p = p->sst_next) { if (p->sst_lnum > lnum) break; if (p->sst_lnum <= lnum && p->sst_change_lnum == 0) { last_valid = p; if (p->sst_lnum >= lnum - syn_block->b_syn_sync_minlines) last_min_valid = p; } } if (last_min_valid != NULL) load_current_state(last_min_valid); } /* * If "lnum" is before or far beyond a line with a saved state, need to * re-synchronize. */ if (INVALID_STATE(&current_state)) { syn_sync(wp, lnum, last_valid); if (current_lnum == 1) /* First line is always valid, no matter "minlines". */ first_stored = 1; else /* Need to parse "minlines" lines before state can be considered * valid to store. */ first_stored = current_lnum + syn_block->b_syn_sync_minlines; } else first_stored = current_lnum; /* * Advance from the sync point or saved state until the current line. * Save some entries for syncing with later on. */ if (syn_block->b_sst_len <= Rows) dist = 999999; else dist = syn_buf->b_ml.ml_line_count / (syn_block->b_sst_len - Rows) + 1; while (current_lnum < lnum) { syn_start_line(); (void)syn_finish_line(FALSE); ++current_lnum; /* If we parsed at least "minlines" lines or started at a valid * state, the current state is considered valid. */ if (current_lnum >= first_stored) { /* Check if the saved state entry is for the current line and is * equal to the current state. If so, then validate all saved * states that depended on a change before the parsed line. */ if (prev == NULL) prev = syn_stack_find_entry(current_lnum - 1); if (prev == NULL) sp = syn_block->b_sst_first; else sp = prev; while (sp != NULL && sp->sst_lnum < current_lnum) sp = sp->sst_next; if (sp != NULL && sp->sst_lnum == current_lnum && syn_stack_equal(sp)) { parsed_lnum = current_lnum; prev = sp; while (sp != NULL && sp->sst_change_lnum <= parsed_lnum) { if (sp->sst_lnum <= lnum) /* valid state before desired line, use this one */ prev = sp; else if (sp->sst_change_lnum == 0) /* past saved states depending on change, break here. */ break; sp->sst_change_lnum = 0; sp = sp->sst_next; } load_current_state(prev); } /* Store the state at this line when it's the first one, the line * where we start parsing, or some distance from the previously * saved state. But only when parsed at least 'minlines'. */ else if (prev == NULL || current_lnum == lnum || current_lnum >= prev->sst_lnum + dist) prev = store_current_state(); } /* This can take a long time: break when CTRL-C pressed. The current * state will be wrong then. */ line_breakcheck(); if (got_int) { current_lnum = lnum; break; } } syn_start_line(); } /* * We cannot simply discard growarrays full of state_items or buf_states; we * have to manually release their extmatch pointers first. */ static void clear_syn_state(p) synstate_T *p; { int i; garray_T *gap; if (p->sst_stacksize > SST_FIX_STATES) { gap = &(p->sst_union.sst_ga); for (i = 0; i < gap->ga_len; i++) unref_extmatch(SYN_STATE_P(gap)[i].bs_extmatch); ga_clear(gap); } else { for (i = 0; i < p->sst_stacksize; i++) unref_extmatch(p->sst_union.sst_stack[i].bs_extmatch); } } /* * Cleanup the current_state stack. */ static void clear_current_state() { int i; stateitem_T *sip; sip = (stateitem_T *)(current_state.ga_data); for (i = 0; i < current_state.ga_len; i++) unref_extmatch(sip[i].si_extmatch); ga_clear(&current_state); } /* * Try to find a synchronisation point for line "lnum". * * This sets current_lnum and the current state. One of three methods is * used: * 1. Search backwards for the end of a C-comment. * 2. Search backwards for given sync patterns. * 3. Simply start on a given number of lines above "lnum". */ static void syn_sync(wp, start_lnum, last_valid) win_T *wp; linenr_T start_lnum; synstate_T *last_valid; { buf_T *curbuf_save; win_T *curwin_save; pos_T cursor_save; int idx; linenr_T lnum; linenr_T end_lnum; linenr_T break_lnum; int had_sync_point; stateitem_T *cur_si; synpat_T *spp; char_u *line; int found_flags = 0; int found_match_idx = 0; linenr_T found_current_lnum = 0; int found_current_col= 0; lpos_T found_m_endpos; colnr_T prev_current_col; /* * Clear any current state that might be hanging around. */ invalidate_current_state(); /* * Start at least "minlines" back. Default starting point for parsing is * there. * Start further back, to avoid that scrolling backwards will result in * resyncing for every line. Now it resyncs only one out of N lines, * where N is minlines * 1.5, or minlines * 2 if minlines is small. * Watch out for overflow when minlines is MAXLNUM. */ if (syn_block->b_syn_sync_minlines > start_lnum) start_lnum = 1; else { if (syn_block->b_syn_sync_minlines == 1) lnum = 1; else if (syn_block->b_syn_sync_minlines < 10) lnum = syn_block->b_syn_sync_minlines * 2; else lnum = syn_block->b_syn_sync_minlines * 3 / 2; if (syn_block->b_syn_sync_maxlines != 0 && lnum > syn_block->b_syn_sync_maxlines) lnum = syn_block->b_syn_sync_maxlines; if (lnum >= start_lnum) start_lnum = 1; else start_lnum -= lnum; } current_lnum = start_lnum; /* * 1. Search backwards for the end of a C-style comment. */ if (syn_block->b_syn_sync_flags & SF_CCOMMENT) { /* Need to make syn_buf the current buffer for a moment, to be able to * use find_start_comment(). */ curwin_save = curwin; curwin = wp; curbuf_save = curbuf; curbuf = syn_buf; /* * Skip lines that end in a backslash. */ for ( ; start_lnum > 1; --start_lnum) { line = ml_get(start_lnum - 1); if (*line == NUL || *(line + STRLEN(line) - 1) != '\\') break; } current_lnum = start_lnum; /* set cursor to start of search */ cursor_save = wp->w_cursor; wp->w_cursor.lnum = start_lnum; wp->w_cursor.col = 0; /* * If the line is inside a comment, need to find the syntax item that * defines the comment. * Restrict the search for the end of a comment to b_syn_sync_maxlines. */ if (find_start_comment((int)syn_block->b_syn_sync_maxlines) != NULL) { for (idx = syn_block->b_syn_patterns.ga_len; --idx >= 0; ) if (SYN_ITEMS(syn_block)[idx].sp_syn.id == syn_block->b_syn_sync_id && SYN_ITEMS(syn_block)[idx].sp_type == SPTYPE_START) { validate_current_state(); if (push_current_state(idx) == OK) update_si_attr(current_state.ga_len - 1); break; } } /* restore cursor and buffer */ wp->w_cursor = cursor_save; curwin = curwin_save; curbuf = curbuf_save; } /* * 2. Search backwards for given sync patterns. */ else if (syn_block->b_syn_sync_flags & SF_MATCH) { if (syn_block->b_syn_sync_maxlines != 0 && start_lnum > syn_block->b_syn_sync_maxlines) break_lnum = start_lnum - syn_block->b_syn_sync_maxlines; else break_lnum = 0; found_m_endpos.lnum = 0; found_m_endpos.col = 0; end_lnum = start_lnum; lnum = start_lnum; while (--lnum > break_lnum) { /* This can take a long time: break when CTRL-C pressed. */ line_breakcheck(); if (got_int) { invalidate_current_state(); current_lnum = start_lnum; break; } /* Check if we have run into a valid saved state stack now. */ if (last_valid != NULL && lnum == last_valid->sst_lnum) { load_current_state(last_valid); break; } /* * Check if the previous line has the line-continuation pattern. */ if (lnum > 1 && syn_match_linecont(lnum - 1)) continue; /* * Start with nothing on the state stack */ validate_current_state(); for (current_lnum = lnum; current_lnum < end_lnum; ++current_lnum) { syn_start_line(); for (;;) { had_sync_point = syn_finish_line(TRUE); /* * When a sync point has been found, remember where, and * continue to look for another one, further on in the line. */ if (had_sync_point && current_state.ga_len) { cur_si = &CUR_STATE(current_state.ga_len - 1); if (cur_si->si_m_endpos.lnum > start_lnum) { /* ignore match that goes to after where started */ current_lnum = end_lnum; break; } if (cur_si->si_idx < 0) { /* Cannot happen? */ found_flags = 0; found_match_idx = KEYWORD_IDX; } else { spp = &(SYN_ITEMS(syn_block)[cur_si->si_idx]); found_flags = spp->sp_flags; found_match_idx = spp->sp_sync_idx; } found_current_lnum = current_lnum; found_current_col = current_col; found_m_endpos = cur_si->si_m_endpos; /* * Continue after the match (be aware of a zero-length * match). */ if (found_m_endpos.lnum > current_lnum) { current_lnum = found_m_endpos.lnum; current_col = found_m_endpos.col; if (current_lnum >= end_lnum) break; } else if (found_m_endpos.col > current_col) current_col = found_m_endpos.col; else ++current_col; /* syn_current_attr() will have skipped the check for * an item that ends here, need to do that now. Be * careful not to go past the NUL. */ prev_current_col = current_col; if (syn_getcurline()[current_col] != NUL) ++current_col; check_state_ends(); current_col = prev_current_col; } else break; } } /* * If a sync point was encountered, break here. */ if (found_flags) { /* * Put the item that was specified by the sync point on the * state stack. If there was no item specified, make the * state stack empty. */ clear_current_state(); if (found_match_idx >= 0 && push_current_state(found_match_idx) == OK) update_si_attr(current_state.ga_len - 1); /* * When using "grouphere", continue from the sync point * match, until the end of the line. Parsing starts at * the next line. * For "groupthere" the parsing starts at start_lnum. */ if (found_flags & HL_SYNC_HERE) { if (current_state.ga_len) { cur_si = &CUR_STATE(current_state.ga_len - 1); cur_si->si_h_startpos.lnum = found_current_lnum; cur_si->si_h_startpos.col = found_current_col; update_si_end(cur_si, (int)current_col, TRUE); check_keepend(); } current_col = found_m_endpos.col; current_lnum = found_m_endpos.lnum; (void)syn_finish_line(FALSE); ++current_lnum; } else current_lnum = start_lnum; break; } end_lnum = lnum; invalidate_current_state(); } /* Ran into start of the file or exceeded maximum number of lines */ if (lnum <= break_lnum) { invalidate_current_state(); current_lnum = break_lnum + 1; } } validate_current_state(); } /* * Return TRUE if the line-continuation pattern matches in line "lnum". */ static int syn_match_linecont(lnum) linenr_T lnum; { regmmatch_T regmatch; if (syn_block->b_syn_linecont_prog != NULL) { regmatch.rmm_ic = syn_block->b_syn_linecont_ic; regmatch.regprog = syn_block->b_syn_linecont_prog; return syn_regexec(&regmatch, lnum, (colnr_T)0); } return FALSE; } /* * Prepare the current state for the start of a line. */ static void syn_start_line() { current_finished = FALSE; current_col = 0; /* * Need to update the end of a start/skip/end that continues from the * previous line and regions that have "keepend". */ if (current_state.ga_len > 0) { syn_update_ends(TRUE); check_state_ends(); } next_match_idx = -1; ++current_line_id; } /* * Check for items in the stack that need their end updated. * When "startofline" is TRUE the last item is always updated. * When "startofline" is FALSE the item with "keepend" is forcefully updated. */ static void syn_update_ends(startofline) int startofline; { stateitem_T *cur_si; int i; int seen_keepend; if (startofline) { /* Check for a match carried over from a previous line with a * contained region. The match ends as soon as the region ends. */ for (i = 0; i < current_state.ga_len; ++i) { cur_si = &CUR_STATE(i); if (cur_si->si_idx >= 0 && (SYN_ITEMS(syn_block)[cur_si->si_idx]).sp_type == SPTYPE_MATCH && cur_si->si_m_endpos.lnum < current_lnum) { cur_si->si_flags |= HL_MATCHCONT; cur_si->si_m_endpos.lnum = 0; cur_si->si_m_endpos.col = 0; cur_si->si_h_endpos = cur_si->si_m_endpos; cur_si->si_ends = TRUE; } } } /* * Need to update the end of a start/skip/end that continues from the * previous line. And regions that have "keepend", because they may * influence contained items. If we've just removed "extend" * (startofline == 0) then we should update ends of normal regions * contained inside "keepend" because "extend" could have extended * these "keepend" regions as well as contained normal regions. * Then check for items ending in column 0. */ i = current_state.ga_len - 1; if (keepend_level >= 0) for ( ; i > keepend_level; --i) if (CUR_STATE(i).si_flags & HL_EXTEND) break; seen_keepend = FALSE; for ( ; i < current_state.ga_len; ++i) { cur_si = &CUR_STATE(i); if ((cur_si->si_flags & HL_KEEPEND) || (seen_keepend && !startofline) || (i == current_state.ga_len - 1 && startofline)) { cur_si->si_h_startpos.col = 0; /* start highl. in col 0 */ cur_si->si_h_startpos.lnum = current_lnum; if (!(cur_si->si_flags & HL_MATCHCONT)) update_si_end(cur_si, (int)current_col, !startofline); if (!startofline && (cur_si->si_flags & HL_KEEPEND)) seen_keepend = TRUE; } } check_keepend(); } /**************************************** * Handling of the state stack cache. */ /* * EXPLANATION OF THE SYNTAX STATE STACK CACHE * * To speed up syntax highlighting, the state stack for the start of some * lines is cached. These entries can be used to start parsing at that point. * * The stack is kept in b_sst_array[] for each buffer. There is a list of * valid entries. b_sst_first points to the first one, then follow sst_next. * The entries are sorted on line number. The first entry is often for line 2 * (line 1 always starts with an empty stack). * There is also a list for free entries. This construction is used to avoid * having to allocate and free memory blocks too often. * * When making changes to the buffer, this is logged in b_mod_*. When calling * update_screen() to update the display, it will call * syn_stack_apply_changes() for each displayed buffer to adjust the cached * entries. The entries which are inside the changed area are removed, * because they must be recomputed. Entries below the changed have their line * number adjusted for deleted/inserted lines, and have their sst_change_lnum * set to indicate that a check must be made if the changed lines would change * the cached entry. * * When later displaying lines, an entry is stored for each line. Displayed * lines are likely to be displayed again, in which case the state at the * start of the line is needed. * For not displayed lines, an entry is stored for every so many lines. These * entries will be used e.g., when scrolling backwards. The distance between * entries depends on the number of lines in the buffer. For small buffers * the distance is fixed at SST_DIST, for large buffers there is a fixed * number of entries SST_MAX_ENTRIES, and the distance is computed. */ static void syn_stack_free_block(block) synblock_T *block; { synstate_T *p; if (block->b_sst_array != NULL) { for (p = block->b_sst_first; p != NULL; p = p->sst_next) clear_syn_state(p); vim_free(block->b_sst_array); block->b_sst_array = NULL; block->b_sst_len = 0; } } /* * Free b_sst_array[] for buffer "buf". * Used when syntax items changed to force resyncing everywhere. */ void syn_stack_free_all(block) synblock_T *block; { win_T *wp; syn_stack_free_block(block); #ifdef FEAT_FOLDING /* When using "syntax" fold method, must update all folds. */ FOR_ALL_WINDOWS(wp) { if (wp->w_s == block && foldmethodIsSyntax(wp)) foldUpdateAll(wp); } #endif } /* * Allocate the syntax state stack for syn_buf when needed. * If the number of entries in b_sst_array[] is much too big or a bit too * small, reallocate it. * Also used to allocate b_sst_array[] for the first time. */ static void syn_stack_alloc() { long len; synstate_T *to, *from; synstate_T *sstp; len = syn_buf->b_ml.ml_line_count / SST_DIST + Rows * 2; if (len < SST_MIN_ENTRIES) len = SST_MIN_ENTRIES; else if (len > SST_MAX_ENTRIES) len = SST_MAX_ENTRIES; if (syn_block->b_sst_len > len * 2 || syn_block->b_sst_len < len) { /* Allocate 50% too much, to avoid reallocating too often. */ len = syn_buf->b_ml.ml_line_count; len = (len + len / 2) / SST_DIST + Rows * 2; if (len < SST_MIN_ENTRIES) len = SST_MIN_ENTRIES; else if (len > SST_MAX_ENTRIES) len = SST_MAX_ENTRIES; if (syn_block->b_sst_array != NULL) { /* When shrinking the array, cleanup the existing stack. * Make sure that all valid entries fit in the new array. */ while (syn_block->b_sst_len - syn_block->b_sst_freecount + 2 > len && syn_stack_cleanup()) ; if (len < syn_block->b_sst_len - syn_block->b_sst_freecount + 2) len = syn_block->b_sst_len - syn_block->b_sst_freecount + 2; } sstp = (synstate_T *)alloc_clear((unsigned)(len * sizeof(synstate_T))); if (sstp == NULL) /* out of memory! */ return; to = sstp - 1; if (syn_block->b_sst_array != NULL) { /* Move the states from the old array to the new one. */ for (from = syn_block->b_sst_first; from != NULL; from = from->sst_next) { ++to; *to = *from; to->sst_next = to + 1; } } if (to != sstp - 1) { to->sst_next = NULL; syn_block->b_sst_first = sstp; syn_block->b_sst_freecount = len - (int)(to - sstp) - 1; } else { syn_block->b_sst_first = NULL; syn_block->b_sst_freecount = len; } /* Create the list of free entries. */ syn_block->b_sst_firstfree = to + 1; while (++to < sstp + len) to->sst_next = to + 1; (sstp + len - 1)->sst_next = NULL; vim_free(syn_block->b_sst_array); syn_block->b_sst_array = sstp; syn_block->b_sst_len = len; } } /* * Check for changes in a buffer to affect stored syntax states. Uses the * b_mod_* fields. * Called from update_screen(), before screen is being updated, once for each * displayed buffer. */ void syn_stack_apply_changes(buf) buf_T *buf; { win_T *wp; syn_stack_apply_changes_block(&buf->b_s, buf); FOR_ALL_WINDOWS(wp) { if ((wp->w_buffer == buf) && (wp->w_s != &buf->b_s)) syn_stack_apply_changes_block(wp->w_s, buf); } } static void syn_stack_apply_changes_block(block, buf) synblock_T *block; buf_T *buf; { synstate_T *p, *prev, *np; linenr_T n; if (block->b_sst_array == NULL) /* nothing to do */ return; prev = NULL; for (p = block->b_sst_first; p != NULL; ) { if (p->sst_lnum + block->b_syn_sync_linebreaks > buf->b_mod_top) { n = p->sst_lnum + buf->b_mod_xlines; if (n <= buf->b_mod_bot) { /* this state is inside the changed area, remove it */ np = p->sst_next; if (prev == NULL) block->b_sst_first = np; else prev->sst_next = np; syn_stack_free_entry(block, p); p = np; continue; } /* This state is below the changed area. Remember the line * that needs to be parsed before this entry can be made valid * again. */ if (p->sst_change_lnum != 0 && p->sst_change_lnum > buf->b_mod_top) { if (p->sst_change_lnum + buf->b_mod_xlines > buf->b_mod_top) p->sst_change_lnum += buf->b_mod_xlines; else p->sst_change_lnum = buf->b_mod_top; } if (p->sst_change_lnum == 0 || p->sst_change_lnum < buf->b_mod_bot) p->sst_change_lnum = buf->b_mod_bot; p->sst_lnum = n; } prev = p; p = p->sst_next; } } /* * Reduce the number of entries in the state stack for syn_buf. * Returns TRUE if at least one entry was freed. */ static int syn_stack_cleanup() { synstate_T *p, *prev; disptick_T tick; int above; int dist; int retval = FALSE; if (syn_block->b_sst_array == NULL || syn_block->b_sst_first == NULL) return retval; /* Compute normal distance between non-displayed entries. */ if (syn_block->b_sst_len <= Rows) dist = 999999; else dist = syn_buf->b_ml.ml_line_count / (syn_block->b_sst_len - Rows) + 1; /* * Go through the list to find the "tick" for the oldest entry that can * be removed. Set "above" when the "tick" for the oldest entry is above * "b_sst_lasttick" (the display tick wraps around). */ tick = syn_block->b_sst_lasttick; above = FALSE; prev = syn_block->b_sst_first; for (p = prev->sst_next; p != NULL; prev = p, p = p->sst_next) { if (prev->sst_lnum + dist > p->sst_lnum) { if (p->sst_tick > syn_block->b_sst_lasttick) { if (!above || p->sst_tick < tick) tick = p->sst_tick; above = TRUE; } else if (!above && p->sst_tick < tick) tick = p->sst_tick; } } /* * Go through the list to make the entries for the oldest tick at an * interval of several lines. */ prev = syn_block->b_sst_first; for (p = prev->sst_next; p != NULL; prev = p, p = p->sst_next) { if (p->sst_tick == tick && prev->sst_lnum + dist > p->sst_lnum) { /* Move this entry from used list to free list */ prev->sst_next = p->sst_next; syn_stack_free_entry(syn_block, p); p = prev; retval = TRUE; } } return retval; } /* * Free the allocated memory for a syn_state item. * Move the entry into the free list. */ static void syn_stack_free_entry(block, p) synblock_T *block; synstate_T *p; { clear_syn_state(p); p->sst_next = block->b_sst_firstfree; block->b_sst_firstfree = p; ++block->b_sst_freecount; } /* * Find an entry in the list of state stacks at or before "lnum". * Returns NULL when there is no entry or the first entry is after "lnum". */ static synstate_T * syn_stack_find_entry(lnum) linenr_T lnum; { synstate_T *p, *prev; prev = NULL; for (p = syn_block->b_sst_first; p != NULL; prev = p, p = p->sst_next) { if (p->sst_lnum == lnum) return p; if (p->sst_lnum > lnum) break; } return prev; } /* * Try saving the current state in b_sst_array[]. * The current state must be valid for the start of the current_lnum line! */ static synstate_T * store_current_state() { int i; synstate_T *p; bufstate_T *bp; stateitem_T *cur_si; synstate_T *sp = syn_stack_find_entry(current_lnum); /* * If the current state contains a start or end pattern that continues * from the previous line, we can't use it. Don't store it then. */ for (i = current_state.ga_len - 1; i >= 0; --i) { cur_si = &CUR_STATE(i); if (cur_si->si_h_startpos.lnum >= current_lnum || cur_si->si_m_endpos.lnum >= current_lnum || cur_si->si_h_endpos.lnum >= current_lnum || (cur_si->si_end_idx && cur_si->si_eoe_pos.lnum >= current_lnum)) break; } if (i >= 0) { if (sp != NULL) { /* find "sp" in the list and remove it */ if (syn_block->b_sst_first == sp) /* it's the first entry */ syn_block->b_sst_first = sp->sst_next; else { /* find the entry just before this one to adjust sst_next */ for (p = syn_block->b_sst_first; p != NULL; p = p->sst_next) if (p->sst_next == sp) break; if (p != NULL) /* just in case */ p->sst_next = sp->sst_next; } syn_stack_free_entry(syn_block, sp); sp = NULL; } } else if (sp == NULL || sp->sst_lnum != current_lnum) { /* * Add a new entry */ /* If no free items, cleanup the array first. */ if (syn_block->b_sst_freecount == 0) { (void)syn_stack_cleanup(); /* "sp" may have been moved to the freelist now */ sp = syn_stack_find_entry(current_lnum); } /* Still no free items? Must be a strange problem... */ if (syn_block->b_sst_freecount == 0) sp = NULL; else { /* Take the first item from the free list and put it in the used * list, after *sp */ p = syn_block->b_sst_firstfree; syn_block->b_sst_firstfree = p->sst_next; --syn_block->b_sst_freecount; if (sp == NULL) { /* Insert in front of the list */ p->sst_next = syn_block->b_sst_first; syn_block->b_sst_first = p; } else { /* insert in list after *sp */ p->sst_next = sp->sst_next; sp->sst_next = p; } sp = p; sp->sst_stacksize = 0; sp->sst_lnum = current_lnum; } } if (sp != NULL) { /* When overwriting an existing state stack, clear it first */ clear_syn_state(sp); sp->sst_stacksize = current_state.ga_len; if (current_state.ga_len > SST_FIX_STATES) { /* Need to clear it, might be something remaining from when the * length was less than SST_FIX_STATES. */ ga_init2(&sp->sst_union.sst_ga, (int)sizeof(bufstate_T), 1); if (ga_grow(&sp->sst_union.sst_ga, current_state.ga_len) == FAIL) sp->sst_stacksize = 0; else sp->sst_union.sst_ga.ga_len = current_state.ga_len; bp = SYN_STATE_P(&(sp->sst_union.sst_ga)); } else bp = sp->sst_union.sst_stack; for (i = 0; i < sp->sst_stacksize; ++i) { bp[i].bs_idx = CUR_STATE(i).si_idx; bp[i].bs_flags = CUR_STATE(i).si_flags; #ifdef FEAT_CONCEAL bp[i].bs_seqnr = CUR_STATE(i).si_seqnr; bp[i].bs_cchar = CUR_STATE(i).si_cchar; #endif bp[i].bs_extmatch = ref_extmatch(CUR_STATE(i).si_extmatch); } sp->sst_next_flags = current_next_flags; sp->sst_next_list = current_next_list; sp->sst_tick = display_tick; sp->sst_change_lnum = 0; } current_state_stored = TRUE; return sp; } /* * Copy a state stack from "from" in b_sst_array[] to current_state; */ static void load_current_state(from) synstate_T *from; { int i; bufstate_T *bp; clear_current_state(); validate_current_state(); keepend_level = -1; if (from->sst_stacksize && ga_grow(&current_state, from->sst_stacksize) != FAIL) { if (from->sst_stacksize > SST_FIX_STATES) bp = SYN_STATE_P(&(from->sst_union.sst_ga)); else bp = from->sst_union.sst_stack; for (i = 0; i < from->sst_stacksize; ++i) { CUR_STATE(i).si_idx = bp[i].bs_idx; CUR_STATE(i).si_flags = bp[i].bs_flags; #ifdef FEAT_CONCEAL CUR_STATE(i).si_seqnr = bp[i].bs_seqnr; CUR_STATE(i).si_cchar = bp[i].bs_cchar; #endif CUR_STATE(i).si_extmatch = ref_extmatch(bp[i].bs_extmatch); if (keepend_level < 0 && (CUR_STATE(i).si_flags & HL_KEEPEND)) keepend_level = i; CUR_STATE(i).si_ends = FALSE; CUR_STATE(i).si_m_lnum = 0; if (CUR_STATE(i).si_idx >= 0) CUR_STATE(i).si_next_list = (SYN_ITEMS(syn_block)[CUR_STATE(i).si_idx]).sp_next_list; else CUR_STATE(i).si_next_list = NULL; update_si_attr(i); } current_state.ga_len = from->sst_stacksize; } current_next_list = from->sst_next_list; current_next_flags = from->sst_next_flags; current_lnum = from->sst_lnum; } /* * Compare saved state stack "*sp" with the current state. * Return TRUE when they are equal. */ static int syn_stack_equal(sp) synstate_T *sp; { int i, j; bufstate_T *bp; reg_extmatch_T *six, *bsx; /* First a quick check if the stacks have the same size end nextlist. */ if (sp->sst_stacksize == current_state.ga_len && sp->sst_next_list == current_next_list) { /* Need to compare all states on both stacks. */ if (sp->sst_stacksize > SST_FIX_STATES) bp = SYN_STATE_P(&(sp->sst_union.sst_ga)); else bp = sp->sst_union.sst_stack; for (i = current_state.ga_len; --i >= 0; ) { /* If the item has another index the state is different. */ if (bp[i].bs_idx != CUR_STATE(i).si_idx) break; if (bp[i].bs_extmatch != CUR_STATE(i).si_extmatch) { /* When the extmatch pointers are different, the strings in * them can still be the same. Check if the extmatch * references are equal. */ bsx = bp[i].bs_extmatch; six = CUR_STATE(i).si_extmatch; /* If one of the extmatch pointers is NULL the states are * different. */ if (bsx == NULL || six == NULL) break; for (j = 0; j < NSUBEXP; ++j) { /* Check each referenced match string. They must all be * equal. */ if (bsx->matches[j] != six->matches[j]) { /* If the pointer is different it can still be the * same text. Compare the strings, ignore case when * the start item has the sp_ic flag set. */ if (bsx->matches[j] == NULL || six->matches[j] == NULL) break; if ((SYN_ITEMS(syn_block)[CUR_STATE(i).si_idx]).sp_ic ? MB_STRICMP(bsx->matches[j], six->matches[j]) != 0 : STRCMP(bsx->matches[j], six->matches[j]) != 0) break; } } if (j != NSUBEXP) break; } } if (i < 0) return TRUE; } return FALSE; } /* * We stop parsing syntax above line "lnum". If the stored state at or below * this line depended on a change before it, it now depends on the line below * the last parsed line. * The window looks like this: * line which changed * displayed line * displayed line * lnum -> line below window */ void syntax_end_parsing(lnum) linenr_T lnum; { synstate_T *sp; sp = syn_stack_find_entry(lnum); if (sp != NULL && sp->sst_lnum < lnum) sp = sp->sst_next; if (sp != NULL && sp->sst_change_lnum != 0) sp->sst_change_lnum = lnum; } /* * End of handling of the state stack. ****************************************/ static void invalidate_current_state() { clear_current_state(); current_state.ga_itemsize = 0; /* mark current_state invalid */ current_next_list = NULL; keepend_level = -1; } static void validate_current_state() { current_state.ga_itemsize = sizeof(stateitem_T); current_state.ga_growsize = 3; } /* * Return TRUE if the syntax at start of lnum changed since last time. * This will only be called just after get_syntax_attr() for the previous * line, to check if the next line needs to be redrawn too. */ int syntax_check_changed(lnum) linenr_T lnum; { int retval = TRUE; synstate_T *sp; /* * Check the state stack when: * - lnum is just below the previously syntaxed line. * - lnum is not before the lines with saved states. * - lnum is not past the lines with saved states. * - lnum is at or before the last changed line. */ if (VALID_STATE(&current_state) && lnum == current_lnum + 1) { sp = syn_stack_find_entry(lnum); if (sp != NULL && sp->sst_lnum == lnum) { /* * finish the previous line (needed when not all of the line was * drawn) */ (void)syn_finish_line(FALSE); /* * Compare the current state with the previously saved state of * the line. */ if (syn_stack_equal(sp)) retval = FALSE; /* * Store the current state in b_sst_array[] for later use. */ ++current_lnum; (void)store_current_state(); } } return retval; } /* * Finish the current line. * This doesn't return any attributes, it only gets the state at the end of * the line. It can start anywhere in the line, as long as the current state * is valid. */ static int syn_finish_line(syncing) int syncing; /* called for syncing */ { stateitem_T *cur_si; colnr_T prev_current_col; if (!current_finished) { while (!current_finished) { (void)syn_current_attr(syncing, FALSE, NULL, FALSE); /* * When syncing, and found some item, need to check the item. */ if (syncing && current_state.ga_len) { /* * Check for match with sync item. */ cur_si = &CUR_STATE(current_state.ga_len - 1); if (cur_si->si_idx >= 0 && (SYN_ITEMS(syn_block)[cur_si->si_idx].sp_flags & (HL_SYNC_HERE|HL_SYNC_THERE))) return TRUE; /* syn_current_attr() will have skipped the check for an item * that ends here, need to do that now. Be careful not to go * past the NUL. */ prev_current_col = current_col; if (syn_getcurline()[current_col] != NUL) ++current_col; check_state_ends(); current_col = prev_current_col; } ++current_col; } } return FALSE; } /* * Return highlight attributes for next character. * Must first call syntax_start() once for the line. * "col" is normally 0 for the first use in a line, and increments by one each * time. It's allowed to skip characters and to stop before the end of the * line. But only a "col" after a previously used column is allowed. * When "can_spell" is not NULL set it to TRUE when spell-checking should be * done. */ int get_syntax_attr(col, can_spell, keep_state) colnr_T col; int *can_spell; int keep_state; /* keep state of char at "col" */ { int attr = 0; if (can_spell != NULL) /* Default: Only do spelling when there is no @Spell cluster or when * ":syn spell toplevel" was used. */ *can_spell = syn_block->b_syn_spell == SYNSPL_DEFAULT ? (syn_block->b_spell_cluster_id == 0) : (syn_block->b_syn_spell == SYNSPL_TOP); /* check for out of memory situation */ if (syn_block->b_sst_array == NULL) return 0; /* After 'synmaxcol' the attribute is always zero. */ if (syn_buf->b_p_smc > 0 && col >= (colnr_T)syn_buf->b_p_smc) { clear_current_state(); #ifdef FEAT_EVAL current_id = 0; current_trans_id = 0; #endif #ifdef FEAT_CONCEAL current_flags = 0; #endif return 0; } /* Make sure current_state is valid */ if (INVALID_STATE(&current_state)) validate_current_state(); /* * Skip from the current column to "col", get the attributes for "col". */ while (current_col <= col) { attr = syn_current_attr(FALSE, TRUE, can_spell, current_col == col ? keep_state : FALSE); ++current_col; } return attr; } /* * Get syntax attributes for current_lnum, current_col. */ static int syn_current_attr(syncing, displaying, can_spell, keep_state) int syncing; /* When 1: called for syncing */ int displaying; /* result will be displayed */ int *can_spell; /* return: do spell checking */ int keep_state; /* keep syntax stack afterwards */ { int syn_id; lpos_T endpos; /* was: char_u *endp; */ lpos_T hl_startpos; /* was: int hl_startcol; */ lpos_T hl_endpos; lpos_T eos_pos; /* end-of-start match (start region) */ lpos_T eoe_pos; /* end-of-end pattern */ int end_idx; /* group ID for end pattern */ int idx; synpat_T *spp; stateitem_T *cur_si, *sip = NULL; int startcol; int endcol; long flags; int cchar; short *next_list; int found_match; /* found usable match */ static int try_next_column = FALSE; /* must try in next col */ int do_keywords; regmmatch_T regmatch; lpos_T pos; int lc_col; reg_extmatch_T *cur_extmatch = NULL; char_u *line; /* current line. NOTE: becomes invalid after looking for a pattern match! */ /* variables for zero-width matches that have a "nextgroup" argument */ int keep_next_list; int zero_width_next_list = FALSE; garray_T zero_width_next_ga; /* * No character, no attributes! Past end of line? * Do try matching with an empty line (could be the start of a region). */ line = syn_getcurline(); if (line[current_col] == NUL && current_col != 0) { /* * If we found a match after the last column, use it. */ if (next_match_idx >= 0 && next_match_col >= (int)current_col && next_match_col != MAXCOL) (void)push_next_match(NULL); current_finished = TRUE; current_state_stored = FALSE; return 0; } /* if the current or next character is NUL, we will finish the line now */ if (line[current_col] == NUL || line[current_col + 1] == NUL) { current_finished = TRUE; current_state_stored = FALSE; } /* * When in the previous column there was a match but it could not be used * (empty match or already matched in this column) need to try again in * the next column. */ if (try_next_column) { next_match_idx = -1; try_next_column = FALSE; } /* Only check for keywords when not syncing and there are some. */ do_keywords = !syncing && (syn_block->b_keywtab.ht_used > 0 || syn_block->b_keywtab_ic.ht_used > 0); /* Init the list of zero-width matches with a nextlist. This is used to * avoid matching the same item in the same position twice. */ ga_init2(&zero_width_next_ga, (int)sizeof(int), 10); /* * Repeat matching keywords and patterns, to find contained items at the * same column. This stops when there are no extra matches at the current * column. */ do { found_match = FALSE; keep_next_list = FALSE; syn_id = 0; /* * 1. Check for a current state. * Only when there is no current state, or if the current state may * contain other things, we need to check for keywords and patterns. * Always need to check for contained items if some item has the * "containedin" argument (takes extra time!). */ if (current_state.ga_len) cur_si = &CUR_STATE(current_state.ga_len - 1); else cur_si = NULL; if (syn_block->b_syn_containedin || cur_si == NULL || cur_si->si_cont_list != NULL) { /* * 2. Check for keywords, if on a keyword char after a non-keyword * char. Don't do this when syncing. */ if (do_keywords) { line = syn_getcurline(); if (vim_iswordc_buf(line + current_col, syn_buf) && (current_col == 0 || !vim_iswordc_buf(line + current_col - 1 #ifdef FEAT_MBYTE - (has_mbyte ? (*mb_head_off)(line, line + current_col - 1) : 0) #endif , syn_buf))) { syn_id = check_keyword_id(line, (int)current_col, &endcol, &flags, &next_list, cur_si, &cchar); if (syn_id != 0) { if (push_current_state(KEYWORD_IDX) == OK) { cur_si = &CUR_STATE(current_state.ga_len - 1); cur_si->si_m_startcol = current_col; cur_si->si_h_startpos.lnum = current_lnum; cur_si->si_h_startpos.col = 0; /* starts right away */ cur_si->si_m_endpos.lnum = current_lnum; cur_si->si_m_endpos.col = endcol; cur_si->si_h_endpos.lnum = current_lnum; cur_si->si_h_endpos.col = endcol; cur_si->si_ends = TRUE; cur_si->si_end_idx = 0; cur_si->si_flags = flags; #ifdef FEAT_CONCEAL cur_si->si_seqnr = next_seqnr++; cur_si->si_cchar = cchar; if (current_state.ga_len > 1) cur_si->si_flags |= CUR_STATE(current_state.ga_len - 2).si_flags & HL_CONCEAL; #endif cur_si->si_id = syn_id; cur_si->si_trans_id = syn_id; if (flags & HL_TRANSP) { if (current_state.ga_len < 2) { cur_si->si_attr = 0; cur_si->si_trans_id = 0; } else { cur_si->si_attr = CUR_STATE( current_state.ga_len - 2).si_attr; cur_si->si_trans_id = CUR_STATE( current_state.ga_len - 2).si_trans_id; } } else cur_si->si_attr = syn_id2attr(syn_id); cur_si->si_cont_list = NULL; cur_si->si_next_list = next_list; check_keepend(); } else vim_free(next_list); } } } /* * 3. Check for patterns (only if no keyword found). */ if (syn_id == 0 && syn_block->b_syn_patterns.ga_len) { /* * If we didn't check for a match yet, or we are past it, check * for any match with a pattern. */ if (next_match_idx < 0 || next_match_col < (int)current_col) { /* * Check all relevant patterns for a match at this * position. This is complicated, because matching with a * pattern takes quite a bit of time, thus we want to * avoid doing it when it's not needed. */ next_match_idx = 0; /* no match in this line yet */ next_match_col = MAXCOL; for (idx = syn_block->b_syn_patterns.ga_len; --idx >= 0; ) { spp = &(SYN_ITEMS(syn_block)[idx]); if ( spp->sp_syncing == syncing && (displaying || !(spp->sp_flags & HL_DISPLAY)) && (spp->sp_type == SPTYPE_MATCH || spp->sp_type == SPTYPE_START) && (current_next_list != NULL ? in_id_list(NULL, current_next_list, &spp->sp_syn, 0) : (cur_si == NULL ? !(spp->sp_flags & HL_CONTAINED) : in_id_list(cur_si, cur_si->si_cont_list, &spp->sp_syn, spp->sp_flags & HL_CONTAINED)))) { /* If we already tried matching in this line, and * there isn't a match before next_match_col, skip * this item. */ if (spp->sp_line_id == current_line_id && spp->sp_startcol >= next_match_col) continue; spp->sp_line_id = current_line_id; lc_col = current_col - spp->sp_offsets[SPO_LC_OFF]; if (lc_col < 0) lc_col = 0; regmatch.rmm_ic = spp->sp_ic; regmatch.regprog = spp->sp_prog; if (!syn_regexec(&regmatch, current_lnum, (colnr_T)lc_col)) { /* no match in this line, try another one */ spp->sp_startcol = MAXCOL; continue; } /* * Compute the first column of the match. */ syn_add_start_off(&pos, &regmatch, spp, SPO_MS_OFF, -1); if (pos.lnum > current_lnum) { /* must have used end of match in a next line, * we can't handle that */ spp->sp_startcol = MAXCOL; continue; } startcol = pos.col; /* remember the next column where this pattern * matches in the current line */ spp->sp_startcol = startcol; /* * If a previously found match starts at a lower * column number, don't use this one. */ if (startcol >= next_match_col) continue; /* * If we matched this pattern at this position * before, skip it. Must retry in the next * column, because it may match from there. */ if (did_match_already(idx, &zero_width_next_ga)) { try_next_column = TRUE; continue; } endpos.lnum = regmatch.endpos[0].lnum; endpos.col = regmatch.endpos[0].col; /* Compute the highlight start. */ syn_add_start_off(&hl_startpos, &regmatch, spp, SPO_HS_OFF, -1); /* Compute the region start. */ /* Default is to use the end of the match. */ syn_add_end_off(&eos_pos, &regmatch, spp, SPO_RS_OFF, 0); /* * Grab the external submatches before they get * overwritten. Reference count doesn't change. */ unref_extmatch(cur_extmatch); cur_extmatch = re_extmatch_out; re_extmatch_out = NULL; flags = 0; eoe_pos.lnum = 0; /* avoid warning */ eoe_pos.col = 0; end_idx = 0; hl_endpos.lnum = 0; /* * For a "oneline" the end must be found in the * same line too. Search for it after the end of * the match with the start pattern. Set the * resulting end positions at the same time. */ if (spp->sp_type == SPTYPE_START && (spp->sp_flags & HL_ONELINE)) { lpos_T startpos; startpos = endpos; find_endpos(idx, &startpos, &endpos, &hl_endpos, &flags, &eoe_pos, &end_idx, cur_extmatch); if (endpos.lnum == 0) continue; /* not found */ } /* * For a "match" the size must be > 0 after the * end offset needs has been added. Except when * syncing. */ else if (spp->sp_type == SPTYPE_MATCH) { syn_add_end_off(&hl_endpos, &regmatch, spp, SPO_HE_OFF, 0); syn_add_end_off(&endpos, &regmatch, spp, SPO_ME_OFF, 0); if (endpos.lnum == current_lnum && (int)endpos.col + syncing < startcol) { /* * If an empty string is matched, may need * to try matching again at next column. */ if (regmatch.startpos[0].col == regmatch.endpos[0].col) try_next_column = TRUE; continue; } } /* * keep the best match so far in next_match_* */ /* Highlighting must start after startpos and end * before endpos. */ if (hl_startpos.lnum == current_lnum && (int)hl_startpos.col < startcol) hl_startpos.col = startcol; limit_pos_zero(&hl_endpos, &endpos); next_match_idx = idx; next_match_col = startcol; next_match_m_endpos = endpos; next_match_h_endpos = hl_endpos; next_match_h_startpos = hl_startpos; next_match_flags = flags; next_match_eos_pos = eos_pos; next_match_eoe_pos = eoe_pos; next_match_end_idx = end_idx; unref_extmatch(next_match_extmatch); next_match_extmatch = cur_extmatch; cur_extmatch = NULL; } } } /* * If we found a match at the current column, use it. */ if (next_match_idx >= 0 && next_match_col == (int)current_col) { synpat_T *lspp; /* When a zero-width item matched which has a nextgroup, * don't push the item but set nextgroup. */ lspp = &(SYN_ITEMS(syn_block)[next_match_idx]); if (next_match_m_endpos.lnum == current_lnum && next_match_m_endpos.col == current_col && lspp->sp_next_list != NULL) { current_next_list = lspp->sp_next_list; current_next_flags = lspp->sp_flags; keep_next_list = TRUE; zero_width_next_list = TRUE; /* Add the index to a list, so that we can check * later that we don't match it again (and cause an * endless loop). */ if (ga_grow(&zero_width_next_ga, 1) == OK) { ((int *)(zero_width_next_ga.ga_data)) [zero_width_next_ga.ga_len++] = next_match_idx; } next_match_idx = -1; } else cur_si = push_next_match(cur_si); found_match = TRUE; } } } /* * Handle searching for nextgroup match. */ if (current_next_list != NULL && !keep_next_list) { /* * If a nextgroup was not found, continue looking for one if: * - this is an empty line and the "skipempty" option was given * - we are on white space and the "skipwhite" option was given */ if (!found_match) { line = syn_getcurline(); if (((current_next_flags & HL_SKIPWHITE) && vim_iswhite(line[current_col])) || ((current_next_flags & HL_SKIPEMPTY) && *line == NUL)) break; } /* * If a nextgroup was found: Use it, and continue looking for * contained matches. * If a nextgroup was not found: Continue looking for a normal * match. * When did set current_next_list for a zero-width item and no * match was found don't loop (would get stuck). */ current_next_list = NULL; next_match_idx = -1; if (!zero_width_next_list) found_match = TRUE; } } while (found_match); /* * Use attributes from the current state, if within its highlighting. * If not, use attributes from the current-but-one state, etc. */ current_attr = 0; #ifdef FEAT_EVAL current_id = 0; current_trans_id = 0; #endif #ifdef FEAT_CONCEAL current_flags = 0; #endif if (cur_si != NULL) { #ifndef FEAT_EVAL int current_trans_id = 0; #endif for (idx = current_state.ga_len - 1; idx >= 0; --idx) { sip = &CUR_STATE(idx); if ((current_lnum > sip->si_h_startpos.lnum || (current_lnum == sip->si_h_startpos.lnum && current_col >= sip->si_h_startpos.col)) && (sip->si_h_endpos.lnum == 0 || current_lnum < sip->si_h_endpos.lnum || (current_lnum == sip->si_h_endpos.lnum && current_col < sip->si_h_endpos.col))) { current_attr = sip->si_attr; #ifdef FEAT_EVAL current_id = sip->si_id; #endif current_trans_id = sip->si_trans_id; #ifdef FEAT_CONCEAL current_flags = sip->si_flags; current_seqnr = sip->si_seqnr; current_sub_char = sip->si_cchar; #endif break; } } if (can_spell != NULL) { struct sp_syn sps; /* * set "can_spell" to TRUE if spell checking is supposed to be * done in the current item. */ if (syn_block->b_spell_cluster_id == 0) { /* There is no @Spell cluster: Do spelling for items without * @NoSpell cluster. */ if (syn_block->b_nospell_cluster_id == 0 || current_trans_id == 0) *can_spell = (syn_block->b_syn_spell != SYNSPL_NOTOP); else { sps.inc_tag = 0; sps.id = syn_block->b_nospell_cluster_id; sps.cont_in_list = NULL; *can_spell = !in_id_list(sip, sip->si_cont_list, &sps, 0); } } else { /* The @Spell cluster is defined: Do spelling in items with * the @Spell cluster. But not when @NoSpell is also there. * At the toplevel only spell check when ":syn spell toplevel" * was used. */ if (current_trans_id == 0) *can_spell = (syn_block->b_syn_spell == SYNSPL_TOP); else { sps.inc_tag = 0; sps.id = syn_block->b_spell_cluster_id; sps.cont_in_list = NULL; *can_spell = in_id_list(sip, sip->si_cont_list, &sps, 0); if (syn_block->b_nospell_cluster_id != 0) { sps.id = syn_block->b_nospell_cluster_id; if (in_id_list(sip, sip->si_cont_list, &sps, 0)) *can_spell = FALSE; } } } } /* * Check for end of current state (and the states before it) at the * next column. Don't do this for syncing, because we would miss a * single character match. * First check if the current state ends at the current column. It * may be for an empty match and a containing item might end in the * current column. */ if (!syncing && !keep_state) { check_state_ends(); if (current_state.ga_len > 0 && syn_getcurline()[current_col] != NUL) { ++current_col; check_state_ends(); --current_col; } } } else if (can_spell != NULL) /* Default: Only do spelling when there is no @Spell cluster or when * ":syn spell toplevel" was used. */ *can_spell = syn_block->b_syn_spell == SYNSPL_DEFAULT ? (syn_block->b_spell_cluster_id == 0) : (syn_block->b_syn_spell == SYNSPL_TOP); /* nextgroup ends at end of line, unless "skipnl" or "skipempty" present */ if (current_next_list != NULL && syn_getcurline()[current_col + 1] == NUL && !(current_next_flags & (HL_SKIPNL | HL_SKIPEMPTY))) current_next_list = NULL; if (zero_width_next_ga.ga_len > 0) ga_clear(&zero_width_next_ga); /* No longer need external matches. But keep next_match_extmatch. */ unref_extmatch(re_extmatch_out); re_extmatch_out = NULL; unref_extmatch(cur_extmatch); return current_attr; } /* * Check if we already matched pattern "idx" at the current column. */ static int did_match_already(idx, gap) int idx; garray_T *gap; { int i; for (i = current_state.ga_len; --i >= 0; ) if (CUR_STATE(i).si_m_startcol == (int)current_col && CUR_STATE(i).si_m_lnum == (int)current_lnum && CUR_STATE(i).si_idx == idx) return TRUE; /* Zero-width matches with a nextgroup argument are not put on the syntax * stack, and can only be matched once anyway. */ for (i = gap->ga_len; --i >= 0; ) if (((int *)(gap->ga_data))[i] == idx) return TRUE; return FALSE; } /* * Push the next match onto the stack. */ static stateitem_T * push_next_match(cur_si) stateitem_T *cur_si; { synpat_T *spp; #ifdef FEAT_CONCEAL int save_flags; #endif spp = &(SYN_ITEMS(syn_block)[next_match_idx]); /* * Push the item in current_state stack; */ if (push_current_state(next_match_idx) == OK) { /* * If it's a start-skip-end type that crosses lines, figure out how * much it continues in this line. Otherwise just fill in the length. */ cur_si = &CUR_STATE(current_state.ga_len - 1); cur_si->si_h_startpos = next_match_h_startpos; cur_si->si_m_startcol = current_col; cur_si->si_m_lnum = current_lnum; cur_si->si_flags = spp->sp_flags; #ifdef FEAT_CONCEAL cur_si->si_seqnr = next_seqnr++; cur_si->si_cchar = spp->sp_cchar; if (current_state.ga_len > 1) cur_si->si_flags |= CUR_STATE(current_state.ga_len - 2).si_flags & HL_CONCEAL; #endif cur_si->si_next_list = spp->sp_next_list; cur_si->si_extmatch = ref_extmatch(next_match_extmatch); if (spp->sp_type == SPTYPE_START && !(spp->sp_flags & HL_ONELINE)) { /* Try to find the end pattern in the current line */ update_si_end(cur_si, (int)(next_match_m_endpos.col), TRUE); check_keepend(); } else { cur_si->si_m_endpos = next_match_m_endpos; cur_si->si_h_endpos = next_match_h_endpos; cur_si->si_ends = TRUE; cur_si->si_flags |= next_match_flags; cur_si->si_eoe_pos = next_match_eoe_pos; cur_si->si_end_idx = next_match_end_idx; } if (keepend_level < 0 && (cur_si->si_flags & HL_KEEPEND)) keepend_level = current_state.ga_len - 1; check_keepend(); update_si_attr(current_state.ga_len - 1); #ifdef FEAT_CONCEAL save_flags = cur_si->si_flags & (HL_CONCEAL | HL_CONCEALENDS); #endif /* * If the start pattern has another highlight group, push another item * on the stack for the start pattern. */ if ( spp->sp_type == SPTYPE_START && spp->sp_syn_match_id != 0 && push_current_state(next_match_idx) == OK) { cur_si = &CUR_STATE(current_state.ga_len - 1); cur_si->si_h_startpos = next_match_h_startpos; cur_si->si_m_startcol = current_col; cur_si->si_m_lnum = current_lnum; cur_si->si_m_endpos = next_match_eos_pos; cur_si->si_h_endpos = next_match_eos_pos; cur_si->si_ends = TRUE; cur_si->si_end_idx = 0; cur_si->si_flags = HL_MATCH; #ifdef FEAT_CONCEAL cur_si->si_seqnr = next_seqnr++; cur_si->si_flags |= save_flags; if (cur_si->si_flags & HL_CONCEALENDS) cur_si->si_flags |= HL_CONCEAL; #endif cur_si->si_next_list = NULL; check_keepend(); update_si_attr(current_state.ga_len - 1); } } next_match_idx = -1; /* try other match next time */ return cur_si; } /* * Check for end of current state (and the states before it). */ static void check_state_ends() { stateitem_T *cur_si; int had_extend; cur_si = &CUR_STATE(current_state.ga_len - 1); for (;;) { if (cur_si->si_ends && (cur_si->si_m_endpos.lnum < current_lnum || (cur_si->si_m_endpos.lnum == current_lnum && cur_si->si_m_endpos.col <= current_col))) { /* * If there is an end pattern group ID, highlight the end pattern * now. No need to pop the current item from the stack. * Only do this if the end pattern continues beyond the current * position. */ if (cur_si->si_end_idx && (cur_si->si_eoe_pos.lnum > current_lnum || (cur_si->si_eoe_pos.lnum == current_lnum && cur_si->si_eoe_pos.col > current_col))) { cur_si->si_idx = cur_si->si_end_idx; cur_si->si_end_idx = 0; cur_si->si_m_endpos = cur_si->si_eoe_pos; cur_si->si_h_endpos = cur_si->si_eoe_pos; cur_si->si_flags |= HL_MATCH; #ifdef FEAT_CONCEAL cur_si->si_seqnr = next_seqnr++; if (cur_si->si_flags & HL_CONCEALENDS) cur_si->si_flags |= HL_CONCEAL; #endif update_si_attr(current_state.ga_len - 1); /* nextgroup= should not match in the end pattern */ current_next_list = NULL; /* what matches next may be different now, clear it */ next_match_idx = 0; next_match_col = MAXCOL; break; } else { /* handle next_list, unless at end of line and no "skipnl" or * "skipempty" */ current_next_list = cur_si->si_next_list; current_next_flags = cur_si->si_flags; if (!(current_next_flags & (HL_SKIPNL | HL_SKIPEMPTY)) && syn_getcurline()[current_col] == NUL) current_next_list = NULL; /* When the ended item has "extend", another item with * "keepend" now needs to check for its end. */ had_extend = (cur_si->si_flags & HL_EXTEND); pop_current_state(); if (current_state.ga_len == 0) break; if (had_extend && keepend_level >= 0) { syn_update_ends(FALSE); if (current_state.ga_len == 0) break; } cur_si = &CUR_STATE(current_state.ga_len - 1); /* * Only for a region the search for the end continues after * the end of the contained item. If the contained match * included the end-of-line, break here, the region continues. * Don't do this when: * - "keepend" is used for the contained item * - not at the end of the line (could be end="x$"me=e-1). * - "excludenl" is used (HL_HAS_EOL won't be set) */ if (cur_si->si_idx >= 0 && SYN_ITEMS(syn_block)[cur_si->si_idx].sp_type == SPTYPE_START && !(cur_si->si_flags & (HL_MATCH | HL_KEEPEND))) { update_si_end(cur_si, (int)current_col, TRUE); check_keepend(); if ((current_next_flags & HL_HAS_EOL) && keepend_level < 0 && syn_getcurline()[current_col] == NUL) break; } } } else break; } } /* * Update an entry in the current_state stack for a match or region. This * fills in si_attr, si_next_list and si_cont_list. */ static void update_si_attr(idx) int idx; { stateitem_T *sip = &CUR_STATE(idx); synpat_T *spp; /* This should not happen... */ if (sip->si_idx < 0) return; spp = &(SYN_ITEMS(syn_block)[sip->si_idx]); if (sip->si_flags & HL_MATCH) sip->si_id = spp->sp_syn_match_id; else sip->si_id = spp->sp_syn.id; sip->si_attr = syn_id2attr(sip->si_id); sip->si_trans_id = sip->si_id; if (sip->si_flags & HL_MATCH) sip->si_cont_list = NULL; else sip->si_cont_list = spp->sp_cont_list; /* * For transparent items, take attr from outer item. * Also take cont_list, if there is none. * Don't do this for the matchgroup of a start or end pattern. */ if ((spp->sp_flags & HL_TRANSP) && !(sip->si_flags & HL_MATCH)) { if (idx == 0) { sip->si_attr = 0; sip->si_trans_id = 0; if (sip->si_cont_list == NULL) sip->si_cont_list = ID_LIST_ALL; } else { sip->si_attr = CUR_STATE(idx - 1).si_attr; sip->si_trans_id = CUR_STATE(idx - 1).si_trans_id; sip->si_h_startpos = CUR_STATE(idx - 1).si_h_startpos; sip->si_h_endpos = CUR_STATE(idx - 1).si_h_endpos; if (sip->si_cont_list == NULL) { sip->si_flags |= HL_TRANS_CONT; sip->si_cont_list = CUR_STATE(idx - 1).si_cont_list; } } } } /* * Check the current stack for patterns with "keepend" flag. * Propagate the match-end to contained items, until a "skipend" item is found. */ static void check_keepend() { int i; lpos_T maxpos; lpos_T maxpos_h; stateitem_T *sip; /* * This check can consume a lot of time; only do it from the level where * there really is a keepend. */ if (keepend_level < 0) return; /* * Find the last index of an "extend" item. "keepend" items before that * won't do anything. If there is no "extend" item "i" will be * "keepend_level" and all "keepend" items will work normally. */ for (i = current_state.ga_len - 1; i > keepend_level; --i) if (CUR_STATE(i).si_flags & HL_EXTEND) break; maxpos.lnum = 0; maxpos.col = 0; maxpos_h.lnum = 0; maxpos_h.col = 0; for ( ; i < current_state.ga_len; ++i) { sip = &CUR_STATE(i); if (maxpos.lnum != 0) { limit_pos_zero(&sip->si_m_endpos, &maxpos); limit_pos_zero(&sip->si_h_endpos, &maxpos_h); limit_pos_zero(&sip->si_eoe_pos, &maxpos); sip->si_ends = TRUE; } if (sip->si_ends && (sip->si_flags & HL_KEEPEND)) { if (maxpos.lnum == 0 || maxpos.lnum > sip->si_m_endpos.lnum || (maxpos.lnum == sip->si_m_endpos.lnum && maxpos.col > sip->si_m_endpos.col)) maxpos = sip->si_m_endpos; if (maxpos_h.lnum == 0 || maxpos_h.lnum > sip->si_h_endpos.lnum || (maxpos_h.lnum == sip->si_h_endpos.lnum && maxpos_h.col > sip->si_h_endpos.col)) maxpos_h = sip->si_h_endpos; } } } /* * Update an entry in the current_state stack for a start-skip-end pattern. * This finds the end of the current item, if it's in the current line. * * Return the flags for the matched END. */ static void update_si_end(sip, startcol, force) stateitem_T *sip; int startcol; /* where to start searching for the end */ int force; /* when TRUE overrule a previous end */ { lpos_T startpos; lpos_T endpos; lpos_T hl_endpos; lpos_T end_endpos; int end_idx; /* return quickly for a keyword */ if (sip->si_idx < 0) return; /* Don't update when it's already done. Can be a match of an end pattern * that started in a previous line. Watch out: can also be a "keepend" * from a containing item. */ if (!force && sip->si_m_endpos.lnum >= current_lnum) return; /* * We need to find the end of the region. It may continue in the next * line. */ end_idx = 0; startpos.lnum = current_lnum; startpos.col = startcol; find_endpos(sip->si_idx, &startpos, &endpos, &hl_endpos, &(sip->si_flags), &end_endpos, &end_idx, sip->si_extmatch); if (endpos.lnum == 0) { /* No end pattern matched. */ if (SYN_ITEMS(syn_block)[sip->si_idx].sp_flags & HL_ONELINE) { /* a "oneline" never continues in the next line */ sip->si_ends = TRUE; sip->si_m_endpos.lnum = current_lnum; sip->si_m_endpos.col = (colnr_T)STRLEN(syn_getcurline()); } else { /* continues in the next line */ sip->si_ends = FALSE; sip->si_m_endpos.lnum = 0; } sip->si_h_endpos = sip->si_m_endpos; } else { /* match within this line */ sip->si_m_endpos = endpos; sip->si_h_endpos = hl_endpos; sip->si_eoe_pos = end_endpos; sip->si_ends = TRUE; sip->si_end_idx = end_idx; } } /* * Add a new state to the current state stack. * It is cleared and the index set to "idx". * Return FAIL if it's not possible (out of memory). */ static int push_current_state(idx) int idx; { if (ga_grow(&current_state, 1) == FAIL) return FAIL; vim_memset(&CUR_STATE(current_state.ga_len), 0, sizeof(stateitem_T)); CUR_STATE(current_state.ga_len).si_idx = idx; ++current_state.ga_len; return OK; } /* * Remove a state from the current_state stack. */ static void pop_current_state() { if (current_state.ga_len) { unref_extmatch(CUR_STATE(current_state.ga_len - 1).si_extmatch); --current_state.ga_len; } /* after the end of a pattern, try matching a keyword or pattern */ next_match_idx = -1; /* if first state with "keepend" is popped, reset keepend_level */ if (keepend_level >= current_state.ga_len) keepend_level = -1; } /* * Find the end of a start/skip/end syntax region after "startpos". * Only checks one line. * Also handles a match item that continued from a previous line. * If not found, the syntax item continues in the next line. m_endpos->lnum * will be 0. * If found, the end of the region and the end of the highlighting is * computed. */ static void find_endpos(idx, startpos, m_endpos, hl_endpos, flagsp, end_endpos, end_idx, start_ext) int idx; /* index of the pattern */ lpos_T *startpos; /* where to start looking for an END match */ lpos_T *m_endpos; /* return: end of match */ lpos_T *hl_endpos; /* return: end of highlighting */ long *flagsp; /* return: flags of matching END */ lpos_T *end_endpos; /* return: end of end pattern match */ int *end_idx; /* return: group ID for end pat. match, or 0 */ reg_extmatch_T *start_ext; /* submatches from the start pattern */ { colnr_T matchcol; synpat_T *spp, *spp_skip; int start_idx; int best_idx; regmmatch_T regmatch; regmmatch_T best_regmatch; /* startpos/endpos of best match */ lpos_T pos; char_u *line; int had_match = FALSE; /* just in case we are invoked for a keyword */ if (idx < 0) return; /* * Check for being called with a START pattern. * Can happen with a match that continues to the next line, because it * contained a region. */ spp = &(SYN_ITEMS(syn_block)[idx]); if (spp->sp_type != SPTYPE_START) { *hl_endpos = *startpos; return; } /* * Find the SKIP or first END pattern after the last START pattern. */ for (;;) { spp = &(SYN_ITEMS(syn_block)[idx]); if (spp->sp_type != SPTYPE_START) break; ++idx; } /* * Lookup the SKIP pattern (if present) */ if (spp->sp_type == SPTYPE_SKIP) { spp_skip = spp; ++idx; } else spp_skip = NULL; /* Setup external matches for syn_regexec(). */ unref_extmatch(re_extmatch_in); re_extmatch_in = ref_extmatch(start_ext); matchcol = startpos->col; /* start looking for a match at sstart */ start_idx = idx; /* remember the first END pattern. */ best_regmatch.startpos[0].col = 0; /* avoid compiler warning */ for (;;) { /* * Find end pattern that matches first after "matchcol". */ best_idx = -1; for (idx = start_idx; idx < syn_block->b_syn_patterns.ga_len; ++idx) { int lc_col = matchcol; spp = &(SYN_ITEMS(syn_block)[idx]); if (spp->sp_type != SPTYPE_END) /* past last END pattern */ break; lc_col -= spp->sp_offsets[SPO_LC_OFF]; if (lc_col < 0) lc_col = 0; regmatch.rmm_ic = spp->sp_ic; regmatch.regprog = spp->sp_prog; if (syn_regexec(&regmatch, startpos->lnum, lc_col)) { if (best_idx == -1 || regmatch.startpos[0].col < best_regmatch.startpos[0].col) { best_idx = idx; best_regmatch.startpos[0] = regmatch.startpos[0]; best_regmatch.endpos[0] = regmatch.endpos[0]; } } } /* * If all end patterns have been tried, and there is no match, the * item continues until end-of-line. */ if (best_idx == -1) break; /* * If the skip pattern matches before the end pattern, * continue searching after the skip pattern. */ if (spp_skip != NULL) { int lc_col = matchcol - spp_skip->sp_offsets[SPO_LC_OFF]; if (lc_col < 0) lc_col = 0; regmatch.rmm_ic = spp_skip->sp_ic; regmatch.regprog = spp_skip->sp_prog; if (syn_regexec(&regmatch, startpos->lnum, lc_col) && regmatch.startpos[0].col <= best_regmatch.startpos[0].col) { /* Add offset to skip pattern match */ syn_add_end_off(&pos, &regmatch, spp_skip, SPO_ME_OFF, 1); /* If the skip pattern goes on to the next line, there is no * match with an end pattern in this line. */ if (pos.lnum > startpos->lnum) break; line = ml_get_buf(syn_buf, startpos->lnum, FALSE); /* take care of an empty match or negative offset */ if (pos.col <= matchcol) ++matchcol; else if (pos.col <= regmatch.endpos[0].col) matchcol = pos.col; else /* Be careful not to jump over the NUL at the end-of-line */ for (matchcol = regmatch.endpos[0].col; line[matchcol] != NUL && matchcol < pos.col; ++matchcol) ; /* if the skip pattern includes end-of-line, break here */ if (line[matchcol] == NUL) break; continue; /* start with first end pattern again */ } } /* * Match from start pattern to end pattern. * Correct for match and highlight offset of end pattern. */ spp = &(SYN_ITEMS(syn_block)[best_idx]); syn_add_end_off(m_endpos, &best_regmatch, spp, SPO_ME_OFF, 1); /* can't end before the start */ if (m_endpos->lnum == startpos->lnum && m_endpos->col < startpos->col) m_endpos->col = startpos->col; syn_add_end_off(end_endpos, &best_regmatch, spp, SPO_HE_OFF, 1); /* can't end before the start */ if (end_endpos->lnum == startpos->lnum && end_endpos->col < startpos->col) end_endpos->col = startpos->col; /* can't end after the match */ limit_pos(end_endpos, m_endpos); /* * If the end group is highlighted differently, adjust the pointers. */ if (spp->sp_syn_match_id != spp->sp_syn.id && spp->sp_syn_match_id != 0) { *end_idx = best_idx; if (spp->sp_off_flags & (1 << (SPO_RE_OFF + SPO_COUNT))) { hl_endpos->lnum = best_regmatch.endpos[0].lnum; hl_endpos->col = best_regmatch.endpos[0].col; } else { hl_endpos->lnum = best_regmatch.startpos[0].lnum; hl_endpos->col = best_regmatch.startpos[0].col; } hl_endpos->col += spp->sp_offsets[SPO_RE_OFF]; /* can't end before the start */ if (hl_endpos->lnum == startpos->lnum && hl_endpos->col < startpos->col) hl_endpos->col = startpos->col; limit_pos(hl_endpos, m_endpos); /* now the match ends where the highlighting ends, it is turned * into the matchgroup for the end */ *m_endpos = *hl_endpos; } else { *end_idx = 0; *hl_endpos = *end_endpos; } *flagsp = spp->sp_flags; had_match = TRUE; break; } /* no match for an END pattern in this line */ if (!had_match) m_endpos->lnum = 0; /* Remove external matches. */ unref_extmatch(re_extmatch_in); re_extmatch_in = NULL; } /* * Limit "pos" not to be after "limit". */ static void limit_pos(pos, limit) lpos_T *pos; lpos_T *limit; { if (pos->lnum > limit->lnum) *pos = *limit; else if (pos->lnum == limit->lnum && pos->col > limit->col) pos->col = limit->col; } /* * Limit "pos" not to be after "limit", unless pos->lnum is zero. */ static void limit_pos_zero(pos, limit) lpos_T *pos; lpos_T *limit; { if (pos->lnum == 0) *pos = *limit; else limit_pos(pos, limit); } /* * Add offset to matched text for end of match or highlight. */ static void syn_add_end_off(result, regmatch, spp, idx, extra) lpos_T *result; /* returned position */ regmmatch_T *regmatch; /* start/end of match */ synpat_T *spp; /* matched pattern */ int idx; /* index of offset */ int extra; /* extra chars for offset to start */ { int col; int off; char_u *base; char_u *p; if (spp->sp_off_flags & (1 << idx)) { result->lnum = regmatch->startpos[0].lnum; col = regmatch->startpos[0].col; off = spp->sp_offsets[idx] + extra; } else { result->lnum = regmatch->endpos[0].lnum; col = regmatch->endpos[0].col; off = spp->sp_offsets[idx]; } /* Don't go past the end of the line. Matters for "rs=e+2" when there * is a matchgroup. Watch out for match with last NL in the buffer. */ if (result->lnum > syn_buf->b_ml.ml_line_count) col = 0; else if (off != 0) { base = ml_get_buf(syn_buf, result->lnum, FALSE); p = base + col; if (off > 0) { while (off-- > 0 && *p != NUL) mb_ptr_adv(p); } else if (off < 0) { while (off++ < 0 && base < p) mb_ptr_back(base, p); } col = (int)(p - base); } result->col = col; } /* * Add offset to matched text for start of match or highlight. * Avoid resulting column to become negative. */ static void syn_add_start_off(result, regmatch, spp, idx, extra) lpos_T *result; /* returned position */ regmmatch_T *regmatch; /* start/end of match */ synpat_T *spp; int idx; int extra; /* extra chars for offset to end */ { int col; int off; char_u *base; char_u *p; if (spp->sp_off_flags & (1 << (idx + SPO_COUNT))) { result->lnum = regmatch->endpos[0].lnum; col = regmatch->endpos[0].col; off = spp->sp_offsets[idx] + extra; } else { result->lnum = regmatch->startpos[0].lnum; col = regmatch->startpos[0].col; off = spp->sp_offsets[idx]; } if (result->lnum > syn_buf->b_ml.ml_line_count) { /* a "\n" at the end of the pattern may take us below the last line */ result->lnum = syn_buf->b_ml.ml_line_count; col = (int)STRLEN(ml_get_buf(syn_buf, result->lnum, FALSE)); } if (off != 0) { base = ml_get_buf(syn_buf, result->lnum, FALSE); p = base + col; if (off > 0) { while (off-- && *p != NUL) mb_ptr_adv(p); } else if (off < 0) { while (off++ && base < p) mb_ptr_back(base, p); } col = (int)(p - base); } result->col = col; } /* * Get current line in syntax buffer. */ static char_u * syn_getcurline() { return ml_get_buf(syn_buf, current_lnum, FALSE); } /* * Call vim_regexec() to find a match with "rmp" in "syn_buf". * Returns TRUE when there is a match. */ static int syn_regexec(rmp, lnum, col) regmmatch_T *rmp; linenr_T lnum; colnr_T col; { rmp->rmm_maxcol = syn_buf->b_p_smc; if (vim_regexec_multi(rmp, syn_win, syn_buf, lnum, col, NULL) > 0) { rmp->startpos[0].lnum += lnum; rmp->endpos[0].lnum += lnum; return TRUE; } return FALSE; } /* * Check one position in a line for a matching keyword. * The caller must check if a keyword can start at startcol. * Return it's ID if found, 0 otherwise. */ static int check_keyword_id(line, startcol, endcolp, flagsp, next_listp, cur_si, ccharp) char_u *line; int startcol; /* position in line to check for keyword */ int *endcolp; /* return: character after found keyword */ long *flagsp; /* return: flags of matching keyword */ short **next_listp; /* return: next_list of matching keyword */ stateitem_T *cur_si; /* item at the top of the stack */ int *ccharp UNUSED; /* conceal substitution char */ { keyentry_T *kp; char_u *kwp; int round; int kwlen; char_u keyword[MAXKEYWLEN + 1]; /* assume max. keyword len is 80 */ hashtab_T *ht; hashitem_T *hi; /* Find first character after the keyword. First character was already * checked. */ kwp = line + startcol; kwlen = 0; do { #ifdef FEAT_MBYTE if (has_mbyte) kwlen += (*mb_ptr2len)(kwp + kwlen); else #endif ++kwlen; } while (vim_iswordc_buf(kwp + kwlen, syn_buf)); if (kwlen > MAXKEYWLEN) return 0; /* * Must make a copy of the keyword, so we can add a NUL and make it * lowercase. */ vim_strncpy(keyword, kwp, kwlen); /* * Try twice: * 1. matching case * 2. ignoring case */ for (round = 1; round <= 2; ++round) { ht = round == 1 ? &syn_block->b_keywtab : &syn_block->b_keywtab_ic; if (ht->ht_used == 0) continue; if (round == 2) /* ignore case */ (void)str_foldcase(kwp, kwlen, keyword, MAXKEYWLEN + 1); /* * Find keywords that match. There can be several with different * attributes. * When current_next_list is non-zero accept only that group, otherwise: * Accept a not-contained keyword at toplevel. * Accept a keyword at other levels only if it is in the contains list. */ hi = hash_find(ht, keyword); if (!HASHITEM_EMPTY(hi)) for (kp = HI2KE(hi); kp != NULL; kp = kp->ke_next) { if (current_next_list != 0 ? in_id_list(NULL, current_next_list, &kp->k_syn, 0) : (cur_si == NULL ? !(kp->flags & HL_CONTAINED) : in_id_list(cur_si, cur_si->si_cont_list, &kp->k_syn, kp->flags & HL_CONTAINED))) { *endcolp = startcol + kwlen; *flagsp = kp->flags; *next_listp = kp->next_list; #ifdef FEAT_CONCEAL *ccharp = kp->k_char; #endif return kp->k_syn.id; } } } return 0; } /* * Handle ":syntax conceal" command. */ static void syn_cmd_conceal(eap, syncing) exarg_T *eap UNUSED; int syncing UNUSED; { #ifdef FEAT_CONCEAL char_u *arg = eap->arg; char_u *next; eap->nextcmd = find_nextcmd(arg); if (eap->skip) return; next = skiptowhite(arg); if (STRNICMP(arg, "on", 2) == 0 && next - arg == 2) curwin->w_s->b_syn_conceal = TRUE; else if (STRNICMP(arg, "off", 3) == 0 && next - arg == 3) curwin->w_s->b_syn_conceal = FALSE; else EMSG2(_("E390: Illegal argument: %s"), arg); #endif } /* * Handle ":syntax case" command. */ static void syn_cmd_case(eap, syncing) exarg_T *eap; int syncing UNUSED; { char_u *arg = eap->arg; char_u *next; eap->nextcmd = find_nextcmd(arg); if (eap->skip) return; next = skiptowhite(arg); if (STRNICMP(arg, "match", 5) == 0 && next - arg == 5) curwin->w_s->b_syn_ic = FALSE; else if (STRNICMP(arg, "ignore", 6) == 0 && next - arg == 6) curwin->w_s->b_syn_ic = TRUE; else EMSG2(_("E390: Illegal argument: %s"), arg); } /* * Handle ":syntax spell" command. */ static void syn_cmd_spell(eap, syncing) exarg_T *eap; int syncing UNUSED; { char_u *arg = eap->arg; char_u *next; eap->nextcmd = find_nextcmd(arg); if (eap->skip) return; next = skiptowhite(arg); if (STRNICMP(arg, "toplevel", 8) == 0 && next - arg == 8) curwin->w_s->b_syn_spell = SYNSPL_TOP; else if (STRNICMP(arg, "notoplevel", 10) == 0 && next - arg == 10) curwin->w_s->b_syn_spell = SYNSPL_NOTOP; else if (STRNICMP(arg, "default", 7) == 0 && next - arg == 7) curwin->w_s->b_syn_spell = SYNSPL_DEFAULT; else EMSG2(_("E390: Illegal argument: %s"), arg); } /* * Clear all syntax info for one buffer. */ void syntax_clear(block) synblock_T *block; { int i; block->b_syn_error = FALSE; /* clear previous error */ block->b_syn_ic = FALSE; /* Use case, by default */ block->b_syn_spell = SYNSPL_DEFAULT; /* default spell checking */ block->b_syn_containedin = FALSE; /* free the keywords */ clear_keywtab(&block->b_keywtab); clear_keywtab(&block->b_keywtab_ic); /* free the syntax patterns */ for (i = block->b_syn_patterns.ga_len; --i >= 0; ) syn_clear_pattern(block, i); ga_clear(&block->b_syn_patterns); /* free the syntax clusters */ for (i = block->b_syn_clusters.ga_len; --i >= 0; ) syn_clear_cluster(block, i); ga_clear(&block->b_syn_clusters); block->b_spell_cluster_id = 0; block->b_nospell_cluster_id = 0; block->b_syn_sync_flags = 0; block->b_syn_sync_minlines = 0; block->b_syn_sync_maxlines = 0; block->b_syn_sync_linebreaks = 0; vim_free(block->b_syn_linecont_prog); block->b_syn_linecont_prog = NULL; vim_free(block->b_syn_linecont_pat); block->b_syn_linecont_pat = NULL; #ifdef FEAT_FOLDING block->b_syn_folditems = 0; #endif /* free the stored states */ syn_stack_free_all(block); invalidate_current_state(); /* Reset the counter for ":syn include" */ running_syn_inc_tag = 0; } /* * Get rid of ownsyntax for window "wp". */ void reset_synblock(wp) win_T *wp; { if (wp->w_s != &wp->w_buffer->b_s) { syntax_clear(wp->w_s); vim_free(wp->w_s); wp->w_s = &wp->w_buffer->b_s; } } /* * Clear syncing info for one buffer. */ static void syntax_sync_clear() { int i; /* free the syntax patterns */ for (i = curwin->w_s->b_syn_patterns.ga_len; --i >= 0; ) if (SYN_ITEMS(curwin->w_s)[i].sp_syncing) syn_remove_pattern(curwin->w_s, i); curwin->w_s->b_syn_sync_flags = 0; curwin->w_s->b_syn_sync_minlines = 0; curwin->w_s->b_syn_sync_maxlines = 0; curwin->w_s->b_syn_sync_linebreaks = 0; vim_free(curwin->w_s->b_syn_linecont_prog); curwin->w_s->b_syn_linecont_prog = NULL; vim_free(curwin->w_s->b_syn_linecont_pat); curwin->w_s->b_syn_linecont_pat = NULL; syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ } /* * Remove one pattern from the buffer's pattern list. */ static void syn_remove_pattern(block, idx) synblock_T *block; int idx; { synpat_T *spp; spp = &(SYN_ITEMS(block)[idx]); #ifdef FEAT_FOLDING if (spp->sp_flags & HL_FOLD) --block->b_syn_folditems; #endif syn_clear_pattern(block, idx); mch_memmove(spp, spp + 1, sizeof(synpat_T) * (block->b_syn_patterns.ga_len - idx - 1)); --block->b_syn_patterns.ga_len; } /* * Clear and free one syntax pattern. When clearing all, must be called from * last to first! */ static void syn_clear_pattern(block, i) synblock_T *block; int i; { vim_free(SYN_ITEMS(block)[i].sp_pattern); vim_free(SYN_ITEMS(block)[i].sp_prog); /* Only free sp_cont_list and sp_next_list of first start pattern */ if (i == 0 || SYN_ITEMS(block)[i - 1].sp_type != SPTYPE_START) { vim_free(SYN_ITEMS(block)[i].sp_cont_list); vim_free(SYN_ITEMS(block)[i].sp_next_list); vim_free(SYN_ITEMS(block)[i].sp_syn.cont_in_list); } } /* * Clear and free one syntax cluster. */ static void syn_clear_cluster(block, i) synblock_T *block; int i; { vim_free(SYN_CLSTR(block)[i].scl_name); vim_free(SYN_CLSTR(block)[i].scl_name_u); vim_free(SYN_CLSTR(block)[i].scl_list); } /* * Handle ":syntax clear" command. */ static void syn_cmd_clear(eap, syncing) exarg_T *eap; int syncing; { char_u *arg = eap->arg; char_u *arg_end; int id; eap->nextcmd = find_nextcmd(arg); if (eap->skip) return; /* * We have to disable this within ":syn include @group filename", * because otherwise @group would get deleted. * Only required for Vim 5.x syntax files, 6.0 ones don't contain ":syn * clear". */ if (curwin->w_s->b_syn_topgrp != 0) return; if (ends_excmd(*arg)) { /* * No argument: Clear all syntax items. */ if (syncing) syntax_sync_clear(); else { syntax_clear(curwin->w_s); if (curwin->w_s == &curwin->w_buffer->b_s) do_unlet((char_u *)"b:current_syntax", TRUE); do_unlet((char_u *)"w:current_syntax", TRUE); } } else { /* * Clear the group IDs that are in the argument. */ while (!ends_excmd(*arg)) { arg_end = skiptowhite(arg); if (*arg == '@') { id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1)); if (id == 0) { EMSG2(_("E391: No such syntax cluster: %s"), arg); break; } else { /* * We can't physically delete a cluster without changing * the IDs of other clusters, so we do the next best thing * and make it empty. */ short scl_id = id - SYNID_CLUSTER; vim_free(SYN_CLSTR(curwin->w_s)[scl_id].scl_list); SYN_CLSTR(curwin->w_s)[scl_id].scl_list = NULL; } } else { id = syn_namen2id(arg, (int)(arg_end - arg)); if (id == 0) { EMSG2(_(e_nogroup), arg); break; } else syn_clear_one(id, syncing); } arg = skipwhite(arg_end); } } redraw_curbuf_later(SOME_VALID); syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ } /* * Clear one syntax group for the current buffer. */ static void syn_clear_one(id, syncing) int id; int syncing; { synpat_T *spp; int idx; /* Clear keywords only when not ":syn sync clear group-name" */ if (!syncing) { (void)syn_clear_keyword(id, &curwin->w_s->b_keywtab); (void)syn_clear_keyword(id, &curwin->w_s->b_keywtab_ic); } /* clear the patterns for "id" */ for (idx = curwin->w_s->b_syn_patterns.ga_len; --idx >= 0; ) { spp = &(SYN_ITEMS(curwin->w_s)[idx]); if (spp->sp_syn.id != id || spp->sp_syncing != syncing) continue; syn_remove_pattern(curwin->w_s, idx); } } /* * Handle ":syntax on" command. */ static void syn_cmd_on(eap, syncing) exarg_T *eap; int syncing UNUSED; { syn_cmd_onoff(eap, "syntax"); } /* * Handle ":syntax enable" command. */ static void syn_cmd_enable(eap, syncing) exarg_T *eap; int syncing UNUSED; { set_internal_string_var((char_u *)"syntax_cmd", (char_u *)"enable"); syn_cmd_onoff(eap, "syntax"); do_unlet((char_u *)"g:syntax_cmd", TRUE); } /* * Handle ":syntax reset" command. */ static void syn_cmd_reset(eap, syncing) exarg_T *eap; int syncing UNUSED; { eap->nextcmd = check_nextcmd(eap->arg); if (!eap->skip) { set_internal_string_var((char_u *)"syntax_cmd", (char_u *)"reset"); do_cmdline_cmd((char_u *)"runtime! syntax/syncolor.vim"); do_unlet((char_u *)"g:syntax_cmd", TRUE); } } /* * Handle ":syntax manual" command. */ static void syn_cmd_manual(eap, syncing) exarg_T *eap; int syncing UNUSED; { syn_cmd_onoff(eap, "manual"); } /* * Handle ":syntax off" command. */ static void syn_cmd_off(eap, syncing) exarg_T *eap; int syncing UNUSED; { syn_cmd_onoff(eap, "nosyntax"); } static void syn_cmd_onoff(eap, name) exarg_T *eap; char *name; { char_u buf[100]; eap->nextcmd = check_nextcmd(eap->arg); if (!eap->skip) { STRCPY(buf, "so "); vim_snprintf((char *)buf + 3, sizeof(buf) - 3, SYNTAX_FNAME, name); do_cmdline_cmd(buf); } } /* * Handle ":syntax [list]" command: list current syntax words. */ static void syn_cmd_list(eap, syncing) exarg_T *eap; int syncing; /* when TRUE: list syncing items */ { char_u *arg = eap->arg; int id; char_u *arg_end; eap->nextcmd = find_nextcmd(arg); if (eap->skip) return; if (!syntax_present(curwin)) { MSG(_("No Syntax items defined for this buffer")); return; } if (syncing) { if (curwin->w_s->b_syn_sync_flags & SF_CCOMMENT) { MSG_PUTS(_("syncing on C-style comments")); syn_lines_msg(); syn_match_msg(); return; } else if (!(curwin->w_s->b_syn_sync_flags & SF_MATCH)) { if (curwin->w_s->b_syn_sync_minlines == 0) MSG_PUTS(_("no syncing")); else { MSG_PUTS(_("syncing starts ")); msg_outnum(curwin->w_s->b_syn_sync_minlines); MSG_PUTS(_(" lines before top line")); syn_match_msg(); } return; } MSG_PUTS_TITLE(_("\n--- Syntax sync items ---")); if (curwin->w_s->b_syn_sync_minlines > 0 || curwin->w_s->b_syn_sync_maxlines > 0 || curwin->w_s->b_syn_sync_linebreaks > 0) { MSG_PUTS(_("\nsyncing on items")); syn_lines_msg(); syn_match_msg(); } } else MSG_PUTS_TITLE(_("\n--- Syntax items ---")); if (ends_excmd(*arg)) { /* * No argument: List all group IDs and all syntax clusters. */ for (id = 1; id <= highlight_ga.ga_len && !got_int; ++id) syn_list_one(id, syncing, FALSE); for (id = 0; id < curwin->w_s->b_syn_clusters.ga_len && !got_int; ++id) syn_list_cluster(id); } else { /* * List the group IDs and syntax clusters that are in the argument. */ while (!ends_excmd(*arg) && !got_int) { arg_end = skiptowhite(arg); if (*arg == '@') { id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1)); if (id == 0) EMSG2(_("E392: No such syntax cluster: %s"), arg); else syn_list_cluster(id - SYNID_CLUSTER); } else { id = syn_namen2id(arg, (int)(arg_end - arg)); if (id == 0) EMSG2(_(e_nogroup), arg); else syn_list_one(id, syncing, TRUE); } arg = skipwhite(arg_end); } } eap->nextcmd = check_nextcmd(arg); } static void syn_lines_msg() { if (curwin->w_s->b_syn_sync_maxlines > 0 || curwin->w_s->b_syn_sync_minlines > 0) { MSG_PUTS("; "); if (curwin->w_s->b_syn_sync_minlines > 0) { MSG_PUTS(_("minimal ")); msg_outnum(curwin->w_s->b_syn_sync_minlines); if (curwin->w_s->b_syn_sync_maxlines) MSG_PUTS(", "); } if (curwin->w_s->b_syn_sync_maxlines > 0) { MSG_PUTS(_("maximal ")); msg_outnum(curwin->w_s->b_syn_sync_maxlines); } MSG_PUTS(_(" lines before top line")); } } static void syn_match_msg() { if (curwin->w_s->b_syn_sync_linebreaks > 0) { MSG_PUTS(_("; match ")); msg_outnum(curwin->w_s->b_syn_sync_linebreaks); MSG_PUTS(_(" line breaks")); } } static int last_matchgroup; struct name_list { int flag; char *name; }; static void syn_list_flags __ARGS((struct name_list *nl, int flags, int attr)); /* * List one syntax item, for ":syntax" or "syntax list syntax_name". */ static void syn_list_one(id, syncing, link_only) int id; int syncing; /* when TRUE: list syncing items */ int link_only; /* when TRUE; list link-only too */ { int attr; int idx; int did_header = FALSE; synpat_T *spp; static struct name_list namelist1[] = { {HL_DISPLAY, "display"}, {HL_CONTAINED, "contained"}, {HL_ONELINE, "oneline"}, {HL_KEEPEND, "keepend"}, {HL_EXTEND, "extend"}, {HL_EXCLUDENL, "excludenl"}, {HL_TRANSP, "transparent"}, {HL_FOLD, "fold"}, #ifdef FEAT_CONCEAL {HL_CONCEAL, "conceal"}, {HL_CONCEALENDS, "concealends"}, #endif {0, NULL} }; static struct name_list namelist2[] = { {HL_SKIPWHITE, "skipwhite"}, {HL_SKIPNL, "skipnl"}, {HL_SKIPEMPTY, "skipempty"}, {0, NULL} }; attr = hl_attr(HLF_D); /* highlight like directories */ /* list the keywords for "id" */ if (!syncing) { did_header = syn_list_keywords(id, &curwin->w_s->b_keywtab, FALSE, attr); did_header = syn_list_keywords(id, &curwin->w_s->b_keywtab_ic, did_header, attr); } /* list the patterns for "id" */ for (idx = 0; idx < curwin->w_s->b_syn_patterns.ga_len && !got_int; ++idx) { spp = &(SYN_ITEMS(curwin->w_s)[idx]); if (spp->sp_syn.id != id || spp->sp_syncing != syncing) continue; (void)syn_list_header(did_header, 999, id); did_header = TRUE; last_matchgroup = 0; if (spp->sp_type == SPTYPE_MATCH) { put_pattern("match", ' ', spp, attr); msg_putchar(' '); } else if (spp->sp_type == SPTYPE_START) { while (SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_START) put_pattern("start", '=', &SYN_ITEMS(curwin->w_s)[idx++], attr); if (SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_SKIP) put_pattern("skip", '=', &SYN_ITEMS(curwin->w_s)[idx++], attr); while (idx < curwin->w_s->b_syn_patterns.ga_len && SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_END) put_pattern("end", '=', &SYN_ITEMS(curwin->w_s)[idx++], attr); --idx; msg_putchar(' '); } syn_list_flags(namelist1, spp->sp_flags, attr); if (spp->sp_cont_list != NULL) put_id_list((char_u *)"contains", spp->sp_cont_list, attr); if (spp->sp_syn.cont_in_list != NULL) put_id_list((char_u *)"containedin", spp->sp_syn.cont_in_list, attr); if (spp->sp_next_list != NULL) { put_id_list((char_u *)"nextgroup", spp->sp_next_list, attr); syn_list_flags(namelist2, spp->sp_flags, attr); } if (spp->sp_flags & (HL_SYNC_HERE|HL_SYNC_THERE)) { if (spp->sp_flags & HL_SYNC_HERE) msg_puts_attr((char_u *)"grouphere", attr); else msg_puts_attr((char_u *)"groupthere", attr); msg_putchar(' '); if (spp->sp_sync_idx >= 0) msg_outtrans(HL_TABLE()[SYN_ITEMS(curwin->w_s) [spp->sp_sync_idx].sp_syn.id - 1].sg_name); else MSG_PUTS("NONE"); msg_putchar(' '); } } /* list the link, if there is one */ if (HL_TABLE()[id - 1].sg_link && (did_header || link_only) && !got_int) { (void)syn_list_header(did_header, 999, id); msg_puts_attr((char_u *)"links to", attr); msg_putchar(' '); msg_outtrans(HL_TABLE()[HL_TABLE()[id - 1].sg_link - 1].sg_name); } } static void syn_list_flags(nlist, flags, attr) struct name_list *nlist; int flags; int attr; { int i; for (i = 0; nlist[i].flag != 0; ++i) if (flags & nlist[i].flag) { msg_puts_attr((char_u *)nlist[i].name, attr); msg_putchar(' '); } } /* * List one syntax cluster, for ":syntax" or "syntax list syntax_name". */ static void syn_list_cluster(id) int id; { int endcol = 15; /* slight hack: roughly duplicate the guts of syn_list_header() */ msg_putchar('\n'); msg_outtrans(SYN_CLSTR(curwin->w_s)[id].scl_name); if (msg_col >= endcol) /* output at least one space */ endcol = msg_col + 1; if (Columns <= endcol) /* avoid hang for tiny window */ endcol = Columns - 1; msg_advance(endcol); if (SYN_CLSTR(curwin->w_s)[id].scl_list != NULL) { put_id_list((char_u *)"cluster", SYN_CLSTR(curwin->w_s)[id].scl_list, hl_attr(HLF_D)); } else { msg_puts_attr((char_u *)"cluster", hl_attr(HLF_D)); msg_puts((char_u *)"=NONE"); } } static void put_id_list(name, list, attr) char_u *name; short *list; int attr; { short *p; msg_puts_attr(name, attr); msg_putchar('='); for (p = list; *p; ++p) { if (*p >= SYNID_ALLBUT && *p < SYNID_TOP) { if (p[1]) MSG_PUTS("ALLBUT"); else MSG_PUTS("ALL"); } else if (*p >= SYNID_TOP && *p < SYNID_CONTAINED) { MSG_PUTS("TOP"); } else if (*p >= SYNID_CONTAINED && *p < SYNID_CLUSTER) { MSG_PUTS("CONTAINED"); } else if (*p >= SYNID_CLUSTER) { short scl_id = *p - SYNID_CLUSTER; msg_putchar('@'); msg_outtrans(SYN_CLSTR(curwin->w_s)[scl_id].scl_name); } else msg_outtrans(HL_TABLE()[*p - 1].sg_name); if (p[1]) msg_putchar(','); } msg_putchar(' '); } static void put_pattern(s, c, spp, attr) char *s; int c; synpat_T *spp; int attr; { long n; int mask; int first; static char *sepchars = "/+=-#@\"|'^&"; int i; /* May have to write "matchgroup=group" */ if (last_matchgroup != spp->sp_syn_match_id) { last_matchgroup = spp->sp_syn_match_id; msg_puts_attr((char_u *)"matchgroup", attr); msg_putchar('='); if (last_matchgroup == 0) msg_outtrans((char_u *)"NONE"); else msg_outtrans(HL_TABLE()[last_matchgroup - 1].sg_name); msg_putchar(' '); } /* output the name of the pattern and an '=' or ' ' */ msg_puts_attr((char_u *)s, attr); msg_putchar(c); /* output the pattern, in between a char that is not in the pattern */ for (i = 0; vim_strchr(spp->sp_pattern, sepchars[i]) != NULL; ) if (sepchars[++i] == NUL) { i = 0; /* no good char found, just use the first one */ break; } msg_putchar(sepchars[i]); msg_outtrans(spp->sp_pattern); msg_putchar(sepchars[i]); /* output any pattern options */ first = TRUE; for (i = 0; i < SPO_COUNT; ++i) { mask = (1 << i); if (spp->sp_off_flags & (mask + (mask << SPO_COUNT))) { if (!first) msg_putchar(','); /* separate with commas */ msg_puts((char_u *)spo_name_tab[i]); n = spp->sp_offsets[i]; if (i != SPO_LC_OFF) { if (spp->sp_off_flags & mask) msg_putchar('s'); else msg_putchar('e'); if (n > 0) msg_putchar('+'); } if (n || i == SPO_LC_OFF) msg_outnum(n); first = FALSE; } } msg_putchar(' '); } /* * List or clear the keywords for one syntax group. * Return TRUE if the header has been printed. */ static int syn_list_keywords(id, ht, did_header, attr) int id; hashtab_T *ht; int did_header; /* header has already been printed */ int attr; { int outlen; hashitem_T *hi; keyentry_T *kp; int todo; int prev_contained = 0; short *prev_next_list = NULL; short *prev_cont_in_list = NULL; int prev_skipnl = 0; int prev_skipwhite = 0; int prev_skipempty = 0; /* * Unfortunately, this list of keywords is not sorted on alphabet but on * hash value... */ todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; for (kp = HI2KE(hi); kp != NULL && !got_int; kp = kp->ke_next) { if (kp->k_syn.id == id) { if (prev_contained != (kp->flags & HL_CONTAINED) || prev_skipnl != (kp->flags & HL_SKIPNL) || prev_skipwhite != (kp->flags & HL_SKIPWHITE) || prev_skipempty != (kp->flags & HL_SKIPEMPTY) || prev_cont_in_list != kp->k_syn.cont_in_list || prev_next_list != kp->next_list) outlen = 9999; else outlen = (int)STRLEN(kp->keyword); /* output "contained" and "nextgroup" on each line */ if (syn_list_header(did_header, outlen, id)) { prev_contained = 0; prev_next_list = NULL; prev_cont_in_list = NULL; prev_skipnl = 0; prev_skipwhite = 0; prev_skipempty = 0; } did_header = TRUE; if (prev_contained != (kp->flags & HL_CONTAINED)) { msg_puts_attr((char_u *)"contained", attr); msg_putchar(' '); prev_contained = (kp->flags & HL_CONTAINED); } if (kp->k_syn.cont_in_list != prev_cont_in_list) { put_id_list((char_u *)"containedin", kp->k_syn.cont_in_list, attr); msg_putchar(' '); prev_cont_in_list = kp->k_syn.cont_in_list; } if (kp->next_list != prev_next_list) { put_id_list((char_u *)"nextgroup", kp->next_list, attr); msg_putchar(' '); prev_next_list = kp->next_list; if (kp->flags & HL_SKIPNL) { msg_puts_attr((char_u *)"skipnl", attr); msg_putchar(' '); prev_skipnl = (kp->flags & HL_SKIPNL); } if (kp->flags & HL_SKIPWHITE) { msg_puts_attr((char_u *)"skipwhite", attr); msg_putchar(' '); prev_skipwhite = (kp->flags & HL_SKIPWHITE); } if (kp->flags & HL_SKIPEMPTY) { msg_puts_attr((char_u *)"skipempty", attr); msg_putchar(' '); prev_skipempty = (kp->flags & HL_SKIPEMPTY); } } msg_outtrans(kp->keyword); } } } } return did_header; } static void syn_clear_keyword(id, ht) int id; hashtab_T *ht; { hashitem_T *hi; keyentry_T *kp; keyentry_T *kp_prev; keyentry_T *kp_next; int todo; hash_lock(ht); todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; kp_prev = NULL; for (kp = HI2KE(hi); kp != NULL; ) { if (kp->k_syn.id == id) { kp_next = kp->ke_next; if (kp_prev == NULL) { if (kp_next == NULL) hash_remove(ht, hi); else hi->hi_key = KE2HIKEY(kp_next); } else kp_prev->ke_next = kp_next; vim_free(kp->next_list); vim_free(kp->k_syn.cont_in_list); vim_free(kp); kp = kp_next; } else { kp_prev = kp; kp = kp->ke_next; } } } } hash_unlock(ht); } /* * Clear a whole keyword table. */ static void clear_keywtab(ht) hashtab_T *ht; { hashitem_T *hi; int todo; keyentry_T *kp; keyentry_T *kp_next; todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; for (kp = HI2KE(hi); kp != NULL; kp = kp_next) { kp_next = kp->ke_next; vim_free(kp->next_list); vim_free(kp->k_syn.cont_in_list); vim_free(kp); } } } hash_clear(ht); hash_init(ht); } /* * Add a keyword to the list of keywords. */ static void add_keyword(name, id, flags, cont_in_list, next_list, conceal_char) char_u *name; /* name of keyword */ int id; /* group ID for this keyword */ int flags; /* flags for this keyword */ short *cont_in_list; /* containedin for this keyword */ short *next_list; /* nextgroup for this keyword */ int conceal_char; { keyentry_T *kp; hashtab_T *ht; hashitem_T *hi; char_u *name_ic; long_u hash; char_u name_folded[MAXKEYWLEN + 1]; if (curwin->w_s->b_syn_ic) name_ic = str_foldcase(name, (int)STRLEN(name), name_folded, MAXKEYWLEN + 1); else name_ic = name; kp = (keyentry_T *)alloc((int)(sizeof(keyentry_T) + STRLEN(name_ic))); if (kp == NULL) return; STRCPY(kp->keyword, name_ic); kp->k_syn.id = id; kp->k_syn.inc_tag = current_syn_inc_tag; kp->flags = flags; kp->k_char = conceal_char; kp->k_syn.cont_in_list = copy_id_list(cont_in_list); if (cont_in_list != NULL) curwin->w_s->b_syn_containedin = TRUE; kp->next_list = copy_id_list(next_list); if (curwin->w_s->b_syn_ic) ht = &curwin->w_s->b_keywtab_ic; else ht = &curwin->w_s->b_keywtab; hash = hash_hash(kp->keyword); hi = hash_lookup(ht, kp->keyword, hash); if (HASHITEM_EMPTY(hi)) { /* new keyword, add to hashtable */ kp->ke_next = NULL; hash_add_item(ht, hi, kp->keyword, hash); } else { /* keyword already exists, prepend to list */ kp->ke_next = HI2KE(hi); hi->hi_key = KE2HIKEY(kp); } } /* * Get the start and end of the group name argument. * Return a pointer to the first argument. * Return NULL if the end of the command was found instead of further args. */ static char_u * get_group_name(arg, name_end) char_u *arg; /* start of the argument */ char_u **name_end; /* pointer to end of the name */ { char_u *rest; *name_end = skiptowhite(arg); rest = skipwhite(*name_end); /* * Check if there are enough arguments. The first argument may be a * pattern, where '|' is allowed, so only check for NUL. */ if (ends_excmd(*arg) || *rest == NUL) return NULL; return rest; } /* * Check for syntax command option arguments. * This can be called at any place in the list of arguments, and just picks * out the arguments that are known. Can be called several times in a row to * collect all options in between other arguments. * Return a pointer to the next argument (which isn't an option). * Return NULL for any error; */ static char_u * get_syn_options(arg, opt, conceal_char) char_u *arg; /* next argument to be checked */ syn_opt_arg_T *opt; /* various things */ int *conceal_char UNUSED; { char_u *gname_start, *gname; int syn_id; int len; char *p; int i; int fidx; static struct flag { char *name; int argtype; int flags; } flagtab[] = { {"cCoOnNtTaAiInNeEdD", 0, HL_CONTAINED}, {"oOnNeElLiInNeE", 0, HL_ONELINE}, {"kKeEeEpPeEnNdD", 0, HL_KEEPEND}, {"eExXtTeEnNdD", 0, HL_EXTEND}, {"eExXcClLuUdDeEnNlL", 0, HL_EXCLUDENL}, {"tTrRaAnNsSpPaArReEnNtT", 0, HL_TRANSP}, {"sSkKiIpPnNlL", 0, HL_SKIPNL}, {"sSkKiIpPwWhHiItTeE", 0, HL_SKIPWHITE}, {"sSkKiIpPeEmMpPtTyY", 0, HL_SKIPEMPTY}, {"gGrRoOuUpPhHeErReE", 0, HL_SYNC_HERE}, {"gGrRoOuUpPtThHeErReE", 0, HL_SYNC_THERE}, {"dDiIsSpPlLaAyY", 0, HL_DISPLAY}, {"fFoOlLdD", 0, HL_FOLD}, {"cCoOnNcCeEaAlL", 0, HL_CONCEAL}, {"cCoOnNcCeEaAlLeEnNdDsS", 0, HL_CONCEALENDS}, {"cCcChHaArR", 11, 0}, {"cCoOnNtTaAiInNsS", 1, 0}, {"cCoOnNtTaAiInNeEdDiInN", 2, 0}, {"nNeExXtTgGrRoOuUpP", 3, 0}, }; static char *first_letters = "cCoOkKeEtTsSgGdDfFnN"; if (arg == NULL) /* already detected error */ return NULL; #ifdef FEAT_CONCEAL if (curwin->w_s->b_syn_conceal) opt->flags |= HL_CONCEAL; #endif for (;;) { /* * This is used very often when a large number of keywords is defined. * Need to skip quickly when no option name is found. * Also avoid tolower(), it's slow. */ if (strchr(first_letters, *arg) == NULL) break; for (fidx = sizeof(flagtab) / sizeof(struct flag); --fidx >= 0; ) { p = flagtab[fidx].name; for (i = 0, len = 0; p[i] != NUL; i += 2, ++len) if (arg[len] != p[i] && arg[len] != p[i + 1]) break; if (p[i] == NUL && (vim_iswhite(arg[len]) || (flagtab[fidx].argtype > 0 ? arg[len] == '=' : ends_excmd(arg[len])))) { if (opt->keyword && (flagtab[fidx].flags == HL_DISPLAY || flagtab[fidx].flags == HL_FOLD || flagtab[fidx].flags == HL_EXTEND)) /* treat "display", "fold" and "extend" as a keyword */ fidx = -1; break; } } if (fidx < 0) /* no match found */ break; if (flagtab[fidx].argtype == 1) { if (!opt->has_cont_list) { EMSG(_("E395: contains argument not accepted here")); return NULL; } if (get_id_list(&arg, 8, &opt->cont_list) == FAIL) return NULL; } else if (flagtab[fidx].argtype == 2) { if (get_id_list(&arg, 11, &opt->cont_in_list) == FAIL) return NULL; } else if (flagtab[fidx].argtype == 3) { if (get_id_list(&arg, 9, &opt->next_list) == FAIL) return NULL; } else if (flagtab[fidx].argtype == 11 && arg[5] == '=') { #ifdef FEAT_MBYTE /* cchar=? */ if (has_mbyte) { # ifdef FEAT_CONCEAL *conceal_char = mb_ptr2char(arg + 6); # endif arg += mb_ptr2len(arg + 6) - 1; } else #endif { #ifdef FEAT_CONCEAL *conceal_char = arg[6]; #else ; #endif } #ifdef FEAT_CONCEAL if (!vim_isprintc_strict(*conceal_char)) { EMSG(_("E844: invalid cchar value")); return NULL; } #endif arg = skipwhite(arg + 7); } else { opt->flags |= flagtab[fidx].flags; arg = skipwhite(arg + len); if (flagtab[fidx].flags == HL_SYNC_HERE || flagtab[fidx].flags == HL_SYNC_THERE) { if (opt->sync_idx == NULL) { EMSG(_("E393: group[t]here not accepted here")); return NULL; } gname_start = arg; arg = skiptowhite(arg); if (gname_start == arg) return NULL; gname = vim_strnsave(gname_start, (int)(arg - gname_start)); if (gname == NULL) return NULL; if (STRCMP(gname, "NONE") == 0) *opt->sync_idx = NONE_IDX; else { syn_id = syn_name2id(gname); for (i = curwin->w_s->b_syn_patterns.ga_len; --i >= 0; ) if (SYN_ITEMS(curwin->w_s)[i].sp_syn.id == syn_id && SYN_ITEMS(curwin->w_s)[i].sp_type == SPTYPE_START) { *opt->sync_idx = i; break; } if (i < 0) { EMSG2(_("E394: Didn't find region item for %s"), gname); vim_free(gname); return NULL; } } vim_free(gname); arg = skipwhite(arg); } #ifdef FEAT_FOLDING else if (flagtab[fidx].flags == HL_FOLD && foldmethodIsSyntax(curwin)) /* Need to update folds later. */ foldUpdateAll(curwin); #endif } } return arg; } /* * Adjustments to syntax item when declared in a ":syn include"'d file. * Set the contained flag, and if the item is not already contained, add it * to the specified top-level group, if any. */ static void syn_incl_toplevel(id, flagsp) int id; int *flagsp; { if ((*flagsp & HL_CONTAINED) || curwin->w_s->b_syn_topgrp == 0) return; *flagsp |= HL_CONTAINED; if (curwin->w_s->b_syn_topgrp >= SYNID_CLUSTER) { /* We have to alloc this, because syn_combine_list() will free it. */ short *grp_list = (short *)alloc((unsigned)(2 * sizeof(short))); int tlg_id = curwin->w_s->b_syn_topgrp - SYNID_CLUSTER; if (grp_list != NULL) { grp_list[0] = id; grp_list[1] = 0; syn_combine_list(&SYN_CLSTR(curwin->w_s)[tlg_id].scl_list, &grp_list, CLUSTER_ADD); } } } /* * Handle ":syntax include [@{group-name}] filename" command. */ static void syn_cmd_include(eap, syncing) exarg_T *eap; int syncing UNUSED; { char_u *arg = eap->arg; int sgl_id = 1; char_u *group_name_end; char_u *rest; char_u *errormsg = NULL; int prev_toplvl_grp; int prev_syn_inc_tag; int source = FALSE; eap->nextcmd = find_nextcmd(arg); if (eap->skip) return; if (arg[0] == '@') { ++arg; rest = get_group_name(arg, &group_name_end); if (rest == NULL) { EMSG((char_u *)_("E397: Filename required")); return; } sgl_id = syn_check_cluster(arg, (int)(group_name_end - arg)); if (sgl_id == 0) return; /* separate_nextcmd() and expand_filename() depend on this */ eap->arg = rest; } /* * Everything that's left, up to the next command, should be the * filename to include. */ eap->argt |= (XFILE | NOSPC); separate_nextcmd(eap); if (*eap->arg == '<' || *eap->arg == '$' || mch_isFullName(eap->arg)) { /* For an absolute path, "$VIM/..." or "<sfile>.." we ":source" the * file. Need to expand the file name first. In other cases * ":runtime!" is used. */ source = TRUE; if (expand_filename(eap, syn_cmdlinep, &errormsg) == FAIL) { if (errormsg != NULL) EMSG(errormsg); return; } } /* * Save and restore the existing top-level grouplist id and ":syn * include" tag around the actual inclusion. */ if (running_syn_inc_tag >= MAX_SYN_INC_TAG) { EMSG((char_u *)_("E847: Too many syntax includes")); return; } prev_syn_inc_tag = current_syn_inc_tag; current_syn_inc_tag = ++running_syn_inc_tag; prev_toplvl_grp = curwin->w_s->b_syn_topgrp; curwin->w_s->b_syn_topgrp = sgl_id; if (source ? do_source(eap->arg, FALSE, DOSO_NONE) == FAIL : source_runtime(eap->arg, TRUE) == FAIL) EMSG2(_(e_notopen), eap->arg); curwin->w_s->b_syn_topgrp = prev_toplvl_grp; current_syn_inc_tag = prev_syn_inc_tag; } /* * Handle ":syntax keyword {group-name} [{option}] keyword .." command. */ static void syn_cmd_keyword(eap, syncing) exarg_T *eap; int syncing UNUSED; { char_u *arg = eap->arg; char_u *group_name_end; int syn_id; char_u *rest; char_u *keyword_copy = NULL; char_u *p; char_u *kw; syn_opt_arg_T syn_opt_arg; int cnt; int conceal_char = NUL; rest = get_group_name(arg, &group_name_end); if (rest != NULL) { syn_id = syn_check_group(arg, (int)(group_name_end - arg)); if (syn_id != 0) /* allocate a buffer, for removing backslashes in the keyword */ keyword_copy = alloc((unsigned)STRLEN(rest) + 1); if (keyword_copy != NULL) { syn_opt_arg.flags = 0; syn_opt_arg.keyword = TRUE; syn_opt_arg.sync_idx = NULL; syn_opt_arg.has_cont_list = FALSE; syn_opt_arg.cont_in_list = NULL; syn_opt_arg.next_list = NULL; /* * The options given apply to ALL keywords, so all options must be * found before keywords can be created. * 1: collect the options and copy the keywords to keyword_copy. */ cnt = 0; p = keyword_copy; for ( ; rest != NULL && !ends_excmd(*rest); rest = skipwhite(rest)) { rest = get_syn_options(rest, &syn_opt_arg, &conceal_char); if (rest == NULL || ends_excmd(*rest)) break; /* Copy the keyword, removing backslashes, and add a NUL. */ while (*rest != NUL && !vim_iswhite(*rest)) { if (*rest == '\\' && rest[1] != NUL) ++rest; *p++ = *rest++; } *p++ = NUL; ++cnt; } if (!eap->skip) { /* Adjust flags for use of ":syn include". */ syn_incl_toplevel(syn_id, &syn_opt_arg.flags); /* * 2: Add an entry for each keyword. */ for (kw = keyword_copy; --cnt >= 0; kw += STRLEN(kw) + 1) { for (p = vim_strchr(kw, '['); ; ) { if (p != NULL) *p = NUL; add_keyword(kw, syn_id, syn_opt_arg.flags, syn_opt_arg.cont_in_list, syn_opt_arg.next_list, conceal_char); if (p == NULL) break; if (p[1] == NUL) { EMSG2(_("E789: Missing ']': %s"), kw); kw = p + 2; /* skip over the NUL */ break; } if (p[1] == ']') { kw = p + 1; /* skip over the "]" */ break; } #ifdef FEAT_MBYTE if (has_mbyte) { int l = (*mb_ptr2len)(p + 1); mch_memmove(p, p + 1, l); p += l; } else #endif { p[0] = p[1]; ++p; } } } } vim_free(keyword_copy); vim_free(syn_opt_arg.cont_in_list); vim_free(syn_opt_arg.next_list); } } if (rest != NULL) eap->nextcmd = check_nextcmd(rest); else EMSG2(_(e_invarg2), arg); redraw_curbuf_later(SOME_VALID); syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ } /* * Handle ":syntax match {name} [{options}] {pattern} [{options}]". * * Also ":syntax sync match {name} [[grouphere | groupthere] {group-name}] .." */ static void syn_cmd_match(eap, syncing) exarg_T *eap; int syncing; /* TRUE for ":syntax sync match .. " */ { char_u *arg = eap->arg; char_u *group_name_end; char_u *rest; synpat_T item; /* the item found in the line */ int syn_id; int idx; syn_opt_arg_T syn_opt_arg; int sync_idx = 0; int conceal_char = NUL; /* Isolate the group name, check for validity */ rest = get_group_name(arg, &group_name_end); /* Get options before the pattern */ syn_opt_arg.flags = 0; syn_opt_arg.keyword = FALSE; syn_opt_arg.sync_idx = syncing ? &sync_idx : NULL; syn_opt_arg.has_cont_list = TRUE; syn_opt_arg.cont_list = NULL; syn_opt_arg.cont_in_list = NULL; syn_opt_arg.next_list = NULL; rest = get_syn_options(rest, &syn_opt_arg, &conceal_char); /* get the pattern. */ init_syn_patterns(); vim_memset(&item, 0, sizeof(item)); rest = get_syn_pattern(rest, &item); if (vim_regcomp_had_eol() && !(syn_opt_arg.flags & HL_EXCLUDENL)) syn_opt_arg.flags |= HL_HAS_EOL; /* Get options after the pattern */ rest = get_syn_options(rest, &syn_opt_arg, &conceal_char); if (rest != NULL) /* all arguments are valid */ { /* * Check for trailing command and illegal trailing arguments. */ eap->nextcmd = check_nextcmd(rest); if (!ends_excmd(*rest) || eap->skip) rest = NULL; else if (ga_grow(&curwin->w_s->b_syn_patterns, 1) != FAIL && (syn_id = syn_check_group(arg, (int)(group_name_end - arg))) != 0) { syn_incl_toplevel(syn_id, &syn_opt_arg.flags); /* * Store the pattern in the syn_items list */ idx = curwin->w_s->b_syn_patterns.ga_len; SYN_ITEMS(curwin->w_s)[idx] = item; SYN_ITEMS(curwin->w_s)[idx].sp_syncing = syncing; SYN_ITEMS(curwin->w_s)[idx].sp_type = SPTYPE_MATCH; SYN_ITEMS(curwin->w_s)[idx].sp_syn.id = syn_id; SYN_ITEMS(curwin->w_s)[idx].sp_syn.inc_tag = current_syn_inc_tag; SYN_ITEMS(curwin->w_s)[idx].sp_flags = syn_opt_arg.flags; SYN_ITEMS(curwin->w_s)[idx].sp_sync_idx = sync_idx; SYN_ITEMS(curwin->w_s)[idx].sp_cont_list = syn_opt_arg.cont_list; SYN_ITEMS(curwin->w_s)[idx].sp_syn.cont_in_list = syn_opt_arg.cont_in_list; #ifdef FEAT_CONCEAL SYN_ITEMS(curwin->w_s)[idx].sp_cchar = conceal_char; #endif if (syn_opt_arg.cont_in_list != NULL) curwin->w_s->b_syn_containedin = TRUE; SYN_ITEMS(curwin->w_s)[idx].sp_next_list = syn_opt_arg.next_list; ++curwin->w_s->b_syn_patterns.ga_len; /* remember that we found a match for syncing on */ if (syn_opt_arg.flags & (HL_SYNC_HERE|HL_SYNC_THERE)) curwin->w_s->b_syn_sync_flags |= SF_MATCH; #ifdef FEAT_FOLDING if (syn_opt_arg.flags & HL_FOLD) ++curwin->w_s->b_syn_folditems; #endif redraw_curbuf_later(SOME_VALID); syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ return; /* don't free the progs and patterns now */ } } /* * Something failed, free the allocated memory. */ vim_free(item.sp_prog); vim_free(item.sp_pattern); vim_free(syn_opt_arg.cont_list); vim_free(syn_opt_arg.cont_in_list); vim_free(syn_opt_arg.next_list); if (rest == NULL) EMSG2(_(e_invarg2), arg); } /* * Handle ":syntax region {group-name} [matchgroup={group-name}] * start {start} .. [skip {skip}] end {end} .. [{options}]". */ static void syn_cmd_region(eap, syncing) exarg_T *eap; int syncing; /* TRUE for ":syntax sync region .." */ { char_u *arg = eap->arg; char_u *group_name_end; char_u *rest; /* next arg, NULL on error */ char_u *key_end; char_u *key = NULL; char_u *p; int item; #define ITEM_START 0 #define ITEM_SKIP 1 #define ITEM_END 2 #define ITEM_MATCHGROUP 3 struct pat_ptr { synpat_T *pp_synp; /* pointer to syn_pattern */ int pp_matchgroup_id; /* matchgroup ID */ struct pat_ptr *pp_next; /* pointer to next pat_ptr */ } *(pat_ptrs[3]); /* patterns found in the line */ struct pat_ptr *ppp; struct pat_ptr *ppp_next; int pat_count = 0; /* nr of syn_patterns found */ int syn_id; int matchgroup_id = 0; int not_enough = FALSE; /* not enough arguments */ int illegal = FALSE; /* illegal arguments */ int success = FALSE; int idx; syn_opt_arg_T syn_opt_arg; int conceal_char = NUL; /* Isolate the group name, check for validity */ rest = get_group_name(arg, &group_name_end); pat_ptrs[0] = NULL; pat_ptrs[1] = NULL; pat_ptrs[2] = NULL; init_syn_patterns(); syn_opt_arg.flags = 0; syn_opt_arg.keyword = FALSE; syn_opt_arg.sync_idx = NULL; syn_opt_arg.has_cont_list = TRUE; syn_opt_arg.cont_list = NULL; syn_opt_arg.cont_in_list = NULL; syn_opt_arg.next_list = NULL; /* * get the options, patterns and matchgroup. */ while (rest != NULL && !ends_excmd(*rest)) { /* Check for option arguments */ rest = get_syn_options(rest, &syn_opt_arg, &conceal_char); if (rest == NULL || ends_excmd(*rest)) break; /* must be a pattern or matchgroup then */ key_end = rest; while (*key_end && !vim_iswhite(*key_end) && *key_end != '=') ++key_end; vim_free(key); key = vim_strnsave_up(rest, (int)(key_end - rest)); if (key == NULL) /* out of memory */ { rest = NULL; break; } if (STRCMP(key, "MATCHGROUP") == 0) item = ITEM_MATCHGROUP; else if (STRCMP(key, "START") == 0) item = ITEM_START; else if (STRCMP(key, "END") == 0) item = ITEM_END; else if (STRCMP(key, "SKIP") == 0) { if (pat_ptrs[ITEM_SKIP] != NULL) /* one skip pattern allowed */ { illegal = TRUE; break; } item = ITEM_SKIP; } else break; rest = skipwhite(key_end); if (*rest != '=') { rest = NULL; EMSG2(_("E398: Missing '=': %s"), arg); break; } rest = skipwhite(rest + 1); if (*rest == NUL) { not_enough = TRUE; break; } if (item == ITEM_MATCHGROUP) { p = skiptowhite(rest); if ((p - rest == 4 && STRNCMP(rest, "NONE", 4) == 0) || eap->skip) matchgroup_id = 0; else { matchgroup_id = syn_check_group(rest, (int)(p - rest)); if (matchgroup_id == 0) { illegal = TRUE; break; } } rest = skipwhite(p); } else { /* * Allocate room for a syn_pattern, and link it in the list of * syn_patterns for this item, at the start (because the list is * used from end to start). */ ppp = (struct pat_ptr *)alloc((unsigned)sizeof(struct pat_ptr)); if (ppp == NULL) { rest = NULL; break; } ppp->pp_next = pat_ptrs[item]; pat_ptrs[item] = ppp; ppp->pp_synp = (synpat_T *)alloc_clear((unsigned)sizeof(synpat_T)); if (ppp->pp_synp == NULL) { rest = NULL; break; } /* * Get the syntax pattern and the following offset(s). */ /* Enable the appropriate \z specials. */ if (item == ITEM_START) reg_do_extmatch = REX_SET; else if (item == ITEM_SKIP || item == ITEM_END) reg_do_extmatch = REX_USE; rest = get_syn_pattern(rest, ppp->pp_synp); reg_do_extmatch = 0; if (item == ITEM_END && vim_regcomp_had_eol() && !(syn_opt_arg.flags & HL_EXCLUDENL)) ppp->pp_synp->sp_flags |= HL_HAS_EOL; ppp->pp_matchgroup_id = matchgroup_id; ++pat_count; } } vim_free(key); if (illegal || not_enough) rest = NULL; /* * Must have a "start" and "end" pattern. */ if (rest != NULL && (pat_ptrs[ITEM_START] == NULL || pat_ptrs[ITEM_END] == NULL)) { not_enough = TRUE; rest = NULL; } if (rest != NULL) { /* * Check for trailing garbage or command. * If OK, add the item. */ eap->nextcmd = check_nextcmd(rest); if (!ends_excmd(*rest) || eap->skip) rest = NULL; else if (ga_grow(&(curwin->w_s->b_syn_patterns), pat_count) != FAIL && (syn_id = syn_check_group(arg, (int)(group_name_end - arg))) != 0) { syn_incl_toplevel(syn_id, &syn_opt_arg.flags); /* * Store the start/skip/end in the syn_items list */ idx = curwin->w_s->b_syn_patterns.ga_len; for (item = ITEM_START; item <= ITEM_END; ++item) { for (ppp = pat_ptrs[item]; ppp != NULL; ppp = ppp->pp_next) { SYN_ITEMS(curwin->w_s)[idx] = *(ppp->pp_synp); SYN_ITEMS(curwin->w_s)[idx].sp_syncing = syncing; SYN_ITEMS(curwin->w_s)[idx].sp_type = (item == ITEM_START) ? SPTYPE_START : (item == ITEM_SKIP) ? SPTYPE_SKIP : SPTYPE_END; SYN_ITEMS(curwin->w_s)[idx].sp_flags |= syn_opt_arg.flags; SYN_ITEMS(curwin->w_s)[idx].sp_syn.id = syn_id; SYN_ITEMS(curwin->w_s)[idx].sp_syn.inc_tag = current_syn_inc_tag; SYN_ITEMS(curwin->w_s)[idx].sp_syn_match_id = ppp->pp_matchgroup_id; #ifdef FEAT_CONCEAL SYN_ITEMS(curwin->w_s)[idx].sp_cchar = conceal_char; #endif if (item == ITEM_START) { SYN_ITEMS(curwin->w_s)[idx].sp_cont_list = syn_opt_arg.cont_list; SYN_ITEMS(curwin->w_s)[idx].sp_syn.cont_in_list = syn_opt_arg.cont_in_list; if (syn_opt_arg.cont_in_list != NULL) curwin->w_s->b_syn_containedin = TRUE; SYN_ITEMS(curwin->w_s)[idx].sp_next_list = syn_opt_arg.next_list; } ++curwin->w_s->b_syn_patterns.ga_len; ++idx; #ifdef FEAT_FOLDING if (syn_opt_arg.flags & HL_FOLD) ++curwin->w_s->b_syn_folditems; #endif } } redraw_curbuf_later(SOME_VALID); syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ success = TRUE; /* don't free the progs and patterns now */ } } /* * Free the allocated memory. */ for (item = ITEM_START; item <= ITEM_END; ++item) for (ppp = pat_ptrs[item]; ppp != NULL; ppp = ppp_next) { if (!success) { vim_free(ppp->pp_synp->sp_prog); vim_free(ppp->pp_synp->sp_pattern); } vim_free(ppp->pp_synp); ppp_next = ppp->pp_next; vim_free(ppp); } if (!success) { vim_free(syn_opt_arg.cont_list); vim_free(syn_opt_arg.cont_in_list); vim_free(syn_opt_arg.next_list); if (not_enough) EMSG2(_("E399: Not enough arguments: syntax region %s"), arg); else if (illegal || rest == NULL) EMSG2(_(e_invarg2), arg); } } /* * A simple syntax group ID comparison function suitable for use in qsort() */ static int #ifdef __BORLANDC__ _RTLENTRYF #endif syn_compare_stub(v1, v2) const void *v1; const void *v2; { const short *s1 = v1; const short *s2 = v2; return (*s1 > *s2 ? 1 : *s1 < *s2 ? -1 : 0); } /* * Combines lists of syntax clusters. * *clstr1 and *clstr2 must both be allocated memory; they will be consumed. */ static void syn_combine_list(clstr1, clstr2, list_op) short **clstr1; short **clstr2; int list_op; { int count1 = 0; int count2 = 0; short *g1; short *g2; short *clstr = NULL; int count; int round; /* * Handle degenerate cases. */ if (*clstr2 == NULL) return; if (*clstr1 == NULL || list_op == CLUSTER_REPLACE) { if (list_op == CLUSTER_REPLACE) vim_free(*clstr1); if (list_op == CLUSTER_REPLACE || list_op == CLUSTER_ADD) *clstr1 = *clstr2; else vim_free(*clstr2); return; } for (g1 = *clstr1; *g1; g1++) ++count1; for (g2 = *clstr2; *g2; g2++) ++count2; /* * For speed purposes, sort both lists. */ qsort(*clstr1, (size_t)count1, sizeof(short), syn_compare_stub); qsort(*clstr2, (size_t)count2, sizeof(short), syn_compare_stub); /* * We proceed in two passes; in round 1, we count the elements to place * in the new list, and in round 2, we allocate and populate the new * list. For speed, we use a mergesort-like method, adding the smaller * of the current elements in each list to the new list. */ for (round = 1; round <= 2; round++) { g1 = *clstr1; g2 = *clstr2; count = 0; /* * First, loop through the lists until one of them is empty. */ while (*g1 && *g2) { /* * We always want to add from the first list. */ if (*g1 < *g2) { if (round == 2) clstr[count] = *g1; count++; g1++; continue; } /* * We only want to add from the second list if we're adding the * lists. */ if (list_op == CLUSTER_ADD) { if (round == 2) clstr[count] = *g2; count++; } if (*g1 == *g2) g1++; g2++; } /* * Now add the leftovers from whichever list didn't get finished * first. As before, we only want to add from the second list if * we're adding the lists. */ for (; *g1; g1++, count++) if (round == 2) clstr[count] = *g1; if (list_op == CLUSTER_ADD) for (; *g2; g2++, count++) if (round == 2) clstr[count] = *g2; if (round == 1) { /* * If the group ended up empty, we don't need to allocate any * space for it. */ if (count == 0) { clstr = NULL; break; } clstr = (short *)alloc((unsigned)((count + 1) * sizeof(short))); if (clstr == NULL) break; clstr[count] = 0; } } /* * Finally, put the new list in place. */ vim_free(*clstr1); vim_free(*clstr2); *clstr1 = clstr; } /* * Lookup a syntax cluster name and return it's ID. * If it is not found, 0 is returned. */ static int syn_scl_name2id(name) char_u *name; { int i; char_u *name_u; /* Avoid using stricmp() too much, it's slow on some systems */ name_u = vim_strsave_up(name); if (name_u == NULL) return 0; for (i = curwin->w_s->b_syn_clusters.ga_len; --i >= 0; ) if (SYN_CLSTR(curwin->w_s)[i].scl_name_u != NULL && STRCMP(name_u, SYN_CLSTR(curwin->w_s)[i].scl_name_u) == 0) break; vim_free(name_u); return (i < 0 ? 0 : i + SYNID_CLUSTER); } /* * Like syn_scl_name2id(), but take a pointer + length argument. */ static int syn_scl_namen2id(linep, len) char_u *linep; int len; { char_u *name; int id = 0; name = vim_strnsave(linep, len); if (name != NULL) { id = syn_scl_name2id(name); vim_free(name); } return id; } /* * Find syntax cluster name in the table and return it's ID. * The argument is a pointer to the name and the length of the name. * If it doesn't exist yet, a new entry is created. * Return 0 for failure. */ static int syn_check_cluster(pp, len) char_u *pp; int len; { int id; char_u *name; name = vim_strnsave(pp, len); if (name == NULL) return 0; id = syn_scl_name2id(name); if (id == 0) /* doesn't exist yet */ id = syn_add_cluster(name); else vim_free(name); return id; } /* * Add new syntax cluster and return it's ID. * "name" must be an allocated string, it will be consumed. * Return 0 for failure. */ static int syn_add_cluster(name) char_u *name; { int len; /* * First call for this growarray: init growing array. */ if (curwin->w_s->b_syn_clusters.ga_data == NULL) { curwin->w_s->b_syn_clusters.ga_itemsize = sizeof(syn_cluster_T); curwin->w_s->b_syn_clusters.ga_growsize = 10; } len = curwin->w_s->b_syn_clusters.ga_len; if (len >= MAX_CLUSTER_ID) { EMSG((char_u *)_("E848: Too many syntax clusters")); vim_free(name); return 0; } /* * Make room for at least one other cluster entry. */ if (ga_grow(&curwin->w_s->b_syn_clusters, 1) == FAIL) { vim_free(name); return 0; } vim_memset(&(SYN_CLSTR(curwin->w_s)[len]), 0, sizeof(syn_cluster_T)); SYN_CLSTR(curwin->w_s)[len].scl_name = name; SYN_CLSTR(curwin->w_s)[len].scl_name_u = vim_strsave_up(name); SYN_CLSTR(curwin->w_s)[len].scl_list = NULL; ++curwin->w_s->b_syn_clusters.ga_len; if (STRICMP(name, "Spell") == 0) curwin->w_s->b_spell_cluster_id = len + SYNID_CLUSTER; if (STRICMP(name, "NoSpell") == 0) curwin->w_s->b_nospell_cluster_id = len + SYNID_CLUSTER; return len + SYNID_CLUSTER; } /* * Handle ":syntax cluster {cluster-name} [contains={groupname},..] * [add={groupname},..] [remove={groupname},..]". */ static void syn_cmd_cluster(eap, syncing) exarg_T *eap; int syncing UNUSED; { char_u *arg = eap->arg; char_u *group_name_end; char_u *rest; int scl_id; short *clstr_list; int got_clstr = FALSE; int opt_len; int list_op; eap->nextcmd = find_nextcmd(arg); if (eap->skip) return; rest = get_group_name(arg, &group_name_end); if (rest != NULL) { scl_id = syn_check_cluster(arg, (int)(group_name_end - arg)); if (scl_id == 0) return; scl_id -= SYNID_CLUSTER; for (;;) { if (STRNICMP(rest, "add", 3) == 0 && (vim_iswhite(rest[3]) || rest[3] == '=')) { opt_len = 3; list_op = CLUSTER_ADD; } else if (STRNICMP(rest, "remove", 6) == 0 && (vim_iswhite(rest[6]) || rest[6] == '=')) { opt_len = 6; list_op = CLUSTER_SUBTRACT; } else if (STRNICMP(rest, "contains", 8) == 0 && (vim_iswhite(rest[8]) || rest[8] == '=')) { opt_len = 8; list_op = CLUSTER_REPLACE; } else break; clstr_list = NULL; if (get_id_list(&rest, opt_len, &clstr_list) == FAIL) { EMSG2(_(e_invarg2), rest); break; } syn_combine_list(&SYN_CLSTR(curwin->w_s)[scl_id].scl_list, &clstr_list, list_op); got_clstr = TRUE; } if (got_clstr) { redraw_curbuf_later(SOME_VALID); syn_stack_free_all(curwin->w_s); /* Need to recompute all. */ } } if (!got_clstr) EMSG(_("E400: No cluster specified")); if (rest == NULL || !ends_excmd(*rest)) EMSG2(_(e_invarg2), arg); } /* * On first call for current buffer: Init growing array. */ static void init_syn_patterns() { curwin->w_s->b_syn_patterns.ga_itemsize = sizeof(synpat_T); curwin->w_s->b_syn_patterns.ga_growsize = 10; } /* * Get one pattern for a ":syntax match" or ":syntax region" command. * Stores the pattern and program in a synpat_T. * Returns a pointer to the next argument, or NULL in case of an error. */ static char_u * get_syn_pattern(arg, ci) char_u *arg; synpat_T *ci; { char_u *end; int *p; int idx; char_u *cpo_save; /* need at least three chars */ if (arg == NULL || arg[1] == NUL || arg[2] == NUL) return NULL; end = skip_regexp(arg + 1, *arg, TRUE, NULL); if (*end != *arg) /* end delimiter not found */ { EMSG2(_("E401: Pattern delimiter not found: %s"), arg); return NULL; } /* store the pattern and compiled regexp program */ if ((ci->sp_pattern = vim_strnsave(arg + 1, (int)(end - arg - 1))) == NULL) return NULL; /* Make 'cpoptions' empty, to avoid the 'l' flag */ cpo_save = p_cpo; p_cpo = (char_u *)""; ci->sp_prog = vim_regcomp(ci->sp_pattern, RE_MAGIC); p_cpo = cpo_save; if (ci->sp_prog == NULL) return NULL; ci->sp_ic = curwin->w_s->b_syn_ic; /* * Check for a match, highlight or region offset. */ ++end; do { for (idx = SPO_COUNT; --idx >= 0; ) if (STRNCMP(end, spo_name_tab[idx], 3) == 0) break; if (idx >= 0) { p = &(ci->sp_offsets[idx]); if (idx != SPO_LC_OFF) switch (end[3]) { case 's': break; case 'b': break; case 'e': idx += SPO_COUNT; break; default: idx = -1; break; } if (idx >= 0) { ci->sp_off_flags |= (1 << idx); if (idx == SPO_LC_OFF) /* lc=99 */ { end += 3; *p = getdigits(&end); /* "lc=" offset automatically sets "ms=" offset */ if (!(ci->sp_off_flags & (1 << SPO_MS_OFF))) { ci->sp_off_flags |= (1 << SPO_MS_OFF); ci->sp_offsets[SPO_MS_OFF] = *p; } } else /* yy=x+99 */ { end += 4; if (*end == '+') { ++end; *p = getdigits(&end); /* positive offset */ } else if (*end == '-') { ++end; *p = -getdigits(&end); /* negative offset */ } } if (*end != ',') break; ++end; } } } while (idx >= 0); if (!ends_excmd(*end) && !vim_iswhite(*end)) { EMSG2(_("E402: Garbage after pattern: %s"), arg); return NULL; } return skipwhite(end); } /* * Handle ":syntax sync .." command. */ static void syn_cmd_sync(eap, syncing) exarg_T *eap; int syncing UNUSED; { char_u *arg_start = eap->arg; char_u *arg_end; char_u *key = NULL; char_u *next_arg; int illegal = FALSE; int finished = FALSE; long n; char_u *cpo_save; if (ends_excmd(*arg_start)) { syn_cmd_list(eap, TRUE); return; } while (!ends_excmd(*arg_start)) { arg_end = skiptowhite(arg_start); next_arg = skipwhite(arg_end); vim_free(key); key = vim_strnsave_up(arg_start, (int)(arg_end - arg_start)); if (STRCMP(key, "CCOMMENT") == 0) { if (!eap->skip) curwin->w_s->b_syn_sync_flags |= SF_CCOMMENT; if (!ends_excmd(*next_arg)) { arg_end = skiptowhite(next_arg); if (!eap->skip) curwin->w_s->b_syn_sync_id = syn_check_group(next_arg, (int)(arg_end - next_arg)); next_arg = skipwhite(arg_end); } else if (!eap->skip) curwin->w_s->b_syn_sync_id = syn_name2id((char_u *)"Comment"); } else if ( STRNCMP(key, "LINES", 5) == 0 || STRNCMP(key, "MINLINES", 8) == 0 || STRNCMP(key, "MAXLINES", 8) == 0 || STRNCMP(key, "LINEBREAKS", 10) == 0) { if (key[4] == 'S') arg_end = key + 6; else if (key[0] == 'L') arg_end = key + 11; else arg_end = key + 9; if (arg_end[-1] != '=' || !VIM_ISDIGIT(*arg_end)) { illegal = TRUE; break; } n = getdigits(&arg_end); if (!eap->skip) { if (key[4] == 'B') curwin->w_s->b_syn_sync_linebreaks = n; else if (key[1] == 'A') curwin->w_s->b_syn_sync_maxlines = n; else curwin->w_s->b_syn_sync_minlines = n; } } else if (STRCMP(key, "FROMSTART") == 0) { if (!eap->skip) { curwin->w_s->b_syn_sync_minlines = MAXLNUM; curwin->w_s->b_syn_sync_maxlines = 0; } } else if (STRCMP(key, "LINECONT") == 0) { if (curwin->w_s->b_syn_linecont_pat != NULL) { EMSG(_("E403: syntax sync: line continuations pattern specified twice")); finished = TRUE; break; } arg_end = skip_regexp(next_arg + 1, *next_arg, TRUE, NULL); if (*arg_end != *next_arg) /* end delimiter not found */ { illegal = TRUE; break; } if (!eap->skip) { /* store the pattern and compiled regexp program */ if ((curwin->w_s->b_syn_linecont_pat = vim_strnsave(next_arg + 1, (int)(arg_end - next_arg - 1))) == NULL) { finished = TRUE; break; } curwin->w_s->b_syn_linecont_ic = curwin->w_s->b_syn_ic; /* Make 'cpoptions' empty, to avoid the 'l' flag */ cpo_save = p_cpo; p_cpo = (char_u *)""; curwin->w_s->b_syn_linecont_prog = vim_regcomp(curwin->w_s->b_syn_linecont_pat, RE_MAGIC); p_cpo = cpo_save; if (curwin->w_s->b_syn_linecont_prog == NULL) { vim_free(curwin->w_s->b_syn_linecont_pat); curwin->w_s->b_syn_linecont_pat = NULL; finished = TRUE; break; } } next_arg = skipwhite(arg_end + 1); } else { eap->arg = next_arg; if (STRCMP(key, "MATCH") == 0) syn_cmd_match(eap, TRUE); else if (STRCMP(key, "REGION") == 0) syn_cmd_region(eap, TRUE); else if (STRCMP(key, "CLEAR") == 0) syn_cmd_clear(eap, TRUE); else illegal = TRUE; finished = TRUE; break; } arg_start = next_arg; } vim_free(key); if (illegal) EMSG2(_("E404: Illegal arguments: %s"), arg_start); else if (!finished) { eap->nextcmd = check_nextcmd(arg_start); redraw_curbuf_later(SOME_VALID); syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ } } /* * Convert a line of highlight group names into a list of group ID numbers. * "arg" should point to the "contains" or "nextgroup" keyword. * "arg" is advanced to after the last group name. * Careful: the argument is modified (NULs added). * returns FAIL for some error, OK for success. */ static int get_id_list(arg, keylen, list) char_u **arg; int keylen; /* length of keyword */ short **list; /* where to store the resulting list, if not NULL, the list is silently skipped! */ { char_u *p = NULL; char_u *end; int round; int count; int total_count = 0; short *retval = NULL; char_u *name; regmatch_T regmatch; int id; int i; int failed = FALSE; /* * We parse the list twice: * round == 1: count the number of items, allocate the array. * round == 2: fill the array with the items. * In round 1 new groups may be added, causing the number of items to * grow when a regexp is used. In that case round 1 is done once again. */ for (round = 1; round <= 2; ++round) { /* * skip "contains" */ p = skipwhite(*arg + keylen); if (*p != '=') { EMSG2(_("E405: Missing equal sign: %s"), *arg); break; } p = skipwhite(p + 1); if (ends_excmd(*p)) { EMSG2(_("E406: Empty argument: %s"), *arg); break; } /* * parse the arguments after "contains" */ count = 0; while (!ends_excmd(*p)) { for (end = p; *end && !vim_iswhite(*end) && *end != ','; ++end) ; name = alloc((int)(end - p + 3)); /* leave room for "^$" */ if (name == NULL) { failed = TRUE; break; } vim_strncpy(name + 1, p, end - p); if ( STRCMP(name + 1, "ALLBUT") == 0 || STRCMP(name + 1, "ALL") == 0 || STRCMP(name + 1, "TOP") == 0 || STRCMP(name + 1, "CONTAINED") == 0) { if (TOUPPER_ASC(**arg) != 'C') { EMSG2(_("E407: %s not allowed here"), name + 1); failed = TRUE; vim_free(name); break; } if (count != 0) { EMSG2(_("E408: %s must be first in contains list"), name + 1); failed = TRUE; vim_free(name); break; } if (name[1] == 'A') id = SYNID_ALLBUT; else if (name[1] == 'T') id = SYNID_TOP; else id = SYNID_CONTAINED; id += current_syn_inc_tag; } else if (name[1] == '@') { id = syn_check_cluster(name + 2, (int)(end - p - 1)); } else { /* * Handle full group name. */ if (vim_strpbrk(name + 1, (char_u *)"\\.*^$~[") == NULL) id = syn_check_group(name + 1, (int)(end - p)); else { /* * Handle match of regexp with group names. */ *name = '^'; STRCAT(name, "$"); regmatch.regprog = vim_regcomp(name, RE_MAGIC); if (regmatch.regprog == NULL) { failed = TRUE; vim_free(name); break; } regmatch.rm_ic = TRUE; id = 0; for (i = highlight_ga.ga_len; --i >= 0; ) { if (vim_regexec(&regmatch, HL_TABLE()[i].sg_name, (colnr_T)0)) { if (round == 2) { /* Got more items than expected; can happen * when adding items that match: * "contains=a.*b,axb". * Go back to first round */ if (count >= total_count) { vim_free(retval); round = 1; } else retval[count] = i + 1; } ++count; id = -1; /* remember that we found one */ } } vim_free(regmatch.regprog); } } vim_free(name); if (id == 0) { EMSG2(_("E409: Unknown group name: %s"), p); failed = TRUE; break; } if (id > 0) { if (round == 2) { /* Got more items than expected, go back to first round */ if (count >= total_count) { vim_free(retval); round = 1; } else retval[count] = id; } ++count; } p = skipwhite(end); if (*p != ',') break; p = skipwhite(p + 1); /* skip comma in between arguments */ } if (failed) break; if (round == 1) { retval = (short *)alloc((unsigned)((count + 1) * sizeof(short))); if (retval == NULL) break; retval[count] = 0; /* zero means end of the list */ total_count = count; } } *arg = p; if (failed || retval == NULL) { vim_free(retval); return FAIL; } if (*list == NULL) *list = retval; else vim_free(retval); /* list already found, don't overwrite it */ return OK; } /* * Make a copy of an ID list. */ static short * copy_id_list(list) short *list; { int len; int count; short *retval; if (list == NULL) return NULL; for (count = 0; list[count]; ++count) ; len = (count + 1) * sizeof(short); retval = (short *)alloc((unsigned)len); if (retval != NULL) mch_memmove(retval, list, (size_t)len); return retval; } /* * Check if syntax group "ssp" is in the ID list "list" of "cur_si". * "cur_si" can be NULL if not checking the "containedin" list. * Used to check if a syntax item is in the "contains" or "nextgroup" list of * the current item. * This function is called very often, keep it fast!! */ static int in_id_list(cur_si, list, ssp, contained) stateitem_T *cur_si; /* current item or NULL */ short *list; /* id list */ struct sp_syn *ssp; /* group id and ":syn include" tag of group */ int contained; /* group id is contained */ { int retval; short *scl_list; short item; short id = ssp->id; static int depth = 0; int r; /* If spp has a "containedin" list and "cur_si" is in it, return TRUE. */ if (cur_si != NULL && ssp->cont_in_list != NULL && !(cur_si->si_flags & HL_MATCH)) { /* Ignore transparent items without a contains argument. Double check * that we don't go back past the first one. */ while ((cur_si->si_flags & HL_TRANS_CONT) && cur_si > (stateitem_T *)(current_state.ga_data)) --cur_si; /* cur_si->si_idx is -1 for keywords, these never contain anything. */ if (cur_si->si_idx >= 0 && in_id_list(NULL, ssp->cont_in_list, &(SYN_ITEMS(syn_block)[cur_si->si_idx].sp_syn), SYN_ITEMS(syn_block)[cur_si->si_idx].sp_flags & HL_CONTAINED)) return TRUE; } if (list == NULL) return FALSE; /* * If list is ID_LIST_ALL, we are in a transparent item that isn't * inside anything. Only allow not-contained groups. */ if (list == ID_LIST_ALL) return !contained; /* * If the first item is "ALLBUT", return TRUE if "id" is NOT in the * contains list. We also require that "id" is at the same ":syn include" * level as the list. */ item = *list; if (item >= SYNID_ALLBUT && item < SYNID_CLUSTER) { if (item < SYNID_TOP) { /* ALL or ALLBUT: accept all groups in the same file */ if (item - SYNID_ALLBUT != ssp->inc_tag) return FALSE; } else if (item < SYNID_CONTAINED) { /* TOP: accept all not-contained groups in the same file */ if (item - SYNID_TOP != ssp->inc_tag || contained) return FALSE; } else { /* CONTAINED: accept all contained groups in the same file */ if (item - SYNID_CONTAINED != ssp->inc_tag || !contained) return FALSE; } item = *++list; retval = FALSE; } else retval = TRUE; /* * Return "retval" if id is in the contains list. */ while (item != 0) { if (item == id) return retval; if (item >= SYNID_CLUSTER) { scl_list = SYN_CLSTR(syn_block)[item - SYNID_CLUSTER].scl_list; /* restrict recursiveness to 30 to avoid an endless loop for a * cluster that includes itself (indirectly) */ if (scl_list != NULL && depth < 30) { ++depth; r = in_id_list(NULL, scl_list, ssp, contained); --depth; if (r) return retval; } } item = *++list; } return !retval; } struct subcommand { char *name; /* subcommand name */ void (*func)__ARGS((exarg_T *, int)); /* function to call */ }; static struct subcommand subcommands[] = { {"case", syn_cmd_case}, {"clear", syn_cmd_clear}, {"cluster", syn_cmd_cluster}, {"conceal", syn_cmd_conceal}, {"enable", syn_cmd_enable}, {"include", syn_cmd_include}, {"keyword", syn_cmd_keyword}, {"list", syn_cmd_list}, {"manual", syn_cmd_manual}, {"match", syn_cmd_match}, {"on", syn_cmd_on}, {"off", syn_cmd_off}, {"region", syn_cmd_region}, {"reset", syn_cmd_reset}, {"spell", syn_cmd_spell}, {"sync", syn_cmd_sync}, {"", syn_cmd_list}, {NULL, NULL} }; /* * ":syntax". * This searches the subcommands[] table for the subcommand name, and calls a * syntax_subcommand() function to do the rest. */ void ex_syntax(eap) exarg_T *eap; { char_u *arg = eap->arg; char_u *subcmd_end; char_u *subcmd_name; int i; syn_cmdlinep = eap->cmdlinep; /* isolate subcommand name */ for (subcmd_end = arg; ASCII_ISALPHA(*subcmd_end); ++subcmd_end) ; subcmd_name = vim_strnsave(arg, (int)(subcmd_end - arg)); if (subcmd_name != NULL) { if (eap->skip) /* skip error messages for all subcommands */ ++emsg_skip; for (i = 0; ; ++i) { if (subcommands[i].name == NULL) { EMSG2(_("E410: Invalid :syntax subcommand: %s"), subcmd_name); break; } if (STRCMP(subcmd_name, (char_u *)subcommands[i].name) == 0) { eap->arg = skipwhite(subcmd_end); (subcommands[i].func)(eap, FALSE); break; } } vim_free(subcmd_name); if (eap->skip) --emsg_skip; } } void ex_ownsyntax(eap) exarg_T *eap; { char_u *old_value; char_u *new_value; if (curwin->w_s == &curwin->w_buffer->b_s) { curwin->w_s = (synblock_T *)alloc(sizeof(synblock_T)); memset(curwin->w_s, 0, sizeof(synblock_T)); #ifdef FEAT_SPELL curwin->w_p_spell = FALSE; /* No spell checking */ clear_string_option(&curwin->w_s->b_p_spc); clear_string_option(&curwin->w_s->b_p_spf); vim_free(curwin->w_s->b_cap_prog); curwin->w_s->b_cap_prog = NULL; clear_string_option(&curwin->w_s->b_p_spl); #endif } /* save value of b:current_syntax */ old_value = get_var_value((char_u *)"b:current_syntax"); if (old_value != NULL) old_value = vim_strsave(old_value); /* Apply the "syntax" autocommand event, this finds and loads the syntax * file. */ apply_autocmds(EVENT_SYNTAX, eap->arg, curbuf->b_fname, TRUE, curbuf); /* move value of b:current_syntax to w:current_syntax */ new_value = get_var_value((char_u *)"b:current_syntax"); if (new_value != NULL) set_internal_string_var((char_u *)"w:current_syntax", new_value); /* restore value of b:current_syntax */ if (old_value == NULL) do_unlet((char_u *)"b:current_syntax", TRUE); else { set_internal_string_var((char_u *)"b:current_syntax", old_value); vim_free(old_value); } } int syntax_present(win) win_T *win; { return (win->w_s->b_syn_patterns.ga_len != 0 || win->w_s->b_syn_clusters.ga_len != 0 || win->w_s->b_keywtab.ht_used > 0 || win->w_s->b_keywtab_ic.ht_used > 0); } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) static enum { EXP_SUBCMD, /* expand ":syn" sub-commands */ EXP_CASE /* expand ":syn case" arguments */ } expand_what; /* * Reset include_link, include_default, include_none to 0. * Called when we are done expanding. */ void reset_expand_highlight() { include_link = include_default = include_none = 0; } /* * Handle command line completion for :match and :echohl command: Add "None" * as highlight group. */ void set_context_in_echohl_cmd(xp, arg) expand_T *xp; char_u *arg; { xp->xp_context = EXPAND_HIGHLIGHT; xp->xp_pattern = arg; include_none = 1; } /* * Handle command line completion for :syntax command. */ void set_context_in_syntax_cmd(xp, arg) expand_T *xp; char_u *arg; { char_u *p; /* Default: expand subcommands */ xp->xp_context = EXPAND_SYNTAX; expand_what = EXP_SUBCMD; xp->xp_pattern = arg; include_link = 0; include_default = 0; /* (part of) subcommand already typed */ if (*arg != NUL) { p = skiptowhite(arg); if (*p != NUL) /* past first word */ { xp->xp_pattern = skipwhite(p); if (*skiptowhite(xp->xp_pattern) != NUL) xp->xp_context = EXPAND_NOTHING; else if (STRNICMP(arg, "case", p - arg) == 0) expand_what = EXP_CASE; else if ( STRNICMP(arg, "keyword", p - arg) == 0 || STRNICMP(arg, "region", p - arg) == 0 || STRNICMP(arg, "match", p - arg) == 0 || STRNICMP(arg, "list", p - arg) == 0) xp->xp_context = EXPAND_HIGHLIGHT; else xp->xp_context = EXPAND_NOTHING; } } } static char *(case_args[]) = {"match", "ignore", NULL}; /* * Function given to ExpandGeneric() to obtain the list syntax names for * expansion. */ char_u * get_syntax_name(xp, idx) expand_T *xp UNUSED; int idx; { if (expand_what == EXP_SUBCMD) return (char_u *)subcommands[idx].name; return (char_u *)case_args[idx]; } #endif /* FEAT_CMDL_COMPL */ /* * Function called for expression evaluation: get syntax ID at file position. */ int syn_get_id(wp, lnum, col, trans, spellp, keep_state) win_T *wp; long lnum; colnr_T col; int trans; /* remove transparency */ int *spellp; /* return: can do spell checking */ int keep_state; /* keep state of char at "col" */ { /* When the position is not after the current position and in the same * line of the same buffer, need to restart parsing. */ if (wp->w_buffer != syn_buf || lnum != current_lnum || col < current_col) syntax_start(wp, lnum); (void)get_syntax_attr(col, spellp, keep_state); return (trans ? current_trans_id : current_id); } #if defined(FEAT_CONCEAL) || defined(PROTO) /* * Get extra information about the syntax item. Must be called right after * get_syntax_attr(). * Stores the current item sequence nr in "*seqnrp". * Returns the current flags. */ int get_syntax_info(seqnrp) int *seqnrp; { *seqnrp = current_seqnr; return current_flags; } /* * Return conceal substitution character */ int syn_get_sub_char() { return current_sub_char; } #endif #if defined(FEAT_EVAL) || defined(PROTO) /* * Return the syntax ID at position "i" in the current stack. * The caller must have called syn_get_id() before to fill the stack. * Returns -1 when "i" is out of range. */ int syn_get_stack_item(i) int i; { if (i >= current_state.ga_len) { /* Need to invalidate the state, because we didn't properly finish it * for the last character, "keep_state" was TRUE. */ invalidate_current_state(); current_col = MAXCOL; return -1; } return CUR_STATE(i).si_id; } #endif #if defined(FEAT_FOLDING) || defined(PROTO) /* * Function called to get folding level for line "lnum" in window "wp". */ int syn_get_foldlevel(wp, lnum) win_T *wp; long lnum; { int level = 0; int i; /* Return quickly when there are no fold items at all. */ if (wp->w_s->b_syn_folditems != 0) { syntax_start(wp, lnum); for (i = 0; i < current_state.ga_len; ++i) if (CUR_STATE(i).si_flags & HL_FOLD) ++level; } if (level > wp->w_p_fdn) { level = wp->w_p_fdn; if (level < 0) level = 0; } return level; } #endif #endif /* FEAT_SYN_HL */ /************************************** * Highlighting stuff * **************************************/ /* * The default highlight groups. These are compiled-in for fast startup and * they still work when the runtime files can't be found. * When making changes here, also change runtime/colors/default.vim! * The #ifdefs are needed to reduce the amount of static data. Helps to make * the 16 bit DOS (museum) version compile. */ #if defined(FEAT_GUI) || defined(FEAT_EVAL) # define CENT(a, b) b #else # define CENT(a, b) a #endif static char *(highlight_init_both[]) = { CENT("ErrorMsg term=standout ctermbg=DarkRed ctermfg=White", "ErrorMsg term=standout ctermbg=DarkRed ctermfg=White guibg=Red guifg=White"), CENT("IncSearch term=reverse cterm=reverse", "IncSearch term=reverse cterm=reverse gui=reverse"), CENT("ModeMsg term=bold cterm=bold", "ModeMsg term=bold cterm=bold gui=bold"), CENT("NonText term=bold ctermfg=Blue", "NonText term=bold ctermfg=Blue gui=bold guifg=Blue"), CENT("StatusLine term=reverse,bold cterm=reverse,bold", "StatusLine term=reverse,bold cterm=reverse,bold gui=reverse,bold"), CENT("StatusLineNC term=reverse cterm=reverse", "StatusLineNC term=reverse cterm=reverse gui=reverse"), #ifdef FEAT_VERTSPLIT CENT("VertSplit term=reverse cterm=reverse", "VertSplit term=reverse cterm=reverse gui=reverse"), #endif #ifdef FEAT_CLIPBOARD CENT("VisualNOS term=underline,bold cterm=underline,bold", "VisualNOS term=underline,bold cterm=underline,bold gui=underline,bold"), #endif #ifdef FEAT_DIFF CENT("DiffText term=reverse cterm=bold ctermbg=Red", "DiffText term=reverse cterm=bold ctermbg=Red gui=bold guibg=Red"), #endif #ifdef FEAT_INS_EXPAND CENT("PmenuSbar ctermbg=Grey", "PmenuSbar ctermbg=Grey guibg=Grey"), #endif #ifdef FEAT_WINDOWS CENT("TabLineSel term=bold cterm=bold", "TabLineSel term=bold cterm=bold gui=bold"), CENT("TabLineFill term=reverse cterm=reverse", "TabLineFill term=reverse cterm=reverse gui=reverse"), #endif #ifdef FEAT_GUI "Cursor guibg=fg guifg=bg", "lCursor guibg=fg guifg=bg", /* should be different, but what? */ #endif NULL }; static char *(highlight_init_light[]) = { CENT("Directory term=bold ctermfg=DarkBlue", "Directory term=bold ctermfg=DarkBlue guifg=Blue"), CENT("LineNr term=underline ctermfg=Brown", "LineNr term=underline ctermfg=Brown guifg=Brown"), CENT("CursorLineNr term=bold ctermfg=Brown", "CursorLineNr term=bold ctermfg=Brown gui=bold guifg=Brown"), CENT("MoreMsg term=bold ctermfg=DarkGreen", "MoreMsg term=bold ctermfg=DarkGreen gui=bold guifg=SeaGreen"), CENT("Question term=standout ctermfg=DarkGreen", "Question term=standout ctermfg=DarkGreen gui=bold guifg=SeaGreen"), CENT("Search term=reverse ctermbg=Yellow ctermfg=NONE", "Search term=reverse ctermbg=Yellow ctermfg=NONE guibg=Yellow guifg=NONE"), #ifdef FEAT_SPELL CENT("SpellBad term=reverse ctermbg=LightRed", "SpellBad term=reverse ctermbg=LightRed guisp=Red gui=undercurl"), CENT("SpellCap term=reverse ctermbg=LightBlue", "SpellCap term=reverse ctermbg=LightBlue guisp=Blue gui=undercurl"), CENT("SpellRare term=reverse ctermbg=LightMagenta", "SpellRare term=reverse ctermbg=LightMagenta guisp=Magenta gui=undercurl"), CENT("SpellLocal term=underline ctermbg=Cyan", "SpellLocal term=underline ctermbg=Cyan guisp=DarkCyan gui=undercurl"), #endif #ifdef FEAT_INS_EXPAND CENT("PmenuThumb ctermbg=Black", "PmenuThumb ctermbg=Black guibg=Black"), CENT("Pmenu ctermbg=LightMagenta ctermfg=Black", "Pmenu ctermbg=LightMagenta ctermfg=Black guibg=LightMagenta"), CENT("PmenuSel ctermbg=LightGrey ctermfg=Black", "PmenuSel ctermbg=LightGrey ctermfg=Black guibg=Grey"), #endif CENT("SpecialKey term=bold ctermfg=DarkBlue", "SpecialKey term=bold ctermfg=DarkBlue guifg=Blue"), CENT("Title term=bold ctermfg=DarkMagenta", "Title term=bold ctermfg=DarkMagenta gui=bold guifg=Magenta"), CENT("WarningMsg term=standout ctermfg=DarkRed", "WarningMsg term=standout ctermfg=DarkRed guifg=Red"), #ifdef FEAT_WILDMENU CENT("WildMenu term=standout ctermbg=Yellow ctermfg=Black", "WildMenu term=standout ctermbg=Yellow ctermfg=Black guibg=Yellow guifg=Black"), #endif #ifdef FEAT_FOLDING CENT("Folded term=standout ctermbg=Grey ctermfg=DarkBlue", "Folded term=standout ctermbg=Grey ctermfg=DarkBlue guibg=LightGrey guifg=DarkBlue"), CENT("FoldColumn term=standout ctermbg=Grey ctermfg=DarkBlue", "FoldColumn term=standout ctermbg=Grey ctermfg=DarkBlue guibg=Grey guifg=DarkBlue"), #endif #ifdef FEAT_SIGNS CENT("SignColumn term=standout ctermbg=Grey ctermfg=DarkBlue", "SignColumn term=standout ctermbg=Grey ctermfg=DarkBlue guibg=Grey guifg=DarkBlue"), #endif #ifdef FEAT_VISUAL CENT("Visual term=reverse", "Visual term=reverse guibg=LightGrey"), #endif #ifdef FEAT_DIFF CENT("DiffAdd term=bold ctermbg=LightBlue", "DiffAdd term=bold ctermbg=LightBlue guibg=LightBlue"), CENT("DiffChange term=bold ctermbg=LightMagenta", "DiffChange term=bold ctermbg=LightMagenta guibg=LightMagenta"), CENT("DiffDelete term=bold ctermfg=Blue ctermbg=LightCyan", "DiffDelete term=bold ctermfg=Blue ctermbg=LightCyan gui=bold guifg=Blue guibg=LightCyan"), #endif #ifdef FEAT_WINDOWS CENT("TabLine term=underline cterm=underline ctermfg=black ctermbg=LightGrey", "TabLine term=underline cterm=underline ctermfg=black ctermbg=LightGrey gui=underline guibg=LightGrey"), #endif #ifdef FEAT_SYN_HL CENT("CursorColumn term=reverse ctermbg=LightGrey", "CursorColumn term=reverse ctermbg=LightGrey guibg=Grey90"), CENT("CursorLine term=underline cterm=underline", "CursorLine term=underline cterm=underline guibg=Grey90"), CENT("ColorColumn term=reverse ctermbg=LightRed", "ColorColumn term=reverse ctermbg=LightRed guibg=LightRed"), #endif #ifdef FEAT_CONCEAL CENT("Conceal ctermbg=DarkGrey ctermfg=LightGrey", "Conceal ctermbg=DarkGrey ctermfg=LightGrey guibg=DarkGrey guifg=LightGrey"), #endif #ifdef FEAT_AUTOCMD CENT("MatchParen term=reverse ctermbg=Cyan", "MatchParen term=reverse ctermbg=Cyan guibg=Cyan"), #endif #ifdef FEAT_GUI "Normal gui=NONE", #endif NULL }; static char *(highlight_init_dark[]) = { CENT("Directory term=bold ctermfg=LightCyan", "Directory term=bold ctermfg=LightCyan guifg=Cyan"), CENT("LineNr term=underline ctermfg=Yellow", "LineNr term=underline ctermfg=Yellow guifg=Yellow"), CENT("CursorLineNr term=bold ctermfg=Yellow", "CursorLineNr term=bold ctermfg=Yellow gui=bold guifg=Yellow"), CENT("MoreMsg term=bold ctermfg=LightGreen", "MoreMsg term=bold ctermfg=LightGreen gui=bold guifg=SeaGreen"), CENT("Question term=standout ctermfg=LightGreen", "Question term=standout ctermfg=LightGreen gui=bold guifg=Green"), CENT("Search term=reverse ctermbg=Yellow ctermfg=Black", "Search term=reverse ctermbg=Yellow ctermfg=Black guibg=Yellow guifg=Black"), CENT("SpecialKey term=bold ctermfg=LightBlue", "SpecialKey term=bold ctermfg=LightBlue guifg=Cyan"), #ifdef FEAT_SPELL CENT("SpellBad term=reverse ctermbg=Red", "SpellBad term=reverse ctermbg=Red guisp=Red gui=undercurl"), CENT("SpellCap term=reverse ctermbg=Blue", "SpellCap term=reverse ctermbg=Blue guisp=Blue gui=undercurl"), CENT("SpellRare term=reverse ctermbg=Magenta", "SpellRare term=reverse ctermbg=Magenta guisp=Magenta gui=undercurl"), CENT("SpellLocal term=underline ctermbg=Cyan", "SpellLocal term=underline ctermbg=Cyan guisp=Cyan gui=undercurl"), #endif #ifdef FEAT_INS_EXPAND CENT("PmenuThumb ctermbg=White", "PmenuThumb ctermbg=White guibg=White"), CENT("Pmenu ctermbg=Magenta ctermfg=Black", "Pmenu ctermbg=Magenta ctermfg=Black guibg=Magenta"), CENT("PmenuSel ctermbg=DarkGrey ctermfg=Black", "PmenuSel ctermbg=DarkGrey ctermfg=Black guibg=DarkGrey"), #endif CENT("Title term=bold ctermfg=LightMagenta", "Title term=bold ctermfg=LightMagenta gui=bold guifg=Magenta"), CENT("WarningMsg term=standout ctermfg=LightRed", "WarningMsg term=standout ctermfg=LightRed guifg=Red"), #ifdef FEAT_WILDMENU CENT("WildMenu term=standout ctermbg=Yellow ctermfg=Black", "WildMenu term=standout ctermbg=Yellow ctermfg=Black guibg=Yellow guifg=Black"), #endif #ifdef FEAT_FOLDING CENT("Folded term=standout ctermbg=DarkGrey ctermfg=Cyan", "Folded term=standout ctermbg=DarkGrey ctermfg=Cyan guibg=DarkGrey guifg=Cyan"), CENT("FoldColumn term=standout ctermbg=DarkGrey ctermfg=Cyan", "FoldColumn term=standout ctermbg=DarkGrey ctermfg=Cyan guibg=Grey guifg=Cyan"), #endif #ifdef FEAT_SIGNS CENT("SignColumn term=standout ctermbg=DarkGrey ctermfg=Cyan", "SignColumn term=standout ctermbg=DarkGrey ctermfg=Cyan guibg=Grey guifg=Cyan"), #endif #ifdef FEAT_VISUAL CENT("Visual term=reverse", "Visual term=reverse guibg=DarkGrey"), #endif #ifdef FEAT_DIFF CENT("DiffAdd term=bold ctermbg=DarkBlue", "DiffAdd term=bold ctermbg=DarkBlue guibg=DarkBlue"), CENT("DiffChange term=bold ctermbg=DarkMagenta", "DiffChange term=bold ctermbg=DarkMagenta guibg=DarkMagenta"), CENT("DiffDelete term=bold ctermfg=Blue ctermbg=DarkCyan", "DiffDelete term=bold ctermfg=Blue ctermbg=DarkCyan gui=bold guifg=Blue guibg=DarkCyan"), #endif #ifdef FEAT_WINDOWS CENT("TabLine term=underline cterm=underline ctermfg=white ctermbg=DarkGrey", "TabLine term=underline cterm=underline ctermfg=white ctermbg=DarkGrey gui=underline guibg=DarkGrey"), #endif #ifdef FEAT_SYN_HL CENT("CursorColumn term=reverse ctermbg=DarkGrey", "CursorColumn term=reverse ctermbg=DarkGrey guibg=Grey40"), CENT("CursorLine term=underline cterm=underline", "CursorLine term=underline cterm=underline guibg=Grey40"), CENT("ColorColumn term=reverse ctermbg=DarkRed", "ColorColumn term=reverse ctermbg=DarkRed guibg=DarkRed"), #endif #ifdef FEAT_AUTOCMD CENT("MatchParen term=reverse ctermbg=DarkCyan", "MatchParen term=reverse ctermbg=DarkCyan guibg=DarkCyan"), #endif #ifdef FEAT_CONCEAL CENT("Conceal ctermbg=DarkGrey ctermfg=LightGrey", "Conceal ctermbg=DarkGrey ctermfg=LightGrey guibg=DarkGrey guifg=LightGrey"), #endif #ifdef FEAT_GUI "Normal gui=NONE", #endif NULL }; void init_highlight(both, reset) int both; /* include groups where 'bg' doesn't matter */ int reset; /* clear group first */ { int i; char **pp; static int had_both = FALSE; #ifdef FEAT_EVAL char_u *p; /* * Try finding the color scheme file. Used when a color file was loaded * and 'background' or 't_Co' is changed. */ p = get_var_value((char_u *)"g:colors_name"); if (p != NULL && load_colors(p) == OK) return; #endif /* * Didn't use a color file, use the compiled-in colors. */ if (both) { had_both = TRUE; pp = highlight_init_both; for (i = 0; pp[i] != NULL; ++i) do_highlight((char_u *)pp[i], reset, TRUE); } else if (!had_both) /* Don't do anything before the call with both == TRUE from main(). * Not everything has been setup then, and that call will overrule * everything anyway. */ return; if (*p_bg == 'l') pp = highlight_init_light; else pp = highlight_init_dark; for (i = 0; pp[i] != NULL; ++i) do_highlight((char_u *)pp[i], reset, TRUE); /* Reverse looks ugly, but grey may not work for 8 colors. Thus let it * depend on the number of colors available. * With 8 colors brown is equal to yellow, need to use black for Search fg * to avoid Statement highlighted text disappears. * Clear the attributes, needed when changing the t_Co value. */ if (t_colors > 8) do_highlight((char_u *)(*p_bg == 'l' ? "Visual cterm=NONE ctermbg=LightGrey" : "Visual cterm=NONE ctermbg=DarkGrey"), FALSE, TRUE); else { do_highlight((char_u *)"Visual cterm=reverse ctermbg=NONE", FALSE, TRUE); if (*p_bg == 'l') do_highlight((char_u *)"Search ctermfg=black", FALSE, TRUE); } #ifdef FEAT_SYN_HL /* * If syntax highlighting is enabled load the highlighting for it. */ if (get_var_value((char_u *)"g:syntax_on") != NULL) { static int recursive = 0; if (recursive >= 5) EMSG(_("E679: recursive loop loading syncolor.vim")); else { ++recursive; (void)source_runtime((char_u *)"syntax/syncolor.vim", TRUE); --recursive; } } #endif } /* * Load color file "name". * Return OK for success, FAIL for failure. */ int load_colors(name) char_u *name; { char_u *buf; int retval = FAIL; static int recursive = FALSE; /* When being called recursively, this is probably because setting * 'background' caused the highlighting to be reloaded. This means it is * working, thus we should return OK. */ if (recursive) return OK; recursive = TRUE; buf = alloc((unsigned)(STRLEN(name) + 12)); if (buf != NULL) { sprintf((char *)buf, "colors/%s.vim", name); retval = source_runtime(buf, FALSE); vim_free(buf); #ifdef FEAT_AUTOCMD apply_autocmds(EVENT_COLORSCHEME, NULL, NULL, FALSE, curbuf); #endif } recursive = FALSE; return retval; } /* * Handle the ":highlight .." command. * When using ":hi clear" this is called recursively for each group with * "forceit" and "init" both TRUE. */ void do_highlight(line, forceit, init) char_u *line; int forceit; int init; /* TRUE when called for initializing */ { char_u *name_end; char_u *p; char_u *linep; char_u *key_start; char_u *arg_start; char_u *key = NULL, *arg = NULL; long i; int off; int len; int attr; int id; int idx; int dodefault = FALSE; int doclear = FALSE; int dolink = FALSE; int error = FALSE; int color; int is_normal_group = FALSE; /* "Normal" group */ #ifdef FEAT_GUI_X11 int is_menu_group = FALSE; /* "Menu" group */ int is_scrollbar_group = FALSE; /* "Scrollbar" group */ int is_tooltip_group = FALSE; /* "Tooltip" group */ int do_colors = FALSE; /* need to update colors? */ #else # define is_menu_group 0 # define is_tooltip_group 0 #endif /* * If no argument, list current highlighting. */ if (ends_excmd(*line)) { for (i = 1; i <= highlight_ga.ga_len && !got_int; ++i) /* TODO: only call when the group has attributes set */ highlight_list_one((int)i); return; } /* * Isolate the name. */ name_end = skiptowhite(line); linep = skipwhite(name_end); /* * Check for "default" argument. */ if (STRNCMP(line, "default", name_end - line) == 0) { dodefault = TRUE; line = linep; name_end = skiptowhite(line); linep = skipwhite(name_end); } /* * Check for "clear" or "link" argument. */ if (STRNCMP(line, "clear", name_end - line) == 0) doclear = TRUE; if (STRNCMP(line, "link", name_end - line) == 0) dolink = TRUE; /* * ":highlight {group-name}": list highlighting for one group. */ if (!doclear && !dolink && ends_excmd(*linep)) { id = syn_namen2id(line, (int)(name_end - line)); if (id == 0) EMSG2(_("E411: highlight group not found: %s"), line); else highlight_list_one(id); return; } /* * Handle ":highlight link {from} {to}" command. */ if (dolink) { char_u *from_start = linep; char_u *from_end; char_u *to_start; char_u *to_end; int from_id; int to_id; from_end = skiptowhite(from_start); to_start = skipwhite(from_end); to_end = skiptowhite(to_start); if (ends_excmd(*from_start) || ends_excmd(*to_start)) { EMSG2(_("E412: Not enough arguments: \":highlight link %s\""), from_start); return; } if (!ends_excmd(*skipwhite(to_end))) { EMSG2(_("E413: Too many arguments: \":highlight link %s\""), from_start); return; } from_id = syn_check_group(from_start, (int)(from_end - from_start)); if (STRNCMP(to_start, "NONE", 4) == 0) to_id = 0; else to_id = syn_check_group(to_start, (int)(to_end - to_start)); if (from_id > 0 && (!init || HL_TABLE()[from_id - 1].sg_set == 0)) { /* * Don't allow a link when there already is some highlighting * for the group, unless '!' is used */ if (to_id > 0 && !forceit && !init && hl_has_settings(from_id - 1, dodefault)) { if (sourcing_name == NULL && !dodefault) EMSG(_("E414: group has settings, highlight link ignored")); } else { if (!init) HL_TABLE()[from_id - 1].sg_set |= SG_LINK; HL_TABLE()[from_id - 1].sg_link = to_id; #ifdef FEAT_EVAL HL_TABLE()[from_id - 1].sg_scriptID = current_SID; #endif redraw_all_later(SOME_VALID); } } /* Only call highlight_changed() once, after sourcing a syntax file */ need_highlight_changed = TRUE; return; } if (doclear) { /* * ":highlight clear [group]" command. */ line = linep; if (ends_excmd(*line)) { #ifdef FEAT_GUI /* First, we do not destroy the old values, but allocate the new * ones and update the display. THEN we destroy the old values. * If we destroy the old values first, then the old values * (such as GuiFont's or GuiFontset's) will still be displayed but * invalid because they were free'd. */ if (gui.in_use) { # ifdef FEAT_BEVAL_TIP gui_init_tooltip_font(); # endif # if defined(FEAT_MENU) && (defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MOTIF)) gui_init_menu_font(); # endif } # if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_X11) gui_mch_def_colors(); # endif # ifdef FEAT_GUI_X11 # ifdef FEAT_MENU /* This only needs to be done when there is no Menu highlight * group defined by default, which IS currently the case. */ gui_mch_new_menu_colors(); # endif if (gui.in_use) { gui_new_scrollbar_colors(); # ifdef FEAT_BEVAL gui_mch_new_tooltip_colors(); # endif # ifdef FEAT_MENU gui_mch_new_menu_font(); # endif } # endif /* Ok, we're done allocating the new default graphics items. * The screen should already be refreshed at this point. * It is now Ok to clear out the old data. */ #endif #ifdef FEAT_EVAL do_unlet((char_u *)"colors_name", TRUE); #endif restore_cterm_colors(); /* * Clear all default highlight groups and load the defaults. */ for (idx = 0; idx < highlight_ga.ga_len; ++idx) highlight_clear(idx); init_highlight(TRUE, TRUE); #ifdef FEAT_GUI if (gui.in_use) highlight_gui_started(); #endif highlight_changed(); redraw_later_clear(); return; } name_end = skiptowhite(line); linep = skipwhite(name_end); } /* * Find the group name in the table. If it does not exist yet, add it. */ id = syn_check_group(line, (int)(name_end - line)); if (id == 0) /* failed (out of memory) */ return; idx = id - 1; /* index is ID minus one */ /* Return if "default" was used and the group already has settings. */ if (dodefault && hl_has_settings(idx, TRUE)) return; if (STRCMP(HL_TABLE()[idx].sg_name_u, "NORMAL") == 0) is_normal_group = TRUE; #ifdef FEAT_GUI_X11 else if (STRCMP(HL_TABLE()[idx].sg_name_u, "MENU") == 0) is_menu_group = TRUE; else if (STRCMP(HL_TABLE()[idx].sg_name_u, "SCROLLBAR") == 0) is_scrollbar_group = TRUE; else if (STRCMP(HL_TABLE()[idx].sg_name_u, "TOOLTIP") == 0) is_tooltip_group = TRUE; #endif /* Clear the highlighting for ":hi clear {group}" and ":hi clear". */ if (doclear || (forceit && init)) { highlight_clear(idx); if (!doclear) HL_TABLE()[idx].sg_set = 0; } if (!doclear) while (!ends_excmd(*linep)) { key_start = linep; if (*linep == '=') { EMSG2(_("E415: unexpected equal sign: %s"), key_start); error = TRUE; break; } /* * Isolate the key ("term", "ctermfg", "ctermbg", "font", "guifg" or * "guibg"). */ while (*linep && !vim_iswhite(*linep) && *linep != '=') ++linep; vim_free(key); key = vim_strnsave_up(key_start, (int)(linep - key_start)); if (key == NULL) { error = TRUE; break; } linep = skipwhite(linep); if (STRCMP(key, "NONE") == 0) { if (!init || HL_TABLE()[idx].sg_set == 0) { if (!init) HL_TABLE()[idx].sg_set |= SG_TERM+SG_CTERM+SG_GUI; highlight_clear(idx); } continue; } /* * Check for the equal sign. */ if (*linep != '=') { EMSG2(_("E416: missing equal sign: %s"), key_start); error = TRUE; break; } ++linep; /* * Isolate the argument. */ linep = skipwhite(linep); if (*linep == '\'') /* guifg='color name' */ { arg_start = ++linep; linep = vim_strchr(linep, '\''); if (linep == NULL) { EMSG2(_(e_invarg2), key_start); error = TRUE; break; } } else { arg_start = linep; linep = skiptowhite(linep); } if (linep == arg_start) { EMSG2(_("E417: missing argument: %s"), key_start); error = TRUE; break; } vim_free(arg); arg = vim_strnsave(arg_start, (int)(linep - arg_start)); if (arg == NULL) { error = TRUE; break; } if (*linep == '\'') ++linep; /* * Store the argument. */ if ( STRCMP(key, "TERM") == 0 || STRCMP(key, "CTERM") == 0 || STRCMP(key, "GUI") == 0) { attr = 0; off = 0; while (arg[off] != NUL) { for (i = sizeof(hl_attr_table) / sizeof(int); --i >= 0; ) { len = (int)STRLEN(hl_name_table[i]); if (STRNICMP(arg + off, hl_name_table[i], len) == 0) { attr |= hl_attr_table[i]; off += len; break; } } if (i < 0) { EMSG2(_("E418: Illegal value: %s"), arg); error = TRUE; break; } if (arg[off] == ',') /* another one follows */ ++off; } if (error) break; if (*key == 'T') { if (!init || !(HL_TABLE()[idx].sg_set & SG_TERM)) { if (!init) HL_TABLE()[idx].sg_set |= SG_TERM; HL_TABLE()[idx].sg_term = attr; } } else if (*key == 'C') { if (!init || !(HL_TABLE()[idx].sg_set & SG_CTERM)) { if (!init) HL_TABLE()[idx].sg_set |= SG_CTERM; HL_TABLE()[idx].sg_cterm = attr; HL_TABLE()[idx].sg_cterm_bold = FALSE; } } #if defined(FEAT_GUI) || defined(FEAT_EVAL) else { if (!init || !(HL_TABLE()[idx].sg_set & SG_GUI)) { if (!init) HL_TABLE()[idx].sg_set |= SG_GUI; HL_TABLE()[idx].sg_gui = attr; } } #endif } else if (STRCMP(key, "FONT") == 0) { /* in non-GUI fonts are simply ignored */ #ifdef FEAT_GUI if (!gui.shell_created) { /* GUI not started yet, always accept the name. */ vim_free(HL_TABLE()[idx].sg_font_name); HL_TABLE()[idx].sg_font_name = vim_strsave(arg); } else { GuiFont temp_sg_font = HL_TABLE()[idx].sg_font; # ifdef FEAT_XFONTSET GuiFontset temp_sg_fontset = HL_TABLE()[idx].sg_fontset; # endif /* First, save the current font/fontset. * Then try to allocate the font/fontset. * If the allocation fails, HL_TABLE()[idx].sg_font OR * sg_fontset will be set to NOFONT or NOFONTSET respectively. */ HL_TABLE()[idx].sg_font = NOFONT; # ifdef FEAT_XFONTSET HL_TABLE()[idx].sg_fontset = NOFONTSET; # endif hl_do_font(idx, arg, is_normal_group, is_menu_group, is_tooltip_group); # ifdef FEAT_XFONTSET if (HL_TABLE()[idx].sg_fontset != NOFONTSET) { /* New fontset was accepted. Free the old one, if there was * one. */ gui_mch_free_fontset(temp_sg_fontset); vim_free(HL_TABLE()[idx].sg_font_name); HL_TABLE()[idx].sg_font_name = vim_strsave(arg); } else HL_TABLE()[idx].sg_fontset = temp_sg_fontset; # endif if (HL_TABLE()[idx].sg_font != NOFONT) { /* New font was accepted. Free the old one, if there was * one. */ gui_mch_free_font(temp_sg_font); vim_free(HL_TABLE()[idx].sg_font_name); HL_TABLE()[idx].sg_font_name = vim_strsave(arg); } else HL_TABLE()[idx].sg_font = temp_sg_font; } #endif } else if (STRCMP(key, "CTERMFG") == 0 || STRCMP(key, "CTERMBG") == 0) { if (!init || !(HL_TABLE()[idx].sg_set & SG_CTERM)) { if (!init) HL_TABLE()[idx].sg_set |= SG_CTERM; /* When setting the foreground color, and previously the "bold" * flag was set for a light color, reset it now */ if (key[5] == 'F' && HL_TABLE()[idx].sg_cterm_bold) { HL_TABLE()[idx].sg_cterm &= ~HL_BOLD; HL_TABLE()[idx].sg_cterm_bold = FALSE; } if (VIM_ISDIGIT(*arg)) color = atoi((char *)arg); else if (STRICMP(arg, "fg") == 0) { if (cterm_normal_fg_color) color = cterm_normal_fg_color - 1; else { EMSG(_("E419: FG color unknown")); error = TRUE; break; } } else if (STRICMP(arg, "bg") == 0) { if (cterm_normal_bg_color > 0) color = cterm_normal_bg_color - 1; else { EMSG(_("E420: BG color unknown")); error = TRUE; break; } } else { static char *(color_names[28]) = { "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "Brown", "DarkYellow", "Gray", "Grey", "LightGray", "LightGrey", "DarkGray", "DarkGrey", "Blue", "LightBlue", "Green", "LightGreen", "Cyan", "LightCyan", "Red", "LightRed", "Magenta", "LightMagenta", "Yellow", "LightYellow", "White", "NONE"}; static int color_numbers_16[28] = {0, 1, 2, 3, 4, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, -1}; /* for xterm with 88 colors... */ static int color_numbers_88[28] = {0, 4, 2, 6, 1, 5, 32, 72, 84, 84, 7, 7, 82, 82, 12, 43, 10, 61, 14, 63, 9, 74, 13, 75, 11, 78, 15, -1}; /* for xterm with 256 colors... */ static int color_numbers_256[28] = {0, 4, 2, 6, 1, 5, 130, 130, 248, 248, 7, 7, 242, 242, 12, 81, 10, 121, 14, 159, 9, 224, 13, 225, 11, 229, 15, -1}; /* for terminals with less than 16 colors... */ static int color_numbers_8[28] = {0, 4, 2, 6, 1, 5, 3, 3, 7, 7, 7, 7, 0+8, 0+8, 4+8, 4+8, 2+8, 2+8, 6+8, 6+8, 1+8, 1+8, 5+8, 5+8, 3+8, 3+8, 7+8, -1}; #if defined(__QNXNTO__) static int *color_numbers_8_qansi = color_numbers_8; /* On qnx, the 8 & 16 color arrays are the same */ if (STRNCMP(T_NAME, "qansi", 5) == 0) color_numbers_8_qansi = color_numbers_16; #endif /* reduce calls to STRICMP a bit, it can be slow */ off = TOUPPER_ASC(*arg); for (i = (sizeof(color_names) / sizeof(char *)); --i >= 0; ) if (off == color_names[i][0] && STRICMP(arg + 1, color_names[i] + 1) == 0) break; if (i < 0) { EMSG2(_("E421: Color name or number not recognized: %s"), key_start); error = TRUE; break; } /* Use the _16 table to check if its a valid color name. */ color = color_numbers_16[i]; if (color >= 0) { if (t_colors == 8) { /* t_Co is 8: use the 8 colors table */ #if defined(__QNXNTO__) color = color_numbers_8_qansi[i]; #else color = color_numbers_8[i]; #endif if (key[5] == 'F') { /* set/reset bold attribute to get light foreground * colors (on some terminals, e.g. "linux") */ if (color & 8) { HL_TABLE()[idx].sg_cterm |= HL_BOLD; HL_TABLE()[idx].sg_cterm_bold = TRUE; } else HL_TABLE()[idx].sg_cterm &= ~HL_BOLD; } color &= 7; /* truncate to 8 colors */ } else if (t_colors == 16 || t_colors == 88 || t_colors == 256) { /* * Guess: if the termcap entry ends in 'm', it is * probably an xterm-like terminal. Use the changed * order for colors. */ if (*T_CAF != NUL) p = T_CAF; else p = T_CSF; if (*p != NUL && *(p + STRLEN(p) - 1) == 'm') switch (t_colors) { case 16: color = color_numbers_8[i]; break; case 88: color = color_numbers_88[i]; break; case 256: color = color_numbers_256[i]; break; } } } } /* Add one to the argument, to avoid zero. Zero is used for * "NONE", then "color" is -1. */ if (key[5] == 'F') { HL_TABLE()[idx].sg_cterm_fg = color + 1; if (is_normal_group) { cterm_normal_fg_color = color + 1; cterm_normal_fg_bold = (HL_TABLE()[idx].sg_cterm & HL_BOLD); #ifdef FEAT_GUI /* Don't do this if the GUI is used. */ if (!gui.in_use && !gui.starting) #endif { must_redraw = CLEAR; if (termcap_active && color >= 0) term_fg_color(color); } } } else { HL_TABLE()[idx].sg_cterm_bg = color + 1; if (is_normal_group) { cterm_normal_bg_color = color + 1; #ifdef FEAT_GUI /* Don't mess with 'background' if the GUI is used. */ if (!gui.in_use && !gui.starting) #endif { must_redraw = CLEAR; if (color >= 0) { if (termcap_active) term_bg_color(color); if (t_colors < 16) i = (color == 0 || color == 4); else i = (color < 7 || color == 8); /* Set the 'background' option if the value is * wrong. */ if (i != (*p_bg == 'd')) set_option_value((char_u *)"bg", 0L, i ? (char_u *)"dark" : (char_u *)"light", 0); } } } } } } else if (STRCMP(key, "GUIFG") == 0) { #if defined(FEAT_GUI) || defined(FEAT_EVAL) if (!init || !(HL_TABLE()[idx].sg_set & SG_GUI)) { if (!init) HL_TABLE()[idx].sg_set |= SG_GUI; # ifdef FEAT_GUI /* In GUI guifg colors are only used when recognized */ i = color_name2handle(arg); if (i != INVALCOLOR || STRCMP(arg, "NONE") == 0 || !gui.in_use) { HL_TABLE()[idx].sg_gui_fg = i; # endif vim_free(HL_TABLE()[idx].sg_gui_fg_name); if (STRCMP(arg, "NONE")) HL_TABLE()[idx].sg_gui_fg_name = vim_strsave(arg); else HL_TABLE()[idx].sg_gui_fg_name = NULL; # ifdef FEAT_GUI # ifdef FEAT_GUI_X11 if (is_menu_group) gui.menu_fg_pixel = i; if (is_scrollbar_group) gui.scroll_fg_pixel = i; # ifdef FEAT_BEVAL if (is_tooltip_group) gui.tooltip_fg_pixel = i; # endif do_colors = TRUE; # endif } # endif } #endif } else if (STRCMP(key, "GUIBG") == 0) { #if defined(FEAT_GUI) || defined(FEAT_EVAL) if (!init || !(HL_TABLE()[idx].sg_set & SG_GUI)) { if (!init) HL_TABLE()[idx].sg_set |= SG_GUI; # ifdef FEAT_GUI /* In GUI guifg colors are only used when recognized */ i = color_name2handle(arg); if (i != INVALCOLOR || STRCMP(arg, "NONE") == 0 || !gui.in_use) { HL_TABLE()[idx].sg_gui_bg = i; # endif vim_free(HL_TABLE()[idx].sg_gui_bg_name); if (STRCMP(arg, "NONE") != 0) HL_TABLE()[idx].sg_gui_bg_name = vim_strsave(arg); else HL_TABLE()[idx].sg_gui_bg_name = NULL; # ifdef FEAT_GUI # ifdef FEAT_GUI_X11 if (is_menu_group) gui.menu_bg_pixel = i; if (is_scrollbar_group) gui.scroll_bg_pixel = i; # ifdef FEAT_BEVAL if (is_tooltip_group) gui.tooltip_bg_pixel = i; # endif do_colors = TRUE; # endif } # endif } #endif } else if (STRCMP(key, "GUISP") == 0) { #if defined(FEAT_GUI) || defined(FEAT_EVAL) if (!init || !(HL_TABLE()[idx].sg_set & SG_GUI)) { if (!init) HL_TABLE()[idx].sg_set |= SG_GUI; # ifdef FEAT_GUI i = color_name2handle(arg); if (i != INVALCOLOR || STRCMP(arg, "NONE") == 0 || !gui.in_use) { HL_TABLE()[idx].sg_gui_sp = i; # endif vim_free(HL_TABLE()[idx].sg_gui_sp_name); if (STRCMP(arg, "NONE") != 0) HL_TABLE()[idx].sg_gui_sp_name = vim_strsave(arg); else HL_TABLE()[idx].sg_gui_sp_name = NULL; # ifdef FEAT_GUI } # endif } #endif } else if (STRCMP(key, "START") == 0 || STRCMP(key, "STOP") == 0) { char_u buf[100]; char_u *tname; if (!init) HL_TABLE()[idx].sg_set |= SG_TERM; /* * The "start" and "stop" arguments can be a literal escape * sequence, or a comma separated list of terminal codes. */ if (STRNCMP(arg, "t_", 2) == 0) { off = 0; buf[0] = 0; while (arg[off] != NUL) { /* Isolate one termcap name */ for (len = 0; arg[off + len] && arg[off + len] != ','; ++len) ; tname = vim_strnsave(arg + off, len); if (tname == NULL) /* out of memory */ { error = TRUE; break; } /* lookup the escape sequence for the item */ p = get_term_code(tname); vim_free(tname); if (p == NULL) /* ignore non-existing things */ p = (char_u *)""; /* Append it to the already found stuff */ if ((int)(STRLEN(buf) + STRLEN(p)) >= 99) { EMSG2(_("E422: terminal code too long: %s"), arg); error = TRUE; break; } STRCAT(buf, p); /* Advance to the next item */ off += len; if (arg[off] == ',') /* another one follows */ ++off; } } else { /* * Copy characters from arg[] to buf[], translating <> codes. */ for (p = arg, off = 0; off < 100 - 6 && *p; ) { len = trans_special(&p, buf + off, FALSE); if (len > 0) /* recognized special char */ off += len; else /* copy as normal char */ buf[off++] = *p++; } buf[off] = NUL; } if (error) break; if (STRCMP(buf, "NONE") == 0) /* resetting the value */ p = NULL; else p = vim_strsave(buf); if (key[2] == 'A') { vim_free(HL_TABLE()[idx].sg_start); HL_TABLE()[idx].sg_start = p; } else { vim_free(HL_TABLE()[idx].sg_stop); HL_TABLE()[idx].sg_stop = p; } } else { EMSG2(_("E423: Illegal argument: %s"), key_start); error = TRUE; break; } /* * When highlighting has been given for a group, don't link it. */ if (!init || !(HL_TABLE()[idx].sg_set & SG_LINK)) HL_TABLE()[idx].sg_link = 0; /* * Continue with next argument. */ linep = skipwhite(linep); } /* * If there is an error, and it's a new entry, remove it from the table. */ if (error && idx == highlight_ga.ga_len) syn_unadd_group(); else { if (is_normal_group) { HL_TABLE()[idx].sg_term_attr = 0; HL_TABLE()[idx].sg_cterm_attr = 0; #ifdef FEAT_GUI HL_TABLE()[idx].sg_gui_attr = 0; /* * Need to update all groups, because they might be using "bg" * and/or "fg", which have been changed now. */ if (gui.in_use) highlight_gui_started(); #endif } #ifdef FEAT_GUI_X11 # ifdef FEAT_MENU else if (is_menu_group) { if (gui.in_use && do_colors) gui_mch_new_menu_colors(); } # endif else if (is_scrollbar_group) { if (gui.in_use && do_colors) gui_new_scrollbar_colors(); } # ifdef FEAT_BEVAL else if (is_tooltip_group) { if (gui.in_use && do_colors) gui_mch_new_tooltip_colors(); } # endif #endif else set_hl_attr(idx); #ifdef FEAT_EVAL HL_TABLE()[idx].sg_scriptID = current_SID; #endif redraw_all_later(NOT_VALID); } vim_free(key); vim_free(arg); /* Only call highlight_changed() once, after sourcing a syntax file */ need_highlight_changed = TRUE; } #if defined(EXITFREE) || defined(PROTO) void free_highlight() { int i; for (i = 0; i < highlight_ga.ga_len; ++i) { highlight_clear(i); vim_free(HL_TABLE()[i].sg_name); vim_free(HL_TABLE()[i].sg_name_u); } ga_clear(&highlight_ga); } #endif /* * Reset the cterm colors to what they were before Vim was started, if * possible. Otherwise reset them to zero. */ void restore_cterm_colors() { #if defined(MSDOS) || (defined(WIN3264) && !defined(FEAT_GUI_W32)) /* Since t_me has been set, this probably means that the user * wants to use this as default colors. Need to reset default * background/foreground colors. */ mch_set_normal_colors(); #else cterm_normal_fg_color = 0; cterm_normal_fg_bold = 0; cterm_normal_bg_color = 0; #endif } /* * Return TRUE if highlight group "idx" has any settings. * When "check_link" is TRUE also check for an existing link. */ static int hl_has_settings(idx, check_link) int idx; int check_link; { return ( HL_TABLE()[idx].sg_term_attr != 0 || HL_TABLE()[idx].sg_cterm_attr != 0 #ifdef FEAT_GUI || HL_TABLE()[idx].sg_gui_attr != 0 #endif || (check_link && (HL_TABLE()[idx].sg_set & SG_LINK))); } /* * Clear highlighting for one group. */ static void highlight_clear(idx) int idx; { HL_TABLE()[idx].sg_term = 0; vim_free(HL_TABLE()[idx].sg_start); HL_TABLE()[idx].sg_start = NULL; vim_free(HL_TABLE()[idx].sg_stop); HL_TABLE()[idx].sg_stop = NULL; HL_TABLE()[idx].sg_term_attr = 0; HL_TABLE()[idx].sg_cterm = 0; HL_TABLE()[idx].sg_cterm_bold = FALSE; HL_TABLE()[idx].sg_cterm_fg = 0; HL_TABLE()[idx].sg_cterm_bg = 0; HL_TABLE()[idx].sg_cterm_attr = 0; #if defined(FEAT_GUI) || defined(FEAT_EVAL) HL_TABLE()[idx].sg_gui = 0; vim_free(HL_TABLE()[idx].sg_gui_fg_name); HL_TABLE()[idx].sg_gui_fg_name = NULL; vim_free(HL_TABLE()[idx].sg_gui_bg_name); HL_TABLE()[idx].sg_gui_bg_name = NULL; vim_free(HL_TABLE()[idx].sg_gui_sp_name); HL_TABLE()[idx].sg_gui_sp_name = NULL; #endif #ifdef FEAT_GUI HL_TABLE()[idx].sg_gui_fg = INVALCOLOR; HL_TABLE()[idx].sg_gui_bg = INVALCOLOR; HL_TABLE()[idx].sg_gui_sp = INVALCOLOR; gui_mch_free_font(HL_TABLE()[idx].sg_font); HL_TABLE()[idx].sg_font = NOFONT; # ifdef FEAT_XFONTSET gui_mch_free_fontset(HL_TABLE()[idx].sg_fontset); HL_TABLE()[idx].sg_fontset = NOFONTSET; # endif vim_free(HL_TABLE()[idx].sg_font_name); HL_TABLE()[idx].sg_font_name = NULL; HL_TABLE()[idx].sg_gui_attr = 0; #endif #ifdef FEAT_EVAL /* Clear the script ID only when there is no link, since that is not * cleared. */ if (HL_TABLE()[idx].sg_link == 0) HL_TABLE()[idx].sg_scriptID = 0; #endif } #if defined(FEAT_GUI) || defined(PROTO) /* * Set the normal foreground and background colors according to the "Normal" * highlighting group. For X11 also set "Menu", "Scrollbar", and * "Tooltip" colors. */ void set_normal_colors() { if (set_group_colors((char_u *)"Normal", &gui.norm_pixel, &gui.back_pixel, FALSE, TRUE, FALSE)) { gui_mch_new_colors(); must_redraw = CLEAR; } #ifdef FEAT_GUI_X11 if (set_group_colors((char_u *)"Menu", &gui.menu_fg_pixel, &gui.menu_bg_pixel, TRUE, FALSE, FALSE)) { # ifdef FEAT_MENU gui_mch_new_menu_colors(); # endif must_redraw = CLEAR; } # ifdef FEAT_BEVAL if (set_group_colors((char_u *)"Tooltip", &gui.tooltip_fg_pixel, &gui.tooltip_bg_pixel, FALSE, FALSE, TRUE)) { # ifdef FEAT_TOOLBAR gui_mch_new_tooltip_colors(); # endif must_redraw = CLEAR; } #endif if (set_group_colors((char_u *)"Scrollbar", &gui.scroll_fg_pixel, &gui.scroll_bg_pixel, FALSE, FALSE, FALSE)) { gui_new_scrollbar_colors(); must_redraw = CLEAR; } #endif } /* * Set the colors for "Normal", "Menu", "Tooltip" or "Scrollbar". */ static int set_group_colors(name, fgp, bgp, do_menu, use_norm, do_tooltip) char_u *name; guicolor_T *fgp; guicolor_T *bgp; int do_menu; int use_norm; int do_tooltip; { int idx; idx = syn_name2id(name) - 1; if (idx >= 0) { gui_do_one_color(idx, do_menu, do_tooltip); if (HL_TABLE()[idx].sg_gui_fg != INVALCOLOR) *fgp = HL_TABLE()[idx].sg_gui_fg; else if (use_norm) *fgp = gui.def_norm_pixel; if (HL_TABLE()[idx].sg_gui_bg != INVALCOLOR) *bgp = HL_TABLE()[idx].sg_gui_bg; else if (use_norm) *bgp = gui.def_back_pixel; return TRUE; } return FALSE; } /* * Get the font of the "Normal" group. * Returns "" when it's not found or not set. */ char_u * hl_get_font_name() { int id; char_u *s; id = syn_name2id((char_u *)"Normal"); if (id > 0) { s = HL_TABLE()[id - 1].sg_font_name; if (s != NULL) return s; } return (char_u *)""; } /* * Set font for "Normal" group. Called by gui_mch_init_font() when a font has * actually chosen to be used. */ void hl_set_font_name(font_name) char_u *font_name; { int id; id = syn_name2id((char_u *)"Normal"); if (id > 0) { vim_free(HL_TABLE()[id - 1].sg_font_name); HL_TABLE()[id - 1].sg_font_name = vim_strsave(font_name); } } /* * Set background color for "Normal" group. Called by gui_set_bg_color() * when the color is known. */ void hl_set_bg_color_name(name) char_u *name; /* must have been allocated */ { int id; if (name != NULL) { id = syn_name2id((char_u *)"Normal"); if (id > 0) { vim_free(HL_TABLE()[id - 1].sg_gui_bg_name); HL_TABLE()[id - 1].sg_gui_bg_name = name; } } } /* * Set foreground color for "Normal" group. Called by gui_set_fg_color() * when the color is known. */ void hl_set_fg_color_name(name) char_u *name; /* must have been allocated */ { int id; if (name != NULL) { id = syn_name2id((char_u *)"Normal"); if (id > 0) { vim_free(HL_TABLE()[id - 1].sg_gui_fg_name); HL_TABLE()[id - 1].sg_gui_fg_name = name; } } } /* * Return the handle for a color name. * Returns INVALCOLOR when failed. */ static guicolor_T color_name2handle(name) char_u *name; { if (STRCMP(name, "NONE") == 0) return INVALCOLOR; if (STRICMP(name, "fg") == 0 || STRICMP(name, "foreground") == 0) return gui.norm_pixel; if (STRICMP(name, "bg") == 0 || STRICMP(name, "background") == 0) return gui.back_pixel; return gui_get_color(name); } /* * Return the handle for a font name. * Returns NOFONT when failed. */ static GuiFont font_name2handle(name) char_u *name; { if (STRCMP(name, "NONE") == 0) return NOFONT; return gui_mch_get_font(name, TRUE); } # ifdef FEAT_XFONTSET /* * Return the handle for a fontset name. * Returns NOFONTSET when failed. */ static GuiFontset fontset_name2handle(name, fixed_width) char_u *name; int fixed_width; { if (STRCMP(name, "NONE") == 0) return NOFONTSET; return gui_mch_get_fontset(name, TRUE, fixed_width); } # endif /* * Get the font or fontset for one highlight group. */ static void hl_do_font(idx, arg, do_normal, do_menu, do_tooltip) int idx; char_u *arg; int do_normal; /* set normal font */ int do_menu UNUSED; /* set menu font */ int do_tooltip UNUSED; /* set tooltip font */ { # ifdef FEAT_XFONTSET /* If 'guifontset' is not empty, first try using the name as a * fontset. If that doesn't work, use it as a font name. */ if (*p_guifontset != NUL # ifdef FONTSET_ALWAYS || do_menu # endif # ifdef FEAT_BEVAL_TIP /* In Athena & Motif, the Tooltip highlight group is always a fontset */ || do_tooltip # endif ) HL_TABLE()[idx].sg_fontset = fontset_name2handle(arg, 0 # ifdef FONTSET_ALWAYS || do_menu # endif # ifdef FEAT_BEVAL_TIP || do_tooltip # endif ); if (HL_TABLE()[idx].sg_fontset != NOFONTSET) { /* If it worked and it's the Normal group, use it as the * normal fontset. Same for the Menu group. */ if (do_normal) gui_init_font(arg, TRUE); # if (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)) && defined(FEAT_MENU) if (do_menu) { # ifdef FONTSET_ALWAYS gui.menu_fontset = HL_TABLE()[idx].sg_fontset; # else /* YIKES! This is a bug waiting to crash the program */ gui.menu_font = HL_TABLE()[idx].sg_fontset; # endif gui_mch_new_menu_font(); } # ifdef FEAT_BEVAL if (do_tooltip) { /* The Athena widget set cannot currently handle switching between * displaying a single font and a fontset. * If the XtNinternational resource is set to True at widget * creation, then a fontset is always used, otherwise an * XFontStruct is used. */ gui.tooltip_fontset = (XFontSet)HL_TABLE()[idx].sg_fontset; gui_mch_new_tooltip_font(); } # endif # endif } else # endif { HL_TABLE()[idx].sg_font = font_name2handle(arg); /* If it worked and it's the Normal group, use it as the * normal font. Same for the Menu group. */ if (HL_TABLE()[idx].sg_font != NOFONT) { if (do_normal) gui_init_font(arg, FALSE); #ifndef FONTSET_ALWAYS # if (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)) && defined(FEAT_MENU) if (do_menu) { gui.menu_font = HL_TABLE()[idx].sg_font; gui_mch_new_menu_font(); } # endif #endif } } } #endif /* FEAT_GUI */ /* * Table with the specifications for an attribute number. * Note that this table is used by ALL buffers. This is required because the * GUI can redraw at any time for any buffer. */ static garray_T term_attr_table = {0, 0, 0, 0, NULL}; #define TERM_ATTR_ENTRY(idx) ((attrentry_T *)term_attr_table.ga_data)[idx] static garray_T cterm_attr_table = {0, 0, 0, 0, NULL}; #define CTERM_ATTR_ENTRY(idx) ((attrentry_T *)cterm_attr_table.ga_data)[idx] #ifdef FEAT_GUI static garray_T gui_attr_table = {0, 0, 0, 0, NULL}; #define GUI_ATTR_ENTRY(idx) ((attrentry_T *)gui_attr_table.ga_data)[idx] #endif /* * Return the attr number for a set of colors and font. * Add a new entry to the term_attr_table, cterm_attr_table or gui_attr_table * if the combination is new. * Return 0 for error (no more room). */ static int get_attr_entry(table, aep) garray_T *table; attrentry_T *aep; { int i; attrentry_T *taep; static int recursive = FALSE; /* * Init the table, in case it wasn't done yet. */ table->ga_itemsize = sizeof(attrentry_T); table->ga_growsize = 7; /* * Try to find an entry with the same specifications. */ for (i = 0; i < table->ga_len; ++i) { taep = &(((attrentry_T *)table->ga_data)[i]); if ( aep->ae_attr == taep->ae_attr && ( #ifdef FEAT_GUI (table == &gui_attr_table && (aep->ae_u.gui.fg_color == taep->ae_u.gui.fg_color && aep->ae_u.gui.bg_color == taep->ae_u.gui.bg_color && aep->ae_u.gui.sp_color == taep->ae_u.gui.sp_color && aep->ae_u.gui.font == taep->ae_u.gui.font # ifdef FEAT_XFONTSET && aep->ae_u.gui.fontset == taep->ae_u.gui.fontset # endif )) || #endif (table == &term_attr_table && (aep->ae_u.term.start == NULL) == (taep->ae_u.term.start == NULL) && (aep->ae_u.term.start == NULL || STRCMP(aep->ae_u.term.start, taep->ae_u.term.start) == 0) && (aep->ae_u.term.stop == NULL) == (taep->ae_u.term.stop == NULL) && (aep->ae_u.term.stop == NULL || STRCMP(aep->ae_u.term.stop, taep->ae_u.term.stop) == 0)) || (table == &cterm_attr_table && aep->ae_u.cterm.fg_color == taep->ae_u.cterm.fg_color && aep->ae_u.cterm.bg_color == taep->ae_u.cterm.bg_color) )) return i + ATTR_OFF; } if (table->ga_len + ATTR_OFF > MAX_TYPENR) { /* * Running out of attribute entries! remove all attributes, and * compute new ones for all groups. * When called recursively, we are really out of numbers. */ if (recursive) { EMSG(_("E424: Too many different highlighting attributes in use")); return 0; } recursive = TRUE; clear_hl_tables(); must_redraw = CLEAR; for (i = 0; i < highlight_ga.ga_len; ++i) set_hl_attr(i); recursive = FALSE; } /* * This is a new combination of colors and font, add an entry. */ if (ga_grow(table, 1) == FAIL) return 0; taep = &(((attrentry_T *)table->ga_data)[table->ga_len]); vim_memset(taep, 0, sizeof(attrentry_T)); taep->ae_attr = aep->ae_attr; #ifdef FEAT_GUI if (table == &gui_attr_table) { taep->ae_u.gui.fg_color = aep->ae_u.gui.fg_color; taep->ae_u.gui.bg_color = aep->ae_u.gui.bg_color; taep->ae_u.gui.sp_color = aep->ae_u.gui.sp_color; taep->ae_u.gui.font = aep->ae_u.gui.font; # ifdef FEAT_XFONTSET taep->ae_u.gui.fontset = aep->ae_u.gui.fontset; # endif } #endif if (table == &term_attr_table) { if (aep->ae_u.term.start == NULL) taep->ae_u.term.start = NULL; else taep->ae_u.term.start = vim_strsave(aep->ae_u.term.start); if (aep->ae_u.term.stop == NULL) taep->ae_u.term.stop = NULL; else taep->ae_u.term.stop = vim_strsave(aep->ae_u.term.stop); } else if (table == &cterm_attr_table) { taep->ae_u.cterm.fg_color = aep->ae_u.cterm.fg_color; taep->ae_u.cterm.bg_color = aep->ae_u.cterm.bg_color; } ++table->ga_len; return (table->ga_len - 1 + ATTR_OFF); } /* * Clear all highlight tables. */ void clear_hl_tables() { int i; attrentry_T *taep; #ifdef FEAT_GUI ga_clear(&gui_attr_table); #endif for (i = 0; i < term_attr_table.ga_len; ++i) { taep = &(((attrentry_T *)term_attr_table.ga_data)[i]); vim_free(taep->ae_u.term.start); vim_free(taep->ae_u.term.stop); } ga_clear(&term_attr_table); ga_clear(&cterm_attr_table); } #if defined(FEAT_SYN_HL) || defined(FEAT_SPELL) || defined(PROTO) /* * Combine special attributes (e.g., for spelling) with other attributes * (e.g., for syntax highlighting). * "prim_attr" overrules "char_attr". * This creates a new group when required. * Since we expect there to be few spelling mistakes we don't cache the * result. * Return the resulting attributes. */ int hl_combine_attr(char_attr, prim_attr) int char_attr; int prim_attr; { attrentry_T *char_aep = NULL; attrentry_T *spell_aep; attrentry_T new_en; if (char_attr == 0) return prim_attr; if (char_attr <= HL_ALL && prim_attr <= HL_ALL) return char_attr | prim_attr; #ifdef FEAT_GUI if (gui.in_use) { if (char_attr > HL_ALL) char_aep = syn_gui_attr2entry(char_attr); if (char_aep != NULL) new_en = *char_aep; else { vim_memset(&new_en, 0, sizeof(new_en)); new_en.ae_u.gui.fg_color = INVALCOLOR; new_en.ae_u.gui.bg_color = INVALCOLOR; new_en.ae_u.gui.sp_color = INVALCOLOR; if (char_attr <= HL_ALL) new_en.ae_attr = char_attr; } if (prim_attr <= HL_ALL) new_en.ae_attr |= prim_attr; else { spell_aep = syn_gui_attr2entry(prim_attr); if (spell_aep != NULL) { new_en.ae_attr |= spell_aep->ae_attr; if (spell_aep->ae_u.gui.fg_color != INVALCOLOR) new_en.ae_u.gui.fg_color = spell_aep->ae_u.gui.fg_color; if (spell_aep->ae_u.gui.bg_color != INVALCOLOR) new_en.ae_u.gui.bg_color = spell_aep->ae_u.gui.bg_color; if (spell_aep->ae_u.gui.sp_color != INVALCOLOR) new_en.ae_u.gui.sp_color = spell_aep->ae_u.gui.sp_color; if (spell_aep->ae_u.gui.font != NOFONT) new_en.ae_u.gui.font = spell_aep->ae_u.gui.font; # ifdef FEAT_XFONTSET if (spell_aep->ae_u.gui.fontset != NOFONTSET) new_en.ae_u.gui.fontset = spell_aep->ae_u.gui.fontset; # endif } } return get_attr_entry(&gui_attr_table, &new_en); } #endif if (t_colors > 1) { if (char_attr > HL_ALL) char_aep = syn_cterm_attr2entry(char_attr); if (char_aep != NULL) new_en = *char_aep; else { vim_memset(&new_en, 0, sizeof(new_en)); if (char_attr <= HL_ALL) new_en.ae_attr = char_attr; } if (prim_attr <= HL_ALL) new_en.ae_attr |= prim_attr; else { spell_aep = syn_cterm_attr2entry(prim_attr); if (spell_aep != NULL) { new_en.ae_attr |= spell_aep->ae_attr; if (spell_aep->ae_u.cterm.fg_color > 0) new_en.ae_u.cterm.fg_color = spell_aep->ae_u.cterm.fg_color; if (spell_aep->ae_u.cterm.bg_color > 0) new_en.ae_u.cterm.bg_color = spell_aep->ae_u.cterm.bg_color; } } return get_attr_entry(&cterm_attr_table, &new_en); } if (char_attr > HL_ALL) char_aep = syn_term_attr2entry(char_attr); if (char_aep != NULL) new_en = *char_aep; else { vim_memset(&new_en, 0, sizeof(new_en)); if (char_attr <= HL_ALL) new_en.ae_attr = char_attr; } if (prim_attr <= HL_ALL) new_en.ae_attr |= prim_attr; else { spell_aep = syn_term_attr2entry(prim_attr); if (spell_aep != NULL) { new_en.ae_attr |= spell_aep->ae_attr; if (spell_aep->ae_u.term.start != NULL) { new_en.ae_u.term.start = spell_aep->ae_u.term.start; new_en.ae_u.term.stop = spell_aep->ae_u.term.stop; } } } return get_attr_entry(&term_attr_table, &new_en); } #endif #ifdef FEAT_GUI attrentry_T * syn_gui_attr2entry(attr) int attr; { attr -= ATTR_OFF; if (attr >= gui_attr_table.ga_len) /* did ":syntax clear" */ return NULL; return &(GUI_ATTR_ENTRY(attr)); } #endif /* FEAT_GUI */ /* * Get the highlight attributes (HL_BOLD etc.) from an attribute nr. * Only to be used when "attr" > HL_ALL. */ int syn_attr2attr(attr) int attr; { attrentry_T *aep; #ifdef FEAT_GUI if (gui.in_use) aep = syn_gui_attr2entry(attr); else #endif if (t_colors > 1) aep = syn_cterm_attr2entry(attr); else aep = syn_term_attr2entry(attr); if (aep == NULL) /* highlighting not set */ return 0; return aep->ae_attr; } attrentry_T * syn_term_attr2entry(attr) int attr; { attr -= ATTR_OFF; if (attr >= term_attr_table.ga_len) /* did ":syntax clear" */ return NULL; return &(TERM_ATTR_ENTRY(attr)); } attrentry_T * syn_cterm_attr2entry(attr) int attr; { attr -= ATTR_OFF; if (attr >= cterm_attr_table.ga_len) /* did ":syntax clear" */ return NULL; return &(CTERM_ATTR_ENTRY(attr)); } #define LIST_ATTR 1 #define LIST_STRING 2 #define LIST_INT 3 static void highlight_list_one(id) int id; { struct hl_group *sgp; int didh = FALSE; sgp = &HL_TABLE()[id - 1]; /* index is ID minus one */ didh = highlight_list_arg(id, didh, LIST_ATTR, sgp->sg_term, NULL, "term"); didh = highlight_list_arg(id, didh, LIST_STRING, 0, sgp->sg_start, "start"); didh = highlight_list_arg(id, didh, LIST_STRING, 0, sgp->sg_stop, "stop"); didh = highlight_list_arg(id, didh, LIST_ATTR, sgp->sg_cterm, NULL, "cterm"); didh = highlight_list_arg(id, didh, LIST_INT, sgp->sg_cterm_fg, NULL, "ctermfg"); didh = highlight_list_arg(id, didh, LIST_INT, sgp->sg_cterm_bg, NULL, "ctermbg"); #if defined(FEAT_GUI) || defined(FEAT_EVAL) didh = highlight_list_arg(id, didh, LIST_ATTR, sgp->sg_gui, NULL, "gui"); didh = highlight_list_arg(id, didh, LIST_STRING, 0, sgp->sg_gui_fg_name, "guifg"); didh = highlight_list_arg(id, didh, LIST_STRING, 0, sgp->sg_gui_bg_name, "guibg"); didh = highlight_list_arg(id, didh, LIST_STRING, 0, sgp->sg_gui_sp_name, "guisp"); #endif #ifdef FEAT_GUI didh = highlight_list_arg(id, didh, LIST_STRING, 0, sgp->sg_font_name, "font"); #endif if (sgp->sg_link && !got_int) { (void)syn_list_header(didh, 9999, id); didh = TRUE; msg_puts_attr((char_u *)"links to", hl_attr(HLF_D)); msg_putchar(' '); msg_outtrans(HL_TABLE()[HL_TABLE()[id - 1].sg_link - 1].sg_name); } if (!didh) highlight_list_arg(id, didh, LIST_STRING, 0, (char_u *)"cleared", ""); #ifdef FEAT_EVAL if (p_verbose > 0) last_set_msg(sgp->sg_scriptID); #endif } static int highlight_list_arg(id, didh, type, iarg, sarg, name) int id; int didh; int type; int iarg; char_u *sarg; char *name; { char_u buf[100]; char_u *ts; int i; if (got_int) return FALSE; if (type == LIST_STRING ? (sarg != NULL) : (iarg != 0)) { ts = buf; if (type == LIST_INT) sprintf((char *)buf, "%d", iarg - 1); else if (type == LIST_STRING) ts = sarg; else /* type == LIST_ATTR */ { buf[0] = NUL; for (i = 0; hl_attr_table[i] != 0; ++i) { if (iarg & hl_attr_table[i]) { if (buf[0] != NUL) vim_strcat(buf, (char_u *)",", 100); vim_strcat(buf, (char_u *)hl_name_table[i], 100); iarg &= ~hl_attr_table[i]; /* don't want "inverse" */ } } } (void)syn_list_header(didh, (int)(vim_strsize(ts) + STRLEN(name) + 1), id); didh = TRUE; if (!got_int) { if (*name != NUL) { MSG_PUTS_ATTR(name, hl_attr(HLF_D)); MSG_PUTS_ATTR("=", hl_attr(HLF_D)); } msg_outtrans(ts); } } return didh; } #if (((defined(FEAT_EVAL) || defined(FEAT_PRINTER))) && defined(FEAT_SYN_HL)) || defined(PROTO) /* * Return "1" if highlight group "id" has attribute "flag". * Return NULL otherwise. */ char_u * highlight_has_attr(id, flag, modec) int id; int flag; int modec; /* 'g' for GUI, 'c' for cterm, 't' for term */ { int attr; if (id <= 0 || id > highlight_ga.ga_len) return NULL; #if defined(FEAT_GUI) || defined(FEAT_EVAL) if (modec == 'g') attr = HL_TABLE()[id - 1].sg_gui; else #endif if (modec == 'c') attr = HL_TABLE()[id - 1].sg_cterm; else attr = HL_TABLE()[id - 1].sg_term; if (attr & flag) return (char_u *)"1"; return NULL; } #endif #if (defined(FEAT_SYN_HL) && defined(FEAT_EVAL)) || defined(PROTO) /* * Return color name of highlight group "id". */ char_u * highlight_color(id, what, modec) int id; char_u *what; /* "font", "fg", "bg", "sp", "fg#", "bg#" or "sp#" */ int modec; /* 'g' for GUI, 'c' for cterm, 't' for term */ { static char_u name[20]; int n; int fg = FALSE; int sp = FALSE; int font = FALSE; if (id <= 0 || id > highlight_ga.ga_len) return NULL; if (TOLOWER_ASC(what[0]) == 'f' && TOLOWER_ASC(what[1]) == 'g') fg = TRUE; else if (TOLOWER_ASC(what[0]) == 'f' && TOLOWER_ASC(what[1]) == 'o' && TOLOWER_ASC(what[2]) == 'n' && TOLOWER_ASC(what[3]) == 't') font = TRUE; else if (TOLOWER_ASC(what[0]) == 's' && TOLOWER_ASC(what[1]) == 'p') sp = TRUE; else if (!(TOLOWER_ASC(what[0]) == 'b' && TOLOWER_ASC(what[1]) == 'g')) return NULL; if (modec == 'g') { # ifdef FEAT_GUI /* return font name */ if (font) return HL_TABLE()[id - 1].sg_font_name; /* return #RRGGBB form (only possible when GUI is running) */ if (gui.in_use && what[2] == '#') { guicolor_T color; long_u rgb; static char_u buf[10]; if (fg) color = HL_TABLE()[id - 1].sg_gui_fg; else if (sp) color = HL_TABLE()[id - 1].sg_gui_sp; else color = HL_TABLE()[id - 1].sg_gui_bg; if (color == INVALCOLOR) return NULL; rgb = gui_mch_get_rgb(color); sprintf((char *)buf, "#%02x%02x%02x", (unsigned)(rgb >> 16), (unsigned)(rgb >> 8) & 255, (unsigned)rgb & 255); return buf; } #endif if (fg) return (HL_TABLE()[id - 1].sg_gui_fg_name); if (sp) return (HL_TABLE()[id - 1].sg_gui_sp_name); return (HL_TABLE()[id - 1].sg_gui_bg_name); } if (font || sp) return NULL; if (modec == 'c') { if (fg) n = HL_TABLE()[id - 1].sg_cterm_fg - 1; else n = HL_TABLE()[id - 1].sg_cterm_bg - 1; sprintf((char *)name, "%d", n); return name; } /* term doesn't have color */ return NULL; } #endif #if (defined(FEAT_SYN_HL) && defined(FEAT_GUI) && defined(FEAT_PRINTER)) \ || defined(PROTO) /* * Return color name of highlight group "id" as RGB value. */ long_u highlight_gui_color_rgb(id, fg) int id; int fg; /* TRUE = fg, FALSE = bg */ { guicolor_T color; if (id <= 0 || id > highlight_ga.ga_len) return 0L; if (fg) color = HL_TABLE()[id - 1].sg_gui_fg; else color = HL_TABLE()[id - 1].sg_gui_bg; if (color == INVALCOLOR) return 0L; return gui_mch_get_rgb(color); } #endif /* * Output the syntax list header. * Return TRUE when started a new line. */ static int syn_list_header(did_header, outlen, id) int did_header; /* did header already */ int outlen; /* length of string that comes */ int id; /* highlight group id */ { int endcol = 19; int newline = TRUE; if (!did_header) { msg_putchar('\n'); if (got_int) return TRUE; msg_outtrans(HL_TABLE()[id - 1].sg_name); endcol = 15; } else if (msg_col + outlen + 1 >= Columns) { msg_putchar('\n'); if (got_int) return TRUE; } else { if (msg_col >= endcol) /* wrap around is like starting a new line */ newline = FALSE; } if (msg_col >= endcol) /* output at least one space */ endcol = msg_col + 1; if (Columns <= endcol) /* avoid hang for tiny window */ endcol = Columns - 1; msg_advance(endcol); /* Show "xxx" with the attributes. */ if (!did_header) { msg_puts_attr((char_u *)"xxx", syn_id2attr(id)); msg_putchar(' '); } return newline; } /* * Set the attribute numbers for a highlight group. * Called after one of the attributes has changed. */ static void set_hl_attr(idx) int idx; /* index in array */ { attrentry_T at_en; struct hl_group *sgp = HL_TABLE() + idx; /* The "Normal" group doesn't need an attribute number */ if (sgp->sg_name_u != NULL && STRCMP(sgp->sg_name_u, "NORMAL") == 0) return; #ifdef FEAT_GUI /* * For the GUI mode: If there are other than "normal" highlighting * attributes, need to allocate an attr number. */ if (sgp->sg_gui_fg == INVALCOLOR && sgp->sg_gui_bg == INVALCOLOR && sgp->sg_gui_sp == INVALCOLOR && sgp->sg_font == NOFONT # ifdef FEAT_XFONTSET && sgp->sg_fontset == NOFONTSET # endif ) { sgp->sg_gui_attr = sgp->sg_gui; } else { at_en.ae_attr = sgp->sg_gui; at_en.ae_u.gui.fg_color = sgp->sg_gui_fg; at_en.ae_u.gui.bg_color = sgp->sg_gui_bg; at_en.ae_u.gui.sp_color = sgp->sg_gui_sp; at_en.ae_u.gui.font = sgp->sg_font; # ifdef FEAT_XFONTSET at_en.ae_u.gui.fontset = sgp->sg_fontset; # endif sgp->sg_gui_attr = get_attr_entry(&gui_attr_table, &at_en); } #endif /* * For the term mode: If there are other than "normal" highlighting * attributes, need to allocate an attr number. */ if (sgp->sg_start == NULL && sgp->sg_stop == NULL) sgp->sg_term_attr = sgp->sg_term; else { at_en.ae_attr = sgp->sg_term; at_en.ae_u.term.start = sgp->sg_start; at_en.ae_u.term.stop = sgp->sg_stop; sgp->sg_term_attr = get_attr_entry(&term_attr_table, &at_en); } /* * For the color term mode: If there are other than "normal" * highlighting attributes, need to allocate an attr number. */ if (sgp->sg_cterm_fg == 0 && sgp->sg_cterm_bg == 0) sgp->sg_cterm_attr = sgp->sg_cterm; else { at_en.ae_attr = sgp->sg_cterm; at_en.ae_u.cterm.fg_color = sgp->sg_cterm_fg; at_en.ae_u.cterm.bg_color = sgp->sg_cterm_bg; sgp->sg_cterm_attr = get_attr_entry(&cterm_attr_table, &at_en); } } /* * Lookup a highlight group name and return it's ID. * If it is not found, 0 is returned. */ int syn_name2id(name) char_u *name; { int i; char_u name_u[200]; /* Avoid using stricmp() too much, it's slow on some systems */ /* Avoid alloc()/free(), these are slow too. ID names over 200 chars * don't deserve to be found! */ vim_strncpy(name_u, name, 199); vim_strup(name_u); for (i = highlight_ga.ga_len; --i >= 0; ) if (HL_TABLE()[i].sg_name_u != NULL && STRCMP(name_u, HL_TABLE()[i].sg_name_u) == 0) break; return i + 1; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return TRUE if highlight group "name" exists. */ int highlight_exists(name) char_u *name; { return (syn_name2id(name) > 0); } # if defined(FEAT_SEARCH_EXTRA) || defined(PROTO) /* * Return the name of highlight group "id". * When not a valid ID return an empty string. */ char_u * syn_id2name(id) int id; { if (id <= 0 || id > highlight_ga.ga_len) return (char_u *)""; return HL_TABLE()[id - 1].sg_name; } # endif #endif /* * Like syn_name2id(), but take a pointer + length argument. */ int syn_namen2id(linep, len) char_u *linep; int len; { char_u *name; int id = 0; name = vim_strnsave(linep, len); if (name != NULL) { id = syn_name2id(name); vim_free(name); } return id; } /* * Find highlight group name in the table and return it's ID. * The argument is a pointer to the name and the length of the name. * If it doesn't exist yet, a new entry is created. * Return 0 for failure. */ int syn_check_group(pp, len) char_u *pp; int len; { int id; char_u *name; name = vim_strnsave(pp, len); if (name == NULL) return 0; id = syn_name2id(name); if (id == 0) /* doesn't exist yet */ id = syn_add_group(name); else vim_free(name); return id; } /* * Add new highlight group and return it's ID. * "name" must be an allocated string, it will be consumed. * Return 0 for failure. */ static int syn_add_group(name) char_u *name; { char_u *p; /* Check that the name is ASCII letters, digits and underscore. */ for (p = name; *p != NUL; ++p) { if (!vim_isprintc(*p)) { EMSG(_("E669: Unprintable character in group name")); vim_free(name); return 0; } else if (!ASCII_ISALNUM(*p) && *p != '_') { /* This is an error, but since there previously was no check only * give a warning. */ msg_source(hl_attr(HLF_W)); MSG(_("W18: Invalid character in group name")); break; } } /* * First call for this growarray: init growing array. */ if (highlight_ga.ga_data == NULL) { highlight_ga.ga_itemsize = sizeof(struct hl_group); highlight_ga.ga_growsize = 10; } if (highlight_ga.ga_len >= MAX_HL_ID) { EMSG(_("E849: Too many highlight and syntax groups")); vim_free(name); return 0; } /* * Make room for at least one other syntax_highlight entry. */ if (ga_grow(&highlight_ga, 1) == FAIL) { vim_free(name); return 0; } vim_memset(&(HL_TABLE()[highlight_ga.ga_len]), 0, sizeof(struct hl_group)); HL_TABLE()[highlight_ga.ga_len].sg_name = name; HL_TABLE()[highlight_ga.ga_len].sg_name_u = vim_strsave_up(name); #ifdef FEAT_GUI HL_TABLE()[highlight_ga.ga_len].sg_gui_bg = INVALCOLOR; HL_TABLE()[highlight_ga.ga_len].sg_gui_fg = INVALCOLOR; HL_TABLE()[highlight_ga.ga_len].sg_gui_sp = INVALCOLOR; #endif ++highlight_ga.ga_len; return highlight_ga.ga_len; /* ID is index plus one */ } /* * When, just after calling syn_add_group(), an error is discovered, this * function deletes the new name. */ static void syn_unadd_group() { --highlight_ga.ga_len; vim_free(HL_TABLE()[highlight_ga.ga_len].sg_name); vim_free(HL_TABLE()[highlight_ga.ga_len].sg_name_u); } /* * Translate a group ID to highlight attributes. */ int syn_id2attr(hl_id) int hl_id; { int attr; struct hl_group *sgp; hl_id = syn_get_final_id(hl_id); sgp = &HL_TABLE()[hl_id - 1]; /* index is ID minus one */ #ifdef FEAT_GUI /* * Only use GUI attr when the GUI is being used. */ if (gui.in_use) attr = sgp->sg_gui_attr; else #endif if (t_colors > 1) attr = sgp->sg_cterm_attr; else attr = sgp->sg_term_attr; return attr; } #ifdef FEAT_GUI /* * Get the GUI colors and attributes for a group ID. * NOTE: the colors will be INVALCOLOR when not set, the color otherwise. */ int syn_id2colors(hl_id, fgp, bgp) int hl_id; guicolor_T *fgp; guicolor_T *bgp; { struct hl_group *sgp; hl_id = syn_get_final_id(hl_id); sgp = &HL_TABLE()[hl_id - 1]; /* index is ID minus one */ *fgp = sgp->sg_gui_fg; *bgp = sgp->sg_gui_bg; return sgp->sg_gui; } #endif /* * Translate a group ID to the final group ID (following links). */ int syn_get_final_id(hl_id) int hl_id; { int count; struct hl_group *sgp; if (hl_id > highlight_ga.ga_len || hl_id < 1) return 0; /* Can be called from eval!! */ /* * Follow links until there is no more. * Look out for loops! Break after 100 links. */ for (count = 100; --count >= 0; ) { sgp = &HL_TABLE()[hl_id - 1]; /* index is ID minus one */ if (sgp->sg_link == 0 || sgp->sg_link > highlight_ga.ga_len) break; hl_id = sgp->sg_link; } return hl_id; } #ifdef FEAT_GUI /* * Call this function just after the GUI has started. * It finds the font and color handles for the highlighting groups. */ void highlight_gui_started() { int idx; /* First get the colors from the "Normal" and "Menu" group, if set */ set_normal_colors(); for (idx = 0; idx < highlight_ga.ga_len; ++idx) gui_do_one_color(idx, FALSE, FALSE); highlight_changed(); } static void gui_do_one_color(idx, do_menu, do_tooltip) int idx; int do_menu; /* TRUE: might set the menu font */ int do_tooltip; /* TRUE: might set the tooltip font */ { int didit = FALSE; if (HL_TABLE()[idx].sg_font_name != NULL) { hl_do_font(idx, HL_TABLE()[idx].sg_font_name, FALSE, do_menu, do_tooltip); didit = TRUE; } if (HL_TABLE()[idx].sg_gui_fg_name != NULL) { HL_TABLE()[idx].sg_gui_fg = color_name2handle(HL_TABLE()[idx].sg_gui_fg_name); didit = TRUE; } if (HL_TABLE()[idx].sg_gui_bg_name != NULL) { HL_TABLE()[idx].sg_gui_bg = color_name2handle(HL_TABLE()[idx].sg_gui_bg_name); didit = TRUE; } if (HL_TABLE()[idx].sg_gui_sp_name != NULL) { HL_TABLE()[idx].sg_gui_sp = color_name2handle(HL_TABLE()[idx].sg_gui_sp_name); didit = TRUE; } if (didit) /* need to get a new attr number */ set_hl_attr(idx); } #endif /* * Translate the 'highlight' option into attributes in highlight_attr[] and * set up the user highlights User1..9. If FEAT_STL_OPT is in use, a set of * corresponding highlights to use on top of HLF_SNC is computed. * Called only when the 'highlight' option has been changed and upon first * screen redraw after any :highlight command. * Return FAIL when an invalid flag is found in 'highlight'. OK otherwise. */ int highlight_changed() { int hlf; int i; char_u *p; int attr; char_u *end; int id; #ifdef USER_HIGHLIGHT char_u userhl[10]; # ifdef FEAT_STL_OPT int id_SNC = -1; int id_S = -1; int hlcnt; # endif #endif static int hl_flags[HLF_COUNT] = HL_FLAGS; need_highlight_changed = FALSE; /* * Clear all attributes. */ for (hlf = 0; hlf < (int)HLF_COUNT; ++hlf) highlight_attr[hlf] = 0; /* * First set all attributes to their default value. * Then use the attributes from the 'highlight' option. */ for (i = 0; i < 2; ++i) { if (i) p = p_hl; else p = get_highlight_default(); if (p == NULL) /* just in case */ continue; while (*p) { for (hlf = 0; hlf < (int)HLF_COUNT; ++hlf) if (hl_flags[hlf] == *p) break; ++p; if (hlf == (int)HLF_COUNT || *p == NUL) return FAIL; /* * Allow several hl_flags to be combined, like "bu" for * bold-underlined. */ attr = 0; for ( ; *p && *p != ','; ++p) /* parse upto comma */ { if (vim_iswhite(*p)) /* ignore white space */ continue; if (attr > HL_ALL) /* Combination with ':' is not allowed. */ return FAIL; switch (*p) { case 'b': attr |= HL_BOLD; break; case 'i': attr |= HL_ITALIC; break; case '-': case 'n': /* no highlighting */ break; case 'r': attr |= HL_INVERSE; break; case 's': attr |= HL_STANDOUT; break; case 'u': attr |= HL_UNDERLINE; break; case 'c': attr |= HL_UNDERCURL; break; case ':': ++p; /* highlight group name */ if (attr || *p == NUL) /* no combinations */ return FAIL; end = vim_strchr(p, ','); if (end == NULL) end = p + STRLEN(p); id = syn_check_group(p, (int)(end - p)); if (id == 0) return FAIL; attr = syn_id2attr(id); p = end - 1; #if defined(FEAT_STL_OPT) && defined(USER_HIGHLIGHT) if (hlf == (int)HLF_SNC) id_SNC = syn_get_final_id(id); else if (hlf == (int)HLF_S) id_S = syn_get_final_id(id); #endif break; default: return FAIL; } } highlight_attr[hlf] = attr; p = skip_to_option_part(p); /* skip comma and spaces */ } } #ifdef USER_HIGHLIGHT /* Setup the user highlights * * Temporarily utilize 10 more hl entries. Have to be in there * simultaneously in case of table overflows in get_attr_entry() */ # ifdef FEAT_STL_OPT if (ga_grow(&highlight_ga, 10) == FAIL) return FAIL; hlcnt = highlight_ga.ga_len; if (id_S == 0) { /* Make sure id_S is always valid to simplify code below */ vim_memset(&HL_TABLE()[hlcnt + 9], 0, sizeof(struct hl_group)); HL_TABLE()[hlcnt + 9].sg_term = highlight_attr[HLF_S]; id_S = hlcnt + 10; } # endif for (i = 0; i < 9; i++) { sprintf((char *)userhl, "User%d", i + 1); id = syn_name2id(userhl); if (id == 0) { highlight_user[i] = 0; # ifdef FEAT_STL_OPT highlight_stlnc[i] = 0; # endif } else { # ifdef FEAT_STL_OPT struct hl_group *hlt = HL_TABLE(); # endif highlight_user[i] = syn_id2attr(id); # ifdef FEAT_STL_OPT if (id_SNC == 0) { vim_memset(&hlt[hlcnt + i], 0, sizeof(struct hl_group)); hlt[hlcnt + i].sg_term = highlight_attr[HLF_SNC]; hlt[hlcnt + i].sg_cterm = highlight_attr[HLF_SNC]; # if defined(FEAT_GUI) || defined(FEAT_EVAL) hlt[hlcnt + i].sg_gui = highlight_attr[HLF_SNC]; # endif } else mch_memmove(&hlt[hlcnt + i], &hlt[id_SNC - 1], sizeof(struct hl_group)); hlt[hlcnt + i].sg_link = 0; /* Apply difference between UserX and HLF_S to HLF_SNC */ hlt[hlcnt + i].sg_term ^= hlt[id - 1].sg_term ^ hlt[id_S - 1].sg_term; if (hlt[id - 1].sg_start != hlt[id_S - 1].sg_start) hlt[hlcnt + i].sg_start = hlt[id - 1].sg_start; if (hlt[id - 1].sg_stop != hlt[id_S - 1].sg_stop) hlt[hlcnt + i].sg_stop = hlt[id - 1].sg_stop; hlt[hlcnt + i].sg_cterm ^= hlt[id - 1].sg_cterm ^ hlt[id_S - 1].sg_cterm; if (hlt[id - 1].sg_cterm_fg != hlt[id_S - 1].sg_cterm_fg) hlt[hlcnt + i].sg_cterm_fg = hlt[id - 1].sg_cterm_fg; if (hlt[id - 1].sg_cterm_bg != hlt[id_S - 1].sg_cterm_bg) hlt[hlcnt + i].sg_cterm_bg = hlt[id - 1].sg_cterm_bg; # if defined(FEAT_GUI) || defined(FEAT_EVAL) hlt[hlcnt + i].sg_gui ^= hlt[id - 1].sg_gui ^ hlt[id_S - 1].sg_gui; # endif # ifdef FEAT_GUI if (hlt[id - 1].sg_gui_fg != hlt[id_S - 1].sg_gui_fg) hlt[hlcnt + i].sg_gui_fg = hlt[id - 1].sg_gui_fg; if (hlt[id - 1].sg_gui_bg != hlt[id_S - 1].sg_gui_bg) hlt[hlcnt + i].sg_gui_bg = hlt[id - 1].sg_gui_bg; if (hlt[id - 1].sg_gui_sp != hlt[id_S - 1].sg_gui_sp) hlt[hlcnt + i].sg_gui_sp = hlt[id - 1].sg_gui_sp; if (hlt[id - 1].sg_font != hlt[id_S - 1].sg_font) hlt[hlcnt + i].sg_font = hlt[id - 1].sg_font; # ifdef FEAT_XFONTSET if (hlt[id - 1].sg_fontset != hlt[id_S - 1].sg_fontset) hlt[hlcnt + i].sg_fontset = hlt[id - 1].sg_fontset; # endif # endif highlight_ga.ga_len = hlcnt + i + 1; set_hl_attr(hlcnt + i); /* At long last we can apply */ highlight_stlnc[i] = syn_id2attr(hlcnt + i + 1); # endif } } # ifdef FEAT_STL_OPT highlight_ga.ga_len = hlcnt; # endif #endif /* USER_HIGHLIGHT */ return OK; } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) static void highlight_list __ARGS((void)); static void highlight_list_two __ARGS((int cnt, int attr)); /* * Handle command line completion for :highlight command. */ void set_context_in_highlight_cmd(xp, arg) expand_T *xp; char_u *arg; { char_u *p; /* Default: expand group names */ xp->xp_context = EXPAND_HIGHLIGHT; xp->xp_pattern = arg; include_link = 2; include_default = 1; /* (part of) subcommand already typed */ if (*arg != NUL) { p = skiptowhite(arg); if (*p != NUL) /* past "default" or group name */ { include_default = 0; if (STRNCMP("default", arg, p - arg) == 0) { arg = skipwhite(p); xp->xp_pattern = arg; p = skiptowhite(arg); } if (*p != NUL) /* past group name */ { include_link = 0; if (arg[1] == 'i' && arg[0] == 'N') highlight_list(); if (STRNCMP("link", arg, p - arg) == 0 || STRNCMP("clear", arg, p - arg) == 0) { xp->xp_pattern = skipwhite(p); p = skiptowhite(xp->xp_pattern); if (*p != NUL) /* past first group name */ { xp->xp_pattern = skipwhite(p); p = skiptowhite(xp->xp_pattern); } } if (*p != NUL) /* past group name(s) */ xp->xp_context = EXPAND_NOTHING; } } } } /* * List highlighting matches in a nice way. */ static void highlight_list() { int i; for (i = 10; --i >= 0; ) highlight_list_two(i, hl_attr(HLF_D)); for (i = 40; --i >= 0; ) highlight_list_two(99, 0); } static void highlight_list_two(cnt, attr) int cnt; int attr; { msg_puts_attr((char_u *)&("N \bI \b! \b"[cnt / 11]), attr); msg_clr_eos(); out_flush(); ui_delay(cnt == 99 ? 40L : (long)cnt * 50L, FALSE); } #endif /* FEAT_CMDL_COMPL */ #if defined(FEAT_CMDL_COMPL) || (defined(FEAT_SYN_HL) && defined(FEAT_EVAL)) \ || defined(FEAT_SIGNS) || defined(PROTO) /* * Function given to ExpandGeneric() to obtain the list of group names. * Also used for synIDattr() function. */ char_u * get_highlight_name(xp, idx) expand_T *xp UNUSED; int idx; { #ifdef FEAT_CMDL_COMPL if (idx == highlight_ga.ga_len && include_none != 0) return (char_u *)"none"; if (idx == highlight_ga.ga_len + include_none && include_default != 0) return (char_u *)"default"; if (idx == highlight_ga.ga_len + include_none + include_default && include_link != 0) return (char_u *)"link"; if (idx == highlight_ga.ga_len + include_none + include_default + 1 && include_link != 0) return (char_u *)"clear"; #endif if (idx < 0 || idx >= highlight_ga.ga_len) return NULL; return HL_TABLE()[idx].sg_name; } #endif #if defined(FEAT_GUI) || defined(PROTO) /* * Free all the highlight group fonts. * Used when quitting for systems which need it. */ void free_highlight_fonts() { int idx; for (idx = 0; idx < highlight_ga.ga_len; ++idx) { gui_mch_free_font(HL_TABLE()[idx].sg_font); HL_TABLE()[idx].sg_font = NOFONT; # ifdef FEAT_XFONTSET gui_mch_free_fontset(HL_TABLE()[idx].sg_fontset); HL_TABLE()[idx].sg_fontset = NOFONTSET; # endif } gui_mch_free_font(gui.norm_font); # ifdef FEAT_XFONTSET gui_mch_free_fontset(gui.fontset); # endif # ifndef FEAT_GUI_GTK gui_mch_free_font(gui.bold_font); gui_mch_free_font(gui.ital_font); gui_mch_free_font(gui.boldital_font); # endif } #endif /************************************** * End of Highlighting stuff * **************************************/
zyz2011-vim
src/syntax.c
C
gpl2
253,220
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * feature.h: Defines for optional code and preferences * * Edit this file to include/exclude parts of Vim, before compiling. * The only other file that may be edited is Makefile, it contains machine * specific options. * * To include specific options, change the "#if*" and "#endif" into comments, * or uncomment the "#define". * To exclude specific options, change the "#define" into a comment. */ /* * When adding a new feature: * - Add a #define below. * - Add a message in the table above ex_version(). * - Add a string to f_has(). * - Add a feature to ":help feature-list" in doc/eval.txt. * - Add feature to ":help +feature-list" in doc/various.txt. * - Add comment for the documentation of commands that use the feature. */ /* * Basic choices: * ============== * * +tiny almost no features enabled, not even multiple windows * +small few features enabled, as basic as possible * +normal A default selection of features enabled * +big many features enabled, as rich as possible. * +huge all possible features enabled. * * When +small is used, +tiny is also included. +normal implies +small, etc. */ /* * Uncomment one of these to override the default. For unix use a configure * argument, see Makefile. */ #if !defined(FEAT_TINY) && !defined(FEAT_SMALL) && !defined(FEAT_NORMAL) \ && !defined(FEAT_BIG) && !defined(FEAT_HUGE) /* #define FEAT_TINY */ /* #define FEAT_SMALL */ /* #define FEAT_NORMAL */ /* #define FEAT_BIG */ /* #define FEAT_HUGE */ #endif /* * These executables are made available with the +big feature, because they * are supposed to have enough RAM: Win32 (console & GUI), dos32, OS/2 and VMS. * The dos16 version has very little RAM available, use +small. */ #if !defined(FEAT_TINY) && !defined(FEAT_SMALL) && !defined(FEAT_NORMAL) \ && !defined(FEAT_BIG) && !defined(FEAT_HUGE) # if defined(MSWIN) || defined(DJGPP) || defined(OS2) || defined(VMS) || defined(MACOS) || defined(AMIGA) # define FEAT_BIG # else # ifdef MSDOS # define FEAT_SMALL # else # define FEAT_NORMAL # endif # endif #endif /* * Each feature implies including the "smaller" ones. */ #ifdef FEAT_HUGE # define FEAT_BIG #endif #ifdef FEAT_BIG # define FEAT_NORMAL #endif #ifdef FEAT_NORMAL # define FEAT_SMALL #endif #ifdef FEAT_SMALL # define FEAT_TINY #endif /* * Optional code (see ":help +feature-list") * ============= */ /* * +windows Multiple windows. Without this there is no help * window and no status lines. */ #ifdef FEAT_SMALL # define FEAT_WINDOWS #endif /* * +listcmds Vim commands for the buffer list and the argument * list. Without this there is no ":buffer" ":bnext", * ":bdel", ":argdelete", etc. */ #ifdef FEAT_NORMAL # define FEAT_LISTCMDS #endif /* * +vertsplit Vertically split windows. */ #ifdef FEAT_NORMAL # define FEAT_VERTSPLIT #endif #if defined(FEAT_VERTSPLIT) && !defined(FEAT_WINDOWS) # define FEAT_WINDOWS #endif /* * +cmdhist Command line history. */ #ifdef FEAT_SMALL # define FEAT_CMDHIST #endif /* * Message history is fixed at 200 message, 20 for the tiny version. */ #ifdef FEAT_SMALL # define MAX_MSG_HIST_LEN 200 #else # define MAX_MSG_HIST_LEN 20 #endif /* * +jumplist Jumplist, CTRL-O and CTRL-I commands. */ #ifdef FEAT_SMALL # define FEAT_JUMPLIST #endif /* the cmdline-window requires FEAT_VERTSPLIT and FEAT_CMDHIST */ #if defined(FEAT_VERTSPLIT) && defined(FEAT_CMDHIST) # define FEAT_CMDWIN #endif /* * +folding Fold lines. */ #ifdef FEAT_NORMAL # define FEAT_FOLDING #endif /* * +digraphs Digraphs. * In insert mode and on the command line you will be * able to use digraphs. The CTRL-K command will work. * Define OLD_DIGRAPHS to get digraphs compatible with * Vim 5.x. The new ones are from RFC 1345. */ #ifdef FEAT_NORMAL # define FEAT_DIGRAPHS /* #define OLD_DIGRAPHS */ #endif /* * +langmap 'langmap' option. Only useful when you put your * keyboard in a special language mode, e.g. for typing * greek. */ #ifdef FEAT_BIG # define FEAT_LANGMAP #endif /* * +keymap 'keymap' option. Allows you to map typed keys in * Insert mode for a special language. */ #ifdef FEAT_BIG # define FEAT_KEYMAP #endif /* * +localmap Mappings and abbreviations local to a buffer. */ #ifdef FEAT_NORMAL # define FEAT_LOCALMAP #endif /* * +insert_expand CTRL-N/CTRL-P/CTRL-X in insert mode. Takes about * 4Kbyte of code. */ #ifdef FEAT_NORMAL # define FEAT_INS_EXPAND #endif /* * +cmdline_compl completion of mappings/abbreviations in cmdline mode. * Takes a few Kbyte of code. */ #ifdef FEAT_NORMAL # define FEAT_CMDL_COMPL #endif #ifdef FEAT_NORMAL # define VIM_BACKTICK /* internal backtick expansion */ #endif /* * +visual Visual mode. * +visualextra Extra features for Visual mode (mostly block operators). */ #ifdef FEAT_SMALL # define FEAT_VISUAL # ifdef FEAT_NORMAL # define FEAT_VISUALEXTRA # endif #else # ifdef FEAT_CLIPBOARD # undef FEAT_CLIPBOARD /* can't use clipboard without Visual mode */ # endif #endif /* * +virtualedit 'virtualedit' option and its implementation */ #ifdef FEAT_NORMAL # define FEAT_VIRTUALEDIT #endif /* * +vreplace "gR" and "gr" commands. */ #ifdef FEAT_NORMAL # define FEAT_VREPLACE #endif /* * +cmdline_info 'showcmd' and 'ruler' options. */ #ifdef FEAT_NORMAL # define FEAT_CMDL_INFO #endif /* * +linebreak 'showbreak', 'breakat' and 'linebreak' options. * Also 'numberwidth'. */ #ifdef FEAT_NORMAL # define FEAT_LINEBREAK #endif /* * +ex_extra ":retab", ":right", ":left", ":center", ":normal". */ #ifdef FEAT_NORMAL # define FEAT_EX_EXTRA #endif /* * +extra_search 'hlsearch' and 'incsearch' options. */ #ifdef FEAT_NORMAL # define FEAT_SEARCH_EXTRA #endif /* * +quickfix Quickfix commands. */ #ifdef FEAT_NORMAL # define FEAT_QUICKFIX #endif /* * +file_in_path "gf" and "<cfile>" commands. */ #ifdef FEAT_NORMAL # define FEAT_SEARCHPATH #endif /* * +find_in_path "[I" ":isearch" "^W^I", ":checkpath", etc. */ #ifdef FEAT_NORMAL # ifdef FEAT_SEARCHPATH /* FEAT_SEARCHPATH is required */ # define FEAT_FIND_ID # endif #endif /* * +path_extra up/downwards searching in 'path' and 'tags'. */ #ifdef FEAT_NORMAL # define FEAT_PATH_EXTRA #endif /* * +rightleft Right-to-left editing/typing support. * * Disabled for EBCDIC as it requires multibyte. */ #if defined(FEAT_BIG) && !defined(EBCDIC) # define FEAT_RIGHTLEFT #endif /* * +farsi Farsi (Persian language) Keymap support. * Requires FEAT_RIGHTLEFT. * * Disabled for EBCDIC as it requires multibyte. */ #if defined(FEAT_BIG) && !defined(EBCDIC) # define FEAT_FKMAP #endif #ifdef FEAT_FKMAP # ifndef FEAT_RIGHTLEFT # define FEAT_RIGHTLEFT # endif #endif /* * +arabic Arabic keymap and shaping support. * Requires FEAT_RIGHTLEFT and FEAT_MBYTE. * * Disabled for EBCDIC as it requires multibyte. */ #if defined(FEAT_BIG) && !defined(WIN16) && SIZEOF_INT >= 4 && !defined(EBCDIC) # define FEAT_ARABIC #endif #ifdef FEAT_ARABIC # ifndef FEAT_RIGHTLEFT # define FEAT_RIGHTLEFT # endif #endif /* * +emacs_tags When FEAT_EMACS_TAGS defined: Include support for * emacs style TAGS file. */ #ifdef FEAT_BIG # define FEAT_EMACS_TAGS #endif /* * +tag_binary Can use a binary search for the tags file. * * Disabled for EBCDIC: * On z/OS Unix we have the problem that /bin/sort sorts ASCII instead of * EBCDIC. With this binary search doesn't work, as VIM expects a tag file * sorted by character values. I'm not sure how to fix this. Should we really * do a EBCDIC to ASCII conversion for this?? */ #if defined(FEAT_NORMAL) && !defined(EBCDIC) # define FEAT_TAG_BINS #endif /* * +tag_old_static Old style static tags: "file:tag file ..". Slows * down tag searching a bit. */ #ifdef FEAT_NORMAL # define FEAT_TAG_OLDSTATIC #endif /* * +tag_any_white Allow any white space to separate the fields in a tags * file. When not defined, only a TAB is allowed. */ /* #define FEAT_TAG_ANYWHITE */ /* * +cscope Unix only: Cscope support. */ #if defined(UNIX) && defined(FEAT_BIG) && !defined(FEAT_CSCOPE) && !defined(MACOS_X) # define FEAT_CSCOPE #endif /* * +eval Built-in script language and expression evaluation, * ":let", ":if", etc. * +float Floating point variables. */ #ifdef FEAT_NORMAL # define FEAT_EVAL # if defined(HAVE_FLOAT_FUNCS) || defined(WIN3264) || defined(MACOS) # define FEAT_FLOAT # endif #endif /* * +profile Profiling for functions and scripts. */ #if defined(FEAT_HUGE) \ && defined(FEAT_EVAL) \ && ((defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)) \ || defined(WIN3264)) # define FEAT_PROFILE #endif /* * +reltime reltime() function */ #if defined(FEAT_NORMAL) \ && defined(FEAT_EVAL) \ && ((defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)) \ || defined(WIN3264)) # define FEAT_RELTIME #endif /* * +textobjects Text objects: "vaw", "das", etc. */ #if defined(FEAT_NORMAL) && defined(FEAT_EVAL) # define FEAT_TEXTOBJ #endif /* * Insert mode completion with 'completefunc'. */ #if defined(FEAT_INS_EXPAND) && defined(FEAT_EVAL) # define FEAT_COMPL_FUNC #endif /* * +user_commands Allow the user to define his own commands. */ #ifdef FEAT_NORMAL # define FEAT_USR_CMDS #endif /* * +printer ":hardcopy" command * +postscript Printing uses PostScript file output. */ #if defined(FEAT_NORMAL) && (defined(MSWIN) || defined(FEAT_EVAL)) \ && !defined(AMIGA) # define FEAT_PRINTER #endif #if defined(FEAT_PRINTER) && ((defined(MSWIN) && defined(MSWINPS)) \ || (!defined(MSWIN) && defined(FEAT_EVAL))) # define FEAT_POSTSCRIPT #endif /* * +modify_fname modifiers for file name. E.g., "%:p:h". */ #ifdef FEAT_NORMAL # define FEAT_MODIFY_FNAME #endif /* * +autocmd ":autocmd" command */ #ifdef FEAT_NORMAL # define FEAT_AUTOCMD #endif /* * +diff Displaying diffs in a nice way. * Requires +windows and +autocmd. */ #if defined(FEAT_NORMAL) && defined(FEAT_WINDOWS) && defined(FEAT_AUTOCMD) # define FEAT_DIFF #endif /* * +title 'title' and 'icon' options * +statusline 'statusline', 'rulerformat' and special format of * 'titlestring' and 'iconstring' options. * +byte_offset '%o' in 'statusline' and builtin functions line2byte() * and byte2line(). * Note: Required for Macintosh. */ #if defined(FEAT_NORMAL) && !defined(MSDOS) # define FEAT_TITLE #endif #ifdef FEAT_NORMAL # define FEAT_STL_OPT # ifndef FEAT_CMDL_INFO # define FEAT_CMDL_INFO /* 'ruler' is required for 'statusline' */ # endif #endif #ifdef FEAT_NORMAL # define FEAT_BYTEOFF #endif /* * +wildignore 'wildignore' and 'backupskip' options * Needed for Unix to make "crontab -e" work. */ #if defined(FEAT_NORMAL) || defined(UNIX) # define FEAT_WILDIGN #endif /* * +wildmenu 'wildmenu' option */ #if defined(FEAT_NORMAL) && defined(FEAT_WINDOWS) # define FEAT_WILDMENU #endif /* * +viminfo reading/writing the viminfo file. Takes about 8Kbyte * of code. * VIMINFO_FILE Location of user .viminfo file (should start with $). * VIMINFO_FILE2 Location of alternate user .viminfo file. */ #ifdef FEAT_NORMAL # define FEAT_VIMINFO /* #define VIMINFO_FILE "$HOME/foo/.viminfo" */ /* #define VIMINFO_FILE2 "~/bar/.viminfo" */ #endif /* * +syntax syntax highlighting. When using this, it's a good * idea to have +autocmd and +eval too. */ #if defined(FEAT_NORMAL) || defined(PROTO) # define FEAT_SYN_HL #endif /* * +conceal 'conceal' option. Needs syntax highlighting * as this is how the concealed text is defined. */ #if defined(FEAT_BIG) && defined(FEAT_SYN_HL) # define FEAT_CONCEAL #endif /* * +spell spell checking * * Disabled for EBCDIC: * Doesn't work (SIGSEGV). */ #if (defined(FEAT_NORMAL) || defined(PROTO)) && !defined(EBCDIC) # define FEAT_SPELL #endif /* * +builtin_terms Choose one out of the following four: * * NO_BUILTIN_TCAPS Do not include any builtin termcap entries (used only * with HAVE_TGETENT defined). * * (nothing) Machine specific termcap entries will be included. * This is default for win16 to save static data. * * SOME_BUILTIN_TCAPS Include most useful builtin termcap entries (used only * with NO_BUILTIN_TCAPS not defined). * This is the default. * * ALL_BUILTIN_TCAPS Include all builtin termcap entries * (used only with NO_BUILTIN_TCAPS not defined). */ #ifdef HAVE_TGETENT /* #define NO_BUILTIN_TCAPS */ #endif #if !defined(NO_BUILTIN_TCAPS) && !defined(FEAT_GUI_W16) # ifdef FEAT_BIG # define ALL_BUILTIN_TCAPS # else # define SOME_BUILTIN_TCAPS /* default */ # endif #endif /* * +lispindent lisp indenting (From Eric Fischer). * +cindent C code indenting (From Eric Fischer). * +smartindent smart C code indenting when the 'si' option is set. * * These two need to be defined when making prototypes. */ #if defined(FEAT_NORMAL) || defined(PROTO) # define FEAT_LISP #endif #if defined(FEAT_NORMAL) || defined(PROTO) # define FEAT_CINDENT #endif #ifdef FEAT_NORMAL # define FEAT_SMARTINDENT #endif /* * +comments 'comments' option. */ #ifdef FEAT_NORMAL # define FEAT_COMMENTS #endif /* * +cryptv Encryption (by Mohsin Ahmed <mosh@sasi.com>). */ #if defined(FEAT_NORMAL) && !defined(FEAT_CRYPT) || defined(PROTO) # define FEAT_CRYPT #endif /* * +mksession ":mksession" command. * Requires +windows and +vertsplit. */ #if defined(FEAT_NORMAL) && defined(FEAT_WINDOWS) && defined(FEAT_VERTSPLIT) # define FEAT_SESSION #endif /* * +multi_lang Multi language support. ":menutrans", ":language", etc. * +gettext Message translations (requires +multi_lang) * (only when "lang" archive unpacked) */ #ifdef FEAT_NORMAL # define FEAT_MULTI_LANG #endif #if defined(HAVE_GETTEXT) && defined(FEAT_MULTI_LANG) \ && (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) # define FEAT_GETTEXT #endif /* * +multi_byte Generic multi-byte character handling. Doesn't work * with 16 bit ints. Required for GTK+ 2. * * Disabled for EBCDIC: * Multibyte support doesn't work on z/OS Unix currently. */ #if (defined(FEAT_BIG) || defined(FEAT_GUI_GTK) || defined(FEAT_ARABIC)) \ && !defined(FEAT_MBYTE) && !defined(WIN16) \ && SIZEOF_INT >= 4 && !defined(EBCDIC) # define FEAT_MBYTE #endif /* Define this if you want to use 16 bit Unicode only, reduces memory used for * the screen structures. */ /* #define UNICODE16 */ /* * +multi_byte_ime Win32 IME input method. Requires +multi_byte. * Only for far-east Windows, so IME can be used to input * chars. Not tested much! */ #if defined(FEAT_GUI_W32) && !defined(FEAT_MBYTE_IME) /* #define FEAT_MBYTE_IME */ # endif #if defined(FEAT_MBYTE_IME) && !defined(FEAT_MBYTE) # define FEAT_MBYTE #endif #if defined(FEAT_MBYTE) && SIZEOF_INT < 4 && !defined(PROTO) Error: Can only handle multi-byte feature with 32 bit int or larger #endif /* Use iconv() when it's available. */ #if defined(FEAT_MBYTE) && ((defined(HAVE_ICONV_H) && defined(HAVE_ICONV)) \ || defined(DYNAMIC_ICONV)) # define USE_ICONV #endif /* * +xim X Input Method. For entering special languages like * chinese and Japanese. * +hangul_input Internal Hangul input method. Must be included * through configure: "--enable-hangulin" * Both are for Unix and VMS only. */ #ifndef FEAT_XIM /* #define FEAT_XIM */ #endif #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) # define USE_XIM 1 /* needed for GTK include files */ #endif #ifdef FEAT_HANGULIN # define HANGUL_DEFAULT_KEYBOARD 2 /* 2 or 3 bulsik keyboard */ # define ESC_CHG_TO_ENG_MODE /* if defined, when ESC pressed, * turn to english mode */ # if !defined(FEAT_XFONTSET) && defined(HAVE_X11) && !defined(FEAT_GUI_GTK) # define FEAT_XFONTSET /* Hangul input requires xfontset */ # endif # if defined(FEAT_XIM) && !defined(LINT) Error: You should select only ONE of XIM and HANGUL INPUT # endif #endif #if defined(FEAT_HANGULIN) || defined(FEAT_XIM) /* # define X_LOCALE */ /* for OS with incomplete locale support, like old linux versions. */ /* # define SLOW_XSERVER */ /* for extremely slow X server */ #endif /* * +xfontset X fontset support. For outputting wide characters. */ #ifndef FEAT_XFONTSET # if defined(FEAT_MBYTE) && defined(HAVE_X11) && !defined(FEAT_GUI_GTK) # define FEAT_XFONTSET # else /* # define FEAT_XFONTSET */ # endif #endif /* * +libcall libcall() function */ /* Using dlopen() also requires dlsym() to be available. */ #if defined(HAVE_DLOPEN) && defined(HAVE_DLSYM) # define USE_DLOPEN #endif #if defined(FEAT_EVAL) && (defined(WIN3264) || ((defined(UNIX) || defined(VMS)) \ && (defined(USE_DLOPEN) || defined(HAVE_SHL_LOAD)))) # define FEAT_LIBCALL #endif /* * +scrollbind synchronization of split windows */ #if defined(FEAT_NORMAL) && defined(FEAT_WINDOWS) # define FEAT_SCROLLBIND #endif /* * +cursorbind synchronization of split windows */ #if defined(FEAT_NORMAL) && defined(FEAT_WINDOWS) # define FEAT_CURSORBIND #endif /* * +menu ":menu" command */ #ifdef FEAT_NORMAL # define FEAT_MENU # ifdef FEAT_GUI_W32 # define FEAT_TEAROFF # endif #endif /* There are two ways to use XPM. */ #if (defined(HAVE_XM_XPMP_H) && defined(FEAT_GUI_MOTIF)) \ || defined(HAVE_X11_XPM_H) # define HAVE_XPM 1 #endif /* * +toolbar Include code for a toolbar (for the Win32 GUI, GTK * always has it). But only if menus are enabled. */ #if defined(FEAT_NORMAL) && defined(FEAT_MENU) \ && (defined(FEAT_GUI_GTK) \ || defined(FEAT_GUI_MSWIN) \ || ((defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)) \ && defined(HAVE_XPM)) \ || defined(FEAT_GUI_PHOTON)) # define FEAT_TOOLBAR #endif #if defined(FEAT_TOOLBAR) && !defined(FEAT_MENU) # define FEAT_MENU #endif /* * GUI tabline */ #if defined(FEAT_WINDOWS) && defined(FEAT_NORMAL) \ && (defined(FEAT_GUI_GTK) \ || (defined(FEAT_GUI_MOTIF) && defined(HAVE_XM_NOTEBOOK_H)) \ || defined(FEAT_GUI_MAC) \ || (defined(FEAT_GUI_MSWIN) && !defined(WIN16) \ && (!defined(_MSC_VER) || _MSC_VER > 1020))) # define FEAT_GUI_TABLINE #endif /* * +browse ":browse" command. * or just the ":browse" command modifier */ #if defined(FEAT_NORMAL) # define FEAT_BROWSE_CMD # if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) # define FEAT_BROWSE # endif #endif /* * +dialog_gui Use GUI dialog. * +dialog_con May use Console dialog. * When none of these defined there is no dialog support. */ #ifdef FEAT_NORMAL # if ((defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MOTIF)) \ && defined(HAVE_X11_XPM_H)) \ || defined(FEAT_GUI_GTK) \ || defined(FEAT_GUI_PHOTON) \ || defined(FEAT_GUI_MSWIN) \ || defined(FEAT_GUI_MAC) # define FEAT_CON_DIALOG # define FEAT_GUI_DIALOG # else # define FEAT_CON_DIALOG # endif #endif #if !defined(FEAT_GUI_DIALOG) && (defined(FEAT_GUI_MOTIF) \ || defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_GTK) \ || defined(FEAT_GUI_W32)) /* need a dialog to show error messages when starting from the desktop */ # define FEAT_GUI_DIALOG #endif #if defined(FEAT_GUI_DIALOG) && \ (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) \ || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MSWIN) \ || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)) # define FEAT_GUI_TEXTDIALOG #endif /* Mac specific thing: Codewarrior interface. */ #ifdef FEAT_GUI_MAC # define FEAT_CW_EDITOR #endif /* * Preferences: * ============ */ /* * +writebackup 'writebackup' is default on: * Use a backup file while overwriting a file. But it's * deleted again when 'backup' is not set. Changing this * is strongly discouraged: You can lose all your * changes when the computer crashes while writing the * file. * VMS note: It does work on VMS as well, but because of * version handling it does not have any purpose. * Overwrite will write to the new version. */ #ifndef VMS # define FEAT_WRITEBACKUP #endif /* * +xterm_save The t_ti and t_te entries for the builtin xterm will * be set to save the screen when starting Vim and * restoring it when exiting. */ /* #define FEAT_XTERM_SAVE */ /* * DEBUG Output a lot of debugging garbage. */ /* #define DEBUG */ /* * STARTUPTIME Time the startup process. Writes a file with * timestamps. */ #if defined(FEAT_NORMAL) \ && ((defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)) \ || defined(WIN3264)) # define STARTUPTIME 1 #endif /* * MEM_PROFILE Debugging of memory allocation and freeing. */ /* #define MEM_PROFILE */ /* * VIMRC_FILE Name of the .vimrc file in current dir. */ /* #define VIMRC_FILE ".vimrc" */ /* * EXRC_FILE Name of the .exrc file in current dir. */ /* #define EXRC_FILE ".exrc" */ /* * GVIMRC_FILE Name of the .gvimrc file in current dir. */ /* #define GVIMRC_FILE ".gvimrc" */ /* * SESSION_FILE Name of the default ":mksession" file. */ #define SESSION_FILE "Session.vim" /* * USR_VIMRC_FILE Name of the user .vimrc file. * USR_VIMRC_FILE2 Name of alternate user .vimrc file. * USR_VIMRC_FILE3 Name of alternate user .vimrc file. */ /* #define USR_VIMRC_FILE "~/foo/.vimrc" */ /* #define USR_VIMRC_FILE2 "~/bar/.vimrc" */ /* #define USR_VIMRC_FILE3 "$VIM/.vimrc" */ /* * EVIM_FILE Name of the evim.vim script file */ /* #define EVIM_FILE "$VIMRUNTIME/evim.vim" */ /* * USR_EXRC_FILE Name of the user .exrc file. * USR_EXRC_FILE2 Name of the alternate user .exrc file. */ /* #define USR_EXRC_FILE "~/foo/.exrc" */ /* #define USR_EXRC_FILE2 "~/bar/.exrc" */ /* * USR_GVIMRC_FILE Name of the user .gvimrc file. * USR_GVIMRC_FILE2 Name of the alternate user .gvimrc file. */ /* #define USR_GVIMRC_FILE "~/foo/.gvimrc" */ /* #define USR_GVIMRC_FILE2 "~/bar/.gvimrc" */ /* #define USR_GVIMRC_FILE3 "$VIM/.gvimrc" */ /* * SYS_VIMRC_FILE Name of the system-wide .vimrc file. */ /* #define SYS_VIMRC_FILE "/etc/vimrc" */ /* * SYS_GVIMRC_FILE Name of the system-wide .gvimrc file. */ /* #define SYS_GVIMRC_FILE "/etc/gvimrc" */ /* * DFLT_HELPFILE Name of the help file. */ /* # define DFLT_HELPFILE "$VIMRUNTIME/doc/help.txt.gz" */ /* * File names for: * FILETYPE_FILE switch on file type detection * FTPLUGIN_FILE switch on loading filetype plugin files * INDENT_FILE switch on loading indent files * FTOFF_FILE switch off file type detection * FTPLUGOF_FILE switch off loading settings files * INDOFF_FILE switch off loading indent files */ /* # define FILETYPE_FILE "filetype.vim" */ /* # define FTPLUGIN_FILE "ftplugin.vim" */ /* # define INDENT_FILE "indent.vim" */ /* # define FTOFF_FILE "ftoff.vim" */ /* # define FTPLUGOF_FILE "ftplugof.vim" */ /* # define INDOFF_FILE "indoff.vim" */ /* * SYS_MENU_FILE Name of the default menu.vim file. */ /* # define SYS_MENU_FILE "$VIMRUNTIME/menu.vim" */ /* * SYS_OPTWIN_FILE Name of the default optwin.vim file. */ #ifndef SYS_OPTWIN_FILE # define SYS_OPTWIN_FILE "$VIMRUNTIME/optwin.vim" #endif /* * SYNTAX_FNAME Name of a syntax file, where %s is the syntax name. */ /* #define SYNTAX_FNAME "/foo/%s.vim" */ /* * RUNTIME_DIRNAME Generic name for the directory of the runtime files. */ #ifndef RUNTIME_DIRNAME # define RUNTIME_DIRNAME "runtime" #endif /* * RUNTIME_GLOBAL Directory name for global Vim runtime directory. * Don't define this if the preprocessor can't handle * string concatenation. * Also set by "--with-global-runtime" configure argument. */ /* #define RUNTIME_GLOBAL "/etc/vim" */ /* * MODIFIED_BY Name of who modified Vim. Required when distributing * a modifed version of Vim. * Also from the "--with-modified-by" configure argument. */ /* #define MODIFIED_BY "John Doe" */ /* * Machine dependent: * ================== */ /* * +fork Unix only: fork() support (detected by configure) * +system Use system() instead of fork/exec for starting a * shell. Doesn't work for the GUI! */ /* #define USE_SYSTEM */ /* * +X11 Unix only. Include code for xterm title saving and X * clipboard. Only works if HAVE_X11 is also defined. */ #if (defined(FEAT_NORMAL) || defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)) # define WANT_X11 #endif /* * XSMP - X11 Session Management Protocol * It may be preferred to disable this if the GUI supports it (e.g., * GNOME/KDE) and implement save-yourself etc. through that, but it may also * be cleaner to have all SM-aware vims do the same thing (libSM does not * depend upon X11). * If your GUI wants to support SM itself, change this ifdef. * I'm assuming that any X11 implementation will cope with this for now. */ #if defined(HAVE_X11) && defined(WANT_X11) && defined(HAVE_X11_SM_SMLIB_H) # define USE_XSMP #endif #if defined(USE_XSMP_INTERACT) && !defined(USE_XSMP) # undef USE_XSMP_INTERACT #endif /* * +mouse_xterm Unix only: Include code for xterm mouse handling. * +mouse_dec idem, for Dec mouse handling. * +mouse_jsbterm idem, for Jsbterm mouse handling. * +mouse_netterm idem, for Netterm mouse handling. * (none) MS-DOS mouse support. * +mouse_gpm Unix only: Include code for Linux console mouse * handling. * +mouse_pterm PTerm mouse support for QNX * +mouse_sysmouse Unix only: Include code for FreeBSD and DragonFly * console mouse handling. * +mouse Any mouse support (any of the above enabled). */ /* OS/2 and Amiga console have no mouse support */ #if !defined(AMIGA) && !defined(OS2) # ifdef FEAT_NORMAL # define FEAT_MOUSE_XTERM # endif # ifdef FEAT_BIG # define FEAT_MOUSE_NET # endif # ifdef FEAT_BIG # define FEAT_MOUSE_DEC # endif # ifdef FEAT_BIG # define FEAT_MOUSE_URXVT # endif # if defined(FEAT_NORMAL) && (defined(MSDOS) || defined(WIN3264)) # define DOS_MOUSE # endif # if defined(FEAT_NORMAL) && defined(__QNX__) # define FEAT_MOUSE_PTERM # endif #endif #if defined(FEAT_NORMAL) && defined(HAVE_GPM) # define FEAT_MOUSE_GPM #endif #if defined(FEAT_NORMAL) && defined(HAVE_SYSMOUSE) # define FEAT_SYSMOUSE #endif /* urxvt is a small variation of mouse_xterm, and shares its code */ #if defined(FEAT_MOUSE_URXVT) && !defined(FEAT_MOUSE_XTERM) # define FEAT_MOUSE_XTERM #endif /* Define FEAT_MOUSE when any of the above is defined or FEAT_GUI. */ #if !defined(FEAT_MOUSE_TTY) \ && (defined(FEAT_MOUSE_XTERM) \ || defined(FEAT_MOUSE_NET) \ || defined(FEAT_MOUSE_DEC) \ || defined(DOS_MOUSE) \ || defined(FEAT_MOUSE_GPM) \ || defined(FEAT_MOUSE_JSB) \ || defined(FEAT_MOUSE_PTERM) \ || defined(FEAT_SYSMOUSE) \ || defined(FEAT_MOUSE_URXVT)) # define FEAT_MOUSE_TTY /* include non-GUI mouse support */ #endif #if !defined(FEAT_MOUSE) && (defined(FEAT_MOUSE_TTY) || defined(FEAT_GUI)) # define FEAT_MOUSE /* include generic mouse support */ #endif /* * +clipboard Clipboard support. Always used for the GUI. * +xterm_clipboard Unix only: Include code for handling the clipboard * in an xterm like in the GUI. */ #ifdef FEAT_GUI # ifndef FEAT_CLIPBOARD # define FEAT_CLIPBOARD # ifndef FEAT_VISUAL # define FEAT_VISUAL # endif # endif #endif #if defined(FEAT_NORMAL) && defined(FEAT_VISUAL) \ && (defined(UNIX) || defined(VMS)) \ && defined(WANT_X11) && defined(HAVE_X11) # define FEAT_XCLIPBOARD # ifndef FEAT_CLIPBOARD # define FEAT_CLIPBOARD # endif #endif /* * +dnd Drag'n'drop support. Always used for the GTK+ GUI. */ #if defined(FEAT_CLIPBOARD) && defined(FEAT_GUI_GTK) # define FEAT_DND #endif #if defined(FEAT_GUI_MSWIN) && defined(FEAT_SMALL) # define MSWIN_FIND_REPLACE /* include code for find/replace dialog */ # define MSWIN_FR_BUFSIZE 256 #endif #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MOTIF) \ || defined(MSWIN_FIND_REPLACE) # define FIND_REPLACE_DIALOG 1 #endif /* * +clientserver Remote control via the remote_send() function * and the --remote argument */ #if (defined(WIN32) || defined(FEAT_XCLIPBOARD)) && defined(FEAT_EVAL) # define FEAT_CLIENTSERVER #endif /* * +termresponse send t_RV to obtain terminal response. Used for xterm * to check if mouse dragging can be used and if term * codes can be obtained. */ #if (defined(FEAT_NORMAL) || defined(FEAT_MOUSE)) && defined(HAVE_TGETENT) # define FEAT_TERMRESPONSE #endif /* * cursor shape Adjust the shape of the cursor to the mode. * mouse shape Adjust the shape of the mouse pointer to the mode. */ #ifdef FEAT_NORMAL /* MS-DOS console and Win32 console can change cursor shape */ # if defined(MSDOS) || (defined(WIN3264) && !defined(FEAT_GUI_W32)) # define MCH_CURSOR_SHAPE # endif # if defined(FEAT_GUI_W32) || defined(FEAT_GUI_W16) || defined(FEAT_GUI_MOTIF) \ || defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_GTK) \ || defined(FEAT_GUI_PHOTON) # define FEAT_MOUSESHAPE # endif #endif /* GUI and some consoles can change the shape of the cursor. The code is also * needed for the 'mouseshape' and 'concealcursor' options. */ #if defined(FEAT_GUI) \ || defined(MCH_CURSOR_SHAPE) \ || defined(FEAT_MOUSESHAPE) \ || defined(FEAT_CONCEAL) \ || (defined(UNIX) && defined(FEAT_NORMAL)) # define CURSOR_SHAPE #endif #if defined(FEAT_MZSCHEME) && (defined(FEAT_GUI_W32) || defined(FEAT_GUI_GTK) \ || defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) \ || defined(FEAT_GUI_MAC)) # define MZSCHEME_GUI_THREADS #endif /* * +ARP Amiga only. Use arp.library, DOS 2.0 is not required. */ #if !defined(NO_ARP) && !defined(__amigaos4__) # define FEAT_ARP #endif /* * +GUI_Athena To compile Vim with or without the GUI (gvim) you have * +GUI_Motif to edit the Makefile. */ /* * +ole Win32 OLE automation: Use Makefile.ovc. */ /* * These features can only be included by using a configure argument. See the * Makefile for a line to uncomment. * +lua Lua interface: "--enable-luainterp" * +mzscheme MzScheme interface: "--enable-mzscheme" * +perl Perl interface: "--enable-perlinterp" * +python Python interface: "--enable-pythoninterp" * +tcl TCL interface: "--enable-tclinterp" * +sniff Sniff interface: "--enable-sniff" * +sun_workshop Sun Workshop integration * +netbeans_intg Netbeans integration */ /* * These features are automatically detected: * +terminfo * +tgetent */ /* * The Sun Workshop features currently only work with Motif. */ #if !defined(FEAT_GUI_MOTIF) && defined(FEAT_SUN_WORKSHOP) # undef FEAT_SUN_WORKSHOP #endif /* * The Netbeans feature requires +listcmds and +eval. */ #if (!defined(FEAT_LISTCMDS) || !defined(FEAT_EVAL)) \ && defined(FEAT_NETBEANS_INTG) # undef FEAT_NETBEANS_INTG #endif /* * +signs Allow signs to be displayed to the left of text lines. * Adds the ":sign" command. */ #if defined(FEAT_BIG) || defined(FEAT_SUN_WORKSHOP) \ || defined(FEAT_NETBEANS_INTG) # define FEAT_SIGNS # if ((defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)) \ && defined(HAVE_X11_XPM_H)) \ || defined(FEAT_GUI_GTK) \ || (defined(WIN32) && defined(FEAT_GUI)) # define FEAT_SIGN_ICONS # endif #endif /* * +balloon_eval Allow balloon expression evaluation. Used with a * debugger and for tooltips. * Only for GUIs where it was implemented. */ #if (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) \ || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32)) \ && ( ((defined(FEAT_TOOLBAR) || defined(FEAT_GUI_TABLINE)) \ && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_W32)) \ || defined(FEAT_SUN_WORKSHOP) \ || defined(FEAT_NETBEANS_INTG) || defined(FEAT_EVAL)) # define FEAT_BEVAL # if !defined(FEAT_XFONTSET) && !defined(FEAT_GUI_GTK) \ && !defined(FEAT_GUI_W32) # define FEAT_XFONTSET # endif #endif #if defined(FEAT_BEVAL) && (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)) # define FEAT_BEVAL_TIP /* balloon eval used for toolbar tooltip */ #endif /* both Motif and Athena are X11 and share some code */ #if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) # define FEAT_GUI_X11 #endif #if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) /* * The following features are (currently) only used by Sun Visual WorkShop 6 * and NetBeans. These features could be used with other integrations with * debuggers so I've used separate feature defines. */ # if !defined(FEAT_MENU) # define FEAT_MENU # endif #endif #if defined(FEAT_SUN_WORKSHOP) /* * Use an alternative method of X input for a secondary * command input. */ # define ALT_X_INPUT /* * +footer Motif only: Add a message area at the bottom of the * main window area. */ # define FEAT_FOOTER #endif /* * +autochdir 'autochdir' option. */ #if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \ || defined(FEAT_BIG) # define FEAT_AUTOCHDIR #endif /* * +persistent_undo 'undofile', 'undodir' options, :wundo and :rundo, and * implementation. */ #ifdef FEAT_NORMAL # define FEAT_PERSISTENT_UNDO #endif /* * +filterpipe */ #if (defined(UNIX) && !defined(USE_SYSTEM)) \ || (defined(WIN3264) && defined(FEAT_GUI_W32)) # define FEAT_FILTERPIPE #endif
zyz2011-vim
src/feature.h
C
gpl2
33,020
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * option.h: definition of global variables for settable options */ /* * Default values for 'errorformat'. * The "%f|%l| %m" one is used for when the contents of the quickfix window is * written to a file. */ #ifdef AMIGA # define DFLT_EFM "%f>%l:%c:%t:%n:%m,%f:%l: %t%*\\D%n: %m,%f %l %t%*\\D%n: %m,%*[^\"]\"%f\"%*\\D%l: %m,%f:%l:%m,%f|%l| %m" #else # if defined(MSDOS) || defined(WIN3264) # define DFLT_EFM "%f(%l) : %t%*\\D%n: %m,%*[^\"]\"%f\"%*\\D%l: %m,%f(%l) : %m,%*[^ ] %f %l: %m,%f:%l:%c:%m,%f(%l):%m,%f:%l:%m,%f|%l| %m" # else # if defined(__EMX__) /* put most common here (i.e. gcc format) at front */ # define DFLT_EFM "%f:%l:%c:%m,%f(%l):%m,%f:%l:%m,%*[^\"]\"%f\"%*\\D%l: %m,\"%f\"%*\\D%l: %m,%f(%l:%c) : %m,%f|%l| %m" # else # if defined(__QNX__) # define DFLT_EFM "%f(%l):%*[^WE]%t%*\\D%n:%m,%f|%l| %m" # else # ifdef VMS # define DFLT_EFM "%A%p^,%C%%CC-%t-%m,%Cat line number %l in file %f,%f|%l| %m" # else /* Unix, probably */ # ifdef EBCDIC #define DFLT_EFM "%*[^ ] %*[^ ] %f:%l%*[ ]%m,%*[^\"]\"%f\"%*\\D%l: %m,\"%f\"%*\\D%l: %m,%f:%l:%c:%m,%f(%l):%m,%f:%l:%m,\"%f\"\\, line %l%*\\D%c%*[^ ] %m,%D%*\\a[%*\\d]: Entering directory `%f',%X%*\\a[%*\\d]: Leaving directory `%f',%DMaking %*\\a in %f,%f|%l| %m" # else #define DFLT_EFM "%*[^\"]\"%f\"%*\\D%l: %m,\"%f\"%*\\D%l: %m,%-G%f:%l: (Each undeclared identifier is reported only once,%-G%f:%l: for each function it appears in.),%-GIn file included from %f:%l:%c:,%-GIn file included from %f:%l:%c\\,,%-GIn file included from %f:%l:%c,%-GIn file included from %f:%l,%-G%*[ ]from %f:%l:%c,%-G%*[ ]from %f:%l:,%-G%*[ ]from %f:%l\\,,%-G%*[ ]from %f:%l,%f:%l:%c:%m,%f(%l):%m,%f:%l:%m,\"%f\"\\, line %l%*\\D%c%*[^ ] %m,%D%*\\a[%*\\d]: Entering directory `%f',%X%*\\a[%*\\d]: Leaving directory `%f',%D%*\\a: Entering directory `%f',%X%*\\a: Leaving directory `%f',%DMaking %*\\a in %f,%f|%l| %m" # endif # endif # endif # endif # endif #endif #define DFLT_GREPFORMAT "%f:%l:%m,%f:%l%m,%f %l%m" /* default values for b_p_ff 'fileformat' and p_ffs 'fileformats' */ #define FF_DOS "dos" #define FF_MAC "mac" #define FF_UNIX "unix" #ifdef USE_CRNL # define DFLT_FF "dos" # define DFLT_FFS_VIM "dos,unix" # define DFLT_FFS_VI "dos,unix" /* also autodetect in compatible mode */ # define DFLT_TEXTAUTO TRUE #else # ifdef USE_CR # define DFLT_FF "mac" # define DFLT_FFS_VIM "mac,unix,dos" # define DFLT_FFS_VI "mac,unix,dos" # define DFLT_TEXTAUTO TRUE # else # define DFLT_FF "unix" # define DFLT_FFS_VIM "unix,dos" # ifdef __CYGWIN__ # define DFLT_FFS_VI "unix,dos" /* Cygwin always needs file detection */ # define DFLT_TEXTAUTO TRUE # else # define DFLT_FFS_VI "" # define DFLT_TEXTAUTO FALSE # endif # endif #endif #ifdef FEAT_MBYTE /* Possible values for 'encoding' */ # define ENC_UCSBOM "ucs-bom" /* check for BOM at start of file */ /* default value for 'encoding' */ # define ENC_DFLT "latin1" #endif /* end-of-line style */ #define EOL_UNKNOWN -1 /* not defined yet */ #define EOL_UNIX 0 /* NL */ #define EOL_DOS 1 /* CR NL */ #define EOL_MAC 2 /* CR */ /* Formatting options for p_fo 'formatoptions' */ #define FO_WRAP 't' #define FO_WRAP_COMS 'c' #define FO_RET_COMS 'r' #define FO_OPEN_COMS 'o' #define FO_Q_COMS 'q' #define FO_Q_NUMBER 'n' #define FO_Q_SECOND '2' #define FO_INS_VI 'v' #define FO_INS_LONG 'l' #define FO_INS_BLANK 'b' #define FO_MBYTE_BREAK 'm' /* break before/after multi-byte char */ #define FO_MBYTE_JOIN 'M' /* no space before/after multi-byte char */ #define FO_MBYTE_JOIN2 'B' /* no space between multi-byte chars */ #define FO_ONE_LETTER '1' #define FO_WHITE_PAR 'w' /* trailing white space continues paragr. */ #define FO_AUTO 'a' /* automatic formatting */ #define FO_REMOVE_COMS 'j' /* remove comment leaders when joining lines */ #define DFLT_FO_VI "vt" #define DFLT_FO_VIM "tcq" #define FO_ALL "tcroq2vlb1mMBn,awj" /* for do_set() */ /* characters for the p_cpo option: */ #define CPO_ALTREAD 'a' /* ":read" sets alternate file name */ #define CPO_ALTWRITE 'A' /* ":write" sets alternate file name */ #define CPO_BAR 'b' /* "\|" ends a mapping */ #define CPO_BSLASH 'B' /* backslash in mapping is not special */ #define CPO_SEARCH 'c' #define CPO_CONCAT 'C' /* Don't concatenate sourced lines */ #define CPO_DOTTAG 'd' /* "./tags" in 'tags' is in current dir */ #define CPO_DIGRAPH 'D' /* No digraph after "r", "f", etc. */ #define CPO_EXECBUF 'e' #define CPO_EMPTYREGION 'E' /* operating on empty region is an error */ #define CPO_FNAMER 'f' /* set file name for ":r file" */ #define CPO_FNAMEW 'F' /* set file name for ":w file" */ #define CPO_GOTO1 'g' /* goto line 1 for ":edit" */ #define CPO_INSEND 'H' /* "I" inserts before last blank in line */ #define CPO_INTMOD 'i' /* interrupt a read makes buffer modified */ #define CPO_INDENT 'I' /* remove auto-indent more often */ #define CPO_JOINSP 'j' /* only use two spaces for join after '.' */ #define CPO_ENDOFSENT 'J' /* need two spaces to detect end of sentence */ #define CPO_KEYCODE 'k' /* don't recognize raw key code in mappings */ #define CPO_KOFFSET 'K' /* don't wait for key code in mappings */ #define CPO_LITERAL 'l' /* take char after backslash in [] literal */ #define CPO_LISTWM 'L' /* 'list' changes wrapmargin */ #define CPO_SHOWMATCH 'm' #define CPO_MATCHBSL 'M' /* "%" ignores use of backslashes */ #define CPO_NUMCOL 'n' /* 'number' column also used for text */ #define CPO_LINEOFF 'o' #define CPO_OVERNEW 'O' /* silently overwrite new file */ #define CPO_LISP 'p' /* 'lisp' indenting */ #define CPO_FNAMEAPP 'P' /* set file name for ":w >>file" */ #define CPO_JOINCOL 'q' /* with "3J" use column after first join */ #define CPO_REDO 'r' #define CPO_REMMARK 'R' /* remove marks when filtering */ #define CPO_BUFOPT 's' #define CPO_BUFOPTGLOB 'S' #define CPO_TAGPAT 't' #define CPO_UNDO 'u' /* "u" undoes itself */ #define CPO_BACKSPACE 'v' /* "v" keep deleted text */ #define CPO_CW 'w' /* "cw" only changes one blank */ #define CPO_FWRITE 'W' /* "w!" doesn't overwrite readonly files */ #define CPO_ESC 'x' #define CPO_REPLCNT 'X' /* "R" with a count only deletes chars once */ #define CPO_YANK 'y' #define CPO_KEEPRO 'Z' /* don't reset 'readonly' on ":w!" */ #define CPO_DOLLAR '$' #define CPO_FILTER '!' #define CPO_MATCH '%' #define CPO_STAR '*' /* ":*" means ":@" */ #define CPO_PLUS '+' /* ":write file" resets 'modified' */ #define CPO_MINUS '-' /* "9-" fails at and before line 9 */ #define CPO_SPECI '<' /* don't recognize <> in mappings */ #define CPO_REGAPPEND '>' /* insert NL when appending to a register */ /* POSIX flags */ #define CPO_HASH '#' /* "D", "o" and "O" do not use a count */ #define CPO_PARA '{' /* "{" is also a paragraph boundary */ #define CPO_TSIZE '|' /* $LINES and $COLUMNS overrule term size */ #define CPO_PRESERVE '&' /* keep swap file after :preserve */ #define CPO_SUBPERCENT '/' /* % in :s string uses previous one */ #define CPO_BACKSL '\\' /* \ is not special in [] */ #define CPO_CHDIR '.' /* don't chdir if buffer is modified */ #define CPO_SCOLON ';' /* using "," and ";" will skip over char if * cursor would not move */ /* default values for Vim, Vi and POSIX */ #define CPO_VIM "aABceFs" #define CPO_VI "aAbBcCdDeEfFgHiIjJkKlLmMnoOpPqrRsStuvwWxXyZ$!%*-+<>;" #define CPO_ALL "aAbBcCdDeEfFgHiIjJkKlLmMnoOpPqrRsStuvwWxXyZ$!%*-+<>#{|&/\\.;" /* characters for p_ww option: */ #define WW_ALL "bshl<>[],~" /* characters for p_mouse option: */ #define MOUSE_NORMAL 'n' /* use mouse in Normal mode */ #define MOUSE_VISUAL 'v' /* use mouse in Visual/Select mode */ #define MOUSE_INSERT 'i' /* use mouse in Insert mode */ #define MOUSE_COMMAND 'c' /* use mouse in Command-line mode */ #define MOUSE_HELP 'h' /* use mouse in help buffers */ #define MOUSE_RETURN 'r' /* use mouse for hit-return message */ #define MOUSE_A "nvich" /* used for 'a' flag */ #define MOUSE_ALL "anvichr" /* all possible characters */ #define MOUSE_NONE ' ' /* don't use Visual selection */ #define MOUSE_NONEF 'x' /* forced modeless selection */ #define COCU_ALL "nvic" /* flags for 'concealcursor' */ /* characters for p_shm option: */ #define SHM_RO 'r' /* readonly */ #define SHM_MOD 'm' /* modified */ #define SHM_FILE 'f' /* (file 1 of 2) */ #define SHM_LAST 'i' /* last line incomplete */ #define SHM_TEXT 'x' /* tx instead of textmode */ #define SHM_LINES 'l' /* "L" instead of "lines" */ #define SHM_NEW 'n' /* "[New]" instead of "[New file]" */ #define SHM_WRI 'w' /* "[w]" instead of "written" */ #define SHM_A "rmfixlnw" /* represented by 'a' flag */ #define SHM_WRITE 'W' /* don't use "written" at all */ #define SHM_TRUNC 't' /* trunctate file messages */ #define SHM_TRUNCALL 'T' /* trunctate all messages */ #define SHM_OVER 'o' /* overwrite file messages */ #define SHM_OVERALL 'O' /* overwrite more messages */ #define SHM_SEARCH 's' /* no search hit bottom messages */ #define SHM_ATTENTION 'A' /* no ATTENTION messages */ #define SHM_INTRO 'I' /* intro messages */ #define SHM_ALL "rmfixlnwaWtToOsAI" /* all possible flags for 'shm' */ /* characters for p_go: */ #define GO_ASEL 'a' /* autoselect */ #define GO_ASELML 'A' /* autoselect modeless selection */ #define GO_BOT 'b' /* use bottom scrollbar */ #define GO_CONDIALOG 'c' /* use console dialog */ #define GO_TABLINE 'e' /* may show tabline */ #define GO_FORG 'f' /* start GUI in foreground */ #define GO_GREY 'g' /* use grey menu items */ #define GO_HORSCROLL 'h' /* flexible horizontal scrolling */ #define GO_ICON 'i' /* use Vim icon */ #define GO_LEFT 'l' /* use left scrollbar */ #define GO_VLEFT 'L' /* left scrollbar with vert split */ #define GO_MENUS 'm' /* use menu bar */ #define GO_NOSYSMENU 'M' /* don't source system menu */ #define GO_POINTER 'p' /* pointer enter/leave callbacks */ #define GO_RIGHT 'r' /* use right scrollbar */ #define GO_VRIGHT 'R' /* right scrollbar with vert split */ #define GO_TEAROFF 't' /* add tear-off menu items */ #define GO_TOOLBAR 'T' /* add toolbar */ #define GO_FOOTER 'F' /* add footer */ #define GO_VERTICAL 'v' /* arrange dialog buttons vertically */ #define GO_ALL "aAbcefFghilmMprtTv" /* all possible flags for 'go' */ /* flags for 'comments' option */ #define COM_NEST 'n' /* comments strings nest */ #define COM_BLANK 'b' /* needs blank after string */ #define COM_START 's' /* start of comment */ #define COM_MIDDLE 'm' /* middle of comment */ #define COM_END 'e' /* end of comment */ #define COM_AUTO_END 'x' /* last char of end closes comment */ #define COM_FIRST 'f' /* first line comment only */ #define COM_LEFT 'l' /* left adjusted */ #define COM_RIGHT 'r' /* right adjusted */ #define COM_NOBACK 'O' /* don't use for "O" command */ #define COM_ALL "nbsmexflrO" /* all flags for 'comments' option */ #define COM_MAX_LEN 50 /* maximum length of a part */ /* flags for 'statusline' option */ #define STL_FILEPATH 'f' /* path of file in buffer */ #define STL_FULLPATH 'F' /* full path of file in buffer */ #define STL_FILENAME 't' /* last part (tail) of file path */ #define STL_COLUMN 'c' /* column og cursor*/ #define STL_VIRTCOL 'v' /* virtual column */ #define STL_VIRTCOL_ALT 'V' /* - with 'if different' display */ #define STL_LINE 'l' /* line number of cursor */ #define STL_NUMLINES 'L' /* number of lines in buffer */ #define STL_BUFNO 'n' /* current buffer number */ #define STL_KEYMAP 'k' /* 'keymap' when active */ #define STL_OFFSET 'o' /* offset of character under cursor*/ #define STL_OFFSET_X 'O' /* - in hexadecimal */ #define STL_BYTEVAL 'b' /* byte value of character */ #define STL_BYTEVAL_X 'B' /* - in hexadecimal */ #define STL_ROFLAG 'r' /* readonly flag */ #define STL_ROFLAG_ALT 'R' /* - other display */ #define STL_HELPFLAG 'h' /* window is showing a help file */ #define STL_HELPFLAG_ALT 'H' /* - other display */ #define STL_FILETYPE 'y' /* 'filetype' */ #define STL_FILETYPE_ALT 'Y' /* - other display */ #define STL_PREVIEWFLAG 'w' /* window is showing the preview buf */ #define STL_PREVIEWFLAG_ALT 'W' /* - other display */ #define STL_MODIFIED 'm' /* modified flag */ #define STL_MODIFIED_ALT 'M' /* - other display */ #define STL_QUICKFIX 'q' /* quickfix window description */ #define STL_PERCENTAGE 'p' /* percentage through file */ #define STL_ALTPERCENT 'P' /* percentage as TOP BOT ALL or NN% */ #define STL_ARGLISTSTAT 'a' /* argument list status as (x of y) */ #define STL_PAGENUM 'N' /* page number (when printing)*/ #define STL_VIM_EXPR '{' /* start of expression to substitute */ #define STL_MIDDLEMARK '=' /* separation between left and right */ #define STL_TRUNCMARK '<' /* truncation mark if line is too long*/ #define STL_USER_HL '*' /* highlight from (User)1..9 or 0 */ #define STL_HIGHLIGHT '#' /* highlight name */ #define STL_TABPAGENR 'T' /* tab page label nr */ #define STL_TABCLOSENR 'X' /* tab page close nr */ #define STL_ALL ((char_u *) "fFtcvVlLknoObBrRhHmYyWwMqpPaN{#") /* flags used for parsed 'wildmode' */ #define WIM_FULL 1 #define WIM_LONGEST 2 #define WIM_LIST 4 /* arguments for can_bs() */ #define BS_INDENT 'i' /* "Indent" */ #define BS_EOL 'o' /* "eOl" */ #define BS_START 's' /* "Start" */ #define LISPWORD_VALUE "defun,define,defmacro,set!,lambda,if,case,let,flet,let*,letrec,do,do*,define-syntax,let-syntax,letrec-syntax,destructuring-bind,defpackage,defparameter,defstruct,deftype,defvar,do-all-symbols,do-external-symbols,do-symbols,dolist,dotimes,ecase,etypecase,eval-when,labels,macrolet,multiple-value-bind,multiple-value-call,multiple-value-prog1,multiple-value-setq,prog1,progv,typecase,unless,unwind-protect,when,with-input-from-string,with-open-file,with-open-stream,with-output-to-string,with-package-iterator,define-condition,handler-bind,handler-case,restart-bind,restart-case,with-simple-restart,store-value,use-value,muffle-warning,abort,continue,with-slots,with-slots*,with-accessors,with-accessors*,defclass,defmethod,print-unreadable-object" /* * The following are actual variables for the options */ #ifdef FEAT_RIGHTLEFT EXTERN long p_aleph; /* 'aleph' */ #endif #ifdef FEAT_AUTOCHDIR EXTERN int p_acd; /* 'autochdir' */ #endif #ifdef FEAT_MBYTE EXTERN char_u *p_ambw; /* 'ambiwidth' */ #endif #if defined(FEAT_GUI) && defined(MACOS_X) EXTERN int *p_antialias; /* 'antialias' */ #endif EXTERN int p_ar; /* 'autoread' */ EXTERN int p_aw; /* 'autowrite' */ EXTERN int p_awa; /* 'autowriteall' */ EXTERN char_u *p_bs; /* 'backspace' */ EXTERN char_u *p_bg; /* 'background' */ EXTERN int p_bk; /* 'backup' */ EXTERN char_u *p_bkc; /* 'backupcopy' */ EXTERN unsigned bkc_flags; #ifdef IN_OPTION_C static char *(p_bkc_values[]) = {"yes", "auto", "no", "breaksymlink", "breakhardlink", NULL}; #endif # define BKC_YES 0x001 # define BKC_AUTO 0x002 # define BKC_NO 0x004 # define BKC_BREAKSYMLINK 0x008 # define BKC_BREAKHARDLINK 0x010 EXTERN char_u *p_bdir; /* 'backupdir' */ EXTERN char_u *p_bex; /* 'backupext' */ #ifdef FEAT_WILDIGN EXTERN char_u *p_bsk; /* 'backupskip' */ #endif #ifdef FEAT_CRYPT EXTERN char_u *p_cm; /* 'cryptmethod' */ #endif #ifdef FEAT_BEVAL EXTERN long p_bdlay; /* 'balloondelay' */ EXTERN int p_beval; /* 'ballooneval' */ # ifdef FEAT_EVAL EXTERN char_u *p_bexpr; # endif #endif #ifdef FEAT_BROWSE EXTERN char_u *p_bsdir; /* 'browsedir' */ #endif #ifdef MSDOS EXTERN int p_biosk; /* 'bioskey' */ EXTERN int p_consk; /* 'conskey' */ #endif #ifdef FEAT_LINEBREAK EXTERN char_u *p_breakat; /* 'breakat' */ #endif #ifdef FEAT_MBYTE EXTERN char_u *p_cmp; /* 'casemap' */ EXTERN unsigned cmp_flags; # ifdef IN_OPTION_C static char *(p_cmp_values[]) = {"internal", "keepascii", NULL}; # endif # define CMP_INTERNAL 0x001 # define CMP_KEEPASCII 0x002 #endif #ifdef FEAT_MBYTE EXTERN char_u *p_enc; /* 'encoding' */ EXTERN int p_deco; /* 'delcombine' */ # ifdef FEAT_EVAL EXTERN char_u *p_ccv; /* 'charconvert' */ # endif #endif #ifdef FEAT_CMDWIN EXTERN char_u *p_cedit; /* 'cedit' */ EXTERN long p_cwh; /* 'cmdwinheight' */ #endif #ifdef FEAT_CLIPBOARD EXTERN char_u *p_cb; /* 'clipboard' */ #endif EXTERN long p_ch; /* 'cmdheight' */ #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) EXTERN int p_confirm; /* 'confirm' */ #endif EXTERN int p_cp; /* 'compatible' */ #ifdef FEAT_INS_EXPAND EXTERN char_u *p_cot; /* 'completeopt' */ EXTERN long p_ph; /* 'pumheight' */ #endif EXTERN char_u *p_cpo; /* 'cpoptions' */ #ifdef FEAT_CSCOPE EXTERN char_u *p_csprg; /* 'cscopeprg' */ EXTERN int p_csre; /* 'cscoperelative' */ # ifdef FEAT_QUICKFIX EXTERN char_u *p_csqf; /* 'cscopequickfix' */ # define CSQF_CMDS "sgdctefi" # define CSQF_FLAGS "+-0" # endif EXTERN int p_cst; /* 'cscopetag' */ EXTERN long p_csto; /* 'cscopetagorder' */ EXTERN long p_cspc; /* 'cscopepathcomp' */ EXTERN int p_csverbose; /* 'cscopeverbose' */ #endif EXTERN char_u *p_debug; /* 'debug' */ #ifdef FEAT_FIND_ID EXTERN char_u *p_def; /* 'define' */ EXTERN char_u *p_inc; #endif #ifdef FEAT_DIFF EXTERN char_u *p_dip; /* 'diffopt' */ # ifdef FEAT_EVAL EXTERN char_u *p_dex; /* 'diffexpr' */ # endif #endif #ifdef FEAT_INS_EXPAND EXTERN char_u *p_dict; /* 'dictionary' */ #endif #ifdef FEAT_DIGRAPHS EXTERN int p_dg; /* 'digraph' */ #endif EXTERN char_u *p_dir; /* 'directory' */ EXTERN char_u *p_dy; /* 'display' */ EXTERN unsigned dy_flags; #ifdef IN_OPTION_C static char *(p_dy_values[]) = {"lastline", "uhex", NULL}; #endif #define DY_LASTLINE 0x001 #define DY_UHEX 0x002 EXTERN int p_ed; /* 'edcompatible' */ #ifdef FEAT_VERTSPLIT EXTERN char_u *p_ead; /* 'eadirection' */ #endif EXTERN int p_ea; /* 'equalalways' */ EXTERN char_u *p_ep; /* 'equalprg' */ EXTERN int p_eb; /* 'errorbells' */ #ifdef FEAT_QUICKFIX EXTERN char_u *p_ef; /* 'errorfile' */ EXTERN char_u *p_efm; /* 'errorformat' */ EXTERN char_u *p_gefm; /* 'grepformat' */ EXTERN char_u *p_gp; /* 'grepprg' */ #endif #ifdef FEAT_AUTOCMD EXTERN char_u *p_ei; /* 'eventignore' */ #endif EXTERN int p_ek; /* 'esckeys' */ EXTERN int p_exrc; /* 'exrc' */ #ifdef FEAT_MBYTE EXTERN char_u *p_fencs; /* 'fileencodings' */ #endif EXTERN char_u *p_ffs; /* 'fileformats' */ #ifdef FEAT_FOLDING EXTERN char_u *p_fcl; /* 'foldclose' */ EXTERN long p_fdls; /* 'foldlevelstart' */ EXTERN char_u *p_fdo; /* 'foldopen' */ EXTERN unsigned fdo_flags; # ifdef IN_OPTION_C static char *(p_fdo_values[]) = {"all", "block", "hor", "mark", "percent", "quickfix", "search", "tag", "insert", "undo", "jump", NULL}; # endif # define FDO_ALL 0x001 # define FDO_BLOCK 0x002 # define FDO_HOR 0x004 # define FDO_MARK 0x008 # define FDO_PERCENT 0x010 # define FDO_QUICKFIX 0x020 # define FDO_SEARCH 0x040 # define FDO_TAG 0x080 # define FDO_INSERT 0x100 # define FDO_UNDO 0x200 # define FDO_JUMP 0x400 #endif EXTERN char_u *p_fp; /* 'formatprg' */ #ifdef HAVE_FSYNC EXTERN int p_fs; /* 'fsync' */ #endif EXTERN int p_gd; /* 'gdefault' */ #ifdef FEAT_PRINTER EXTERN char_u *p_pdev; /* 'printdevice' */ # ifdef FEAT_POSTSCRIPT EXTERN char_u *p_penc; /* 'printencoding' */ EXTERN char_u *p_pexpr; /* 'printexpr' */ # ifdef FEAT_MBYTE EXTERN char_u *p_pmfn; /* 'printmbfont' */ EXTERN char_u *p_pmcs; /* 'printmbcharset' */ # endif # endif EXTERN char_u *p_pfn; /* 'printfont' */ EXTERN char_u *p_popt; /* 'printoptions' */ EXTERN char_u *p_header; /* 'printheader' */ #endif EXTERN int p_prompt; /* 'prompt' */ #ifdef FEAT_GUI EXTERN char_u *p_guifont; /* 'guifont' */ # ifdef FEAT_XFONTSET EXTERN char_u *p_guifontset; /* 'guifontset' */ # endif # ifdef FEAT_MBYTE EXTERN char_u *p_guifontwide; /* 'guifontwide' */ # endif EXTERN int p_guipty; /* 'guipty' */ #endif #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11) EXTERN long p_ghr; /* 'guiheadroom' */ #endif #ifdef CURSOR_SHAPE EXTERN char_u *p_guicursor; /* 'guicursor' */ #endif #ifdef FEAT_MOUSESHAPE EXTERN char_u *p_mouseshape; /* 'mouseshape' */ #endif #if defined(FEAT_GUI) EXTERN char_u *p_go; /* 'guioptions' */ #endif #if defined(FEAT_GUI_TABLINE) EXTERN char_u *p_gtl; /* 'guitablabel' */ EXTERN char_u *p_gtt; /* 'guitabtooltip' */ #endif EXTERN char_u *p_hf; /* 'helpfile' */ #ifdef FEAT_WINDOWS EXTERN long p_hh; /* 'helpheight' */ #endif #ifdef FEAT_MULTI_LANG EXTERN char_u *p_hlg; /* 'helplang' */ #endif EXTERN int p_hid; /* 'hidden' */ /* Use P_HID to check if a buffer is to be hidden when it is no longer * visible in a window. */ #ifndef FEAT_QUICKFIX # define P_HID(dummy) (p_hid || cmdmod.hide) #else # define P_HID(buf) (buf_hide(buf)) #endif EXTERN char_u *p_hl; /* 'highlight' */ EXTERN int p_hls; /* 'hlsearch' */ EXTERN long p_hi; /* 'history' */ #ifdef FEAT_RIGHTLEFT EXTERN int p_hkmap; /* 'hkmap' */ EXTERN int p_hkmapp; /* 'hkmapp' */ # ifdef FEAT_FKMAP EXTERN int p_fkmap; /* 'fkmap' */ EXTERN int p_altkeymap; /* 'altkeymap' */ # endif # ifdef FEAT_ARABIC EXTERN int p_arshape; /* 'arabicshape' */ # endif #endif #ifdef FEAT_TITLE EXTERN int p_icon; /* 'icon' */ EXTERN char_u *p_iconstring; /* 'iconstring' */ #endif EXTERN int p_ic; /* 'ignorecase' */ #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) EXTERN char_u *p_imak; /* 'imactivatekey' */ #endif #ifdef USE_IM_CONTROL EXTERN int p_imcmdline; /* 'imcmdline' */ EXTERN int p_imdisable; /* 'imdisable' */ #endif EXTERN int p_is; /* 'incsearch' */ EXTERN int p_im; /* 'insertmode' */ EXTERN char_u *p_isf; /* 'isfname' */ EXTERN char_u *p_isi; /* 'isident' */ EXTERN char_u *p_isp; /* 'isprint' */ EXTERN int p_js; /* 'joinspaces' */ EXTERN char_u *p_kp; /* 'keywordprg' */ #ifdef FEAT_VISUAL EXTERN char_u *p_km; /* 'keymodel' */ #endif #ifdef FEAT_LANGMAP EXTERN char_u *p_langmap; /* 'langmap'*/ #endif #if defined(FEAT_MENU) && defined(FEAT_MULTI_LANG) EXTERN char_u *p_lm; /* 'langmenu' */ #endif #ifdef FEAT_GUI EXTERN long p_linespace; /* 'linespace' */ #endif #ifdef FEAT_LISP EXTERN char_u *p_lispwords; /* 'lispwords' */ #endif #ifdef FEAT_WINDOWS EXTERN long p_ls; /* 'laststatus' */ EXTERN long p_stal; /* 'showtabline' */ #endif EXTERN char_u *p_lcs; /* 'listchars' */ EXTERN int p_lz; /* 'lazyredraw' */ EXTERN int p_lpl; /* 'loadplugins' */ #ifdef FEAT_GUI_MAC EXTERN int p_macatsui; /* 'macatsui' */ #endif EXTERN int p_magic; /* 'magic' */ #ifdef FEAT_QUICKFIX EXTERN char_u *p_mef; /* 'makeef' */ EXTERN char_u *p_mp; /* 'makeprg' */ #endif #ifdef FEAT_SYN_HL EXTERN char_u *p_cc; /* 'colorcolumn' */ EXTERN int p_cc_cols[256]; /* array for 'colorcolumn' columns */ #endif EXTERN long p_mat; /* 'matchtime' */ #ifdef FEAT_MBYTE EXTERN long p_mco; /* 'maxcombine' */ #endif #ifdef FEAT_EVAL EXTERN long p_mfd; /* 'maxfuncdepth' */ #endif EXTERN long p_mmd; /* 'maxmapdepth' */ EXTERN long p_mm; /* 'maxmem' */ EXTERN long p_mmp; /* 'maxmempattern' */ EXTERN long p_mmt; /* 'maxmemtot' */ #ifdef FEAT_MENU EXTERN long p_mis; /* 'menuitems' */ #endif #ifdef FEAT_SPELL EXTERN char_u *p_msm; /* 'mkspellmem' */ #endif EXTERN long p_mls; /* 'modelines' */ EXTERN char_u *p_mouse; /* 'mouse' */ #ifdef FEAT_GUI EXTERN int p_mousef; /* 'mousefocus' */ EXTERN int p_mh; /* 'mousehide' */ #endif EXTERN char_u *p_mousem; /* 'mousemodel' */ EXTERN long p_mouset; /* 'mousetime' */ EXTERN int p_more; /* 'more' */ #ifdef FEAT_MZSCHEME EXTERN long p_mzq; /* 'mzquantum */ #endif #if defined(MSDOS) || defined(MSWIN) || defined(OS2) EXTERN int p_odev; /* 'opendevice' */ #endif EXTERN char_u *p_opfunc; /* 'operatorfunc' */ EXTERN char_u *p_para; /* 'paragraphs' */ EXTERN int p_paste; /* 'paste' */ EXTERN char_u *p_pt; /* 'pastetoggle' */ #if defined(FEAT_EVAL) && defined(FEAT_DIFF) EXTERN char_u *p_pex; /* 'patchexpr' */ #endif EXTERN char_u *p_pm; /* 'patchmode' */ EXTERN char_u *p_path; /* 'path' */ #ifdef FEAT_SEARCHPATH EXTERN char_u *p_cdpath; /* 'cdpath' */ #endif #ifdef FEAT_RELTIME EXTERN long p_rdt; /* 'redrawtime' */ #endif EXTERN int p_remap; /* 'remap' */ EXTERN long p_report; /* 'report' */ #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) EXTERN long p_pvh; /* 'previewheight' */ #endif #ifdef WIN3264 EXTERN int p_rs; /* 'restorescreen' */ #endif #ifdef FEAT_RIGHTLEFT EXTERN int p_ari; /* 'allowrevins' */ EXTERN int p_ri; /* 'revins' */ #endif #ifdef FEAT_CMDL_INFO EXTERN int p_ru; /* 'ruler' */ #endif #ifdef FEAT_STL_OPT EXTERN char_u *p_ruf; /* 'rulerformat' */ #endif EXTERN char_u *p_rtp; /* 'runtimepath' */ EXTERN long p_sj; /* 'scrolljump' */ EXTERN long p_so; /* 'scrolloff' */ #ifdef FEAT_SCROLLBIND EXTERN char_u *p_sbo; /* 'scrollopt' */ #endif EXTERN char_u *p_sections; /* 'sections' */ EXTERN int p_secure; /* 'secure' */ #ifdef FEAT_VISUAL EXTERN char_u *p_sel; /* 'selection' */ EXTERN char_u *p_slm; /* 'selectmode' */ #endif #ifdef FEAT_SESSION EXTERN char_u *p_ssop; /* 'sessionoptions' */ EXTERN unsigned ssop_flags; # ifdef IN_OPTION_C /* Also used for 'viewoptions'! */ static char *(p_ssop_values[]) = {"buffers", "winpos", "resize", "winsize", "localoptions", "options", "help", "blank", "globals", "slash", "unix", "sesdir", "curdir", "folds", "cursor", "tabpages", NULL}; # endif # define SSOP_BUFFERS 0x001 # define SSOP_WINPOS 0x002 # define SSOP_RESIZE 0x004 # define SSOP_WINSIZE 0x008 # define SSOP_LOCALOPTIONS 0x010 # define SSOP_OPTIONS 0x020 # define SSOP_HELP 0x040 # define SSOP_BLANK 0x080 # define SSOP_GLOBALS 0x100 # define SSOP_SLASH 0x200 # define SSOP_UNIX 0x400 # define SSOP_SESDIR 0x800 # define SSOP_CURDIR 0x1000 # define SSOP_FOLDS 0x2000 # define SSOP_CURSOR 0x4000 # define SSOP_TABPAGES 0x8000 #endif EXTERN char_u *p_sh; /* 'shell' */ EXTERN char_u *p_shcf; /* 'shellcmdflag' */ #ifdef FEAT_QUICKFIX EXTERN char_u *p_sp; /* 'shellpipe' */ #endif EXTERN char_u *p_shq; /* 'shellquote' */ EXTERN char_u *p_sxq; /* 'shellxquote' */ EXTERN char_u *p_sxe; /* 'shellxescape' */ EXTERN char_u *p_srr; /* 'shellredir' */ #ifdef AMIGA EXTERN long p_st; /* 'shelltype' */ #endif EXTERN int p_stmp; /* 'shelltemp' */ #ifdef BACKSLASH_IN_FILENAME EXTERN int p_ssl; /* 'shellslash' */ #endif #ifdef FEAT_STL_OPT EXTERN char_u *p_stl; /* 'statusline' */ #endif EXTERN int p_sr; /* 'shiftround' */ EXTERN char_u *p_shm; /* 'shortmess' */ #ifdef FEAT_LINEBREAK EXTERN char_u *p_sbr; /* 'showbreak' */ #endif #ifdef FEAT_CMDL_INFO EXTERN int p_sc; /* 'showcmd' */ #endif EXTERN int p_sft; /* 'showfulltag' */ EXTERN int p_sm; /* 'showmatch' */ EXTERN int p_smd; /* 'showmode' */ EXTERN long p_ss; /* 'sidescroll' */ EXTERN long p_siso; /* 'sidescrolloff' */ EXTERN int p_scs; /* 'smartcase' */ EXTERN int p_sta; /* 'smarttab' */ #ifdef FEAT_WINDOWS EXTERN int p_sb; /* 'splitbelow' */ EXTERN long p_tpm; /* 'tabpagemax' */ # if defined(FEAT_STL_OPT) EXTERN char_u *p_tal; /* 'tabline' */ # endif #endif #ifdef FEAT_SPELL EXTERN char_u *p_sps; /* 'spellsuggest' */ #endif #ifdef FEAT_VERTSPLIT EXTERN int p_spr; /* 'splitright' */ #endif EXTERN int p_sol; /* 'startofline' */ EXTERN char_u *p_su; /* 'suffixes' */ EXTERN char_u *p_sws; /* 'swapsync' */ EXTERN char_u *p_swb; /* 'switchbuf' */ EXTERN unsigned swb_flags; #ifdef IN_OPTION_C static char *(p_swb_values[]) = {"useopen", "usetab", "split", "newtab", NULL}; #endif #define SWB_USEOPEN 0x001 #define SWB_USETAB 0x002 #define SWB_SPLIT 0x004 #define SWB_NEWTAB 0x008 EXTERN int p_tbs; /* 'tagbsearch' */ EXTERN long p_tl; /* 'taglength' */ EXTERN int p_tr; /* 'tagrelative' */ EXTERN char_u *p_tags; /* 'tags' */ EXTERN int p_tgst; /* 'tagstack' */ #ifdef FEAT_ARABIC EXTERN int p_tbidi; /* 'termbidi' */ #endif #ifdef FEAT_MBYTE EXTERN char_u *p_tenc; /* 'termencoding' */ #endif EXTERN int p_terse; /* 'terse' */ EXTERN int p_ta; /* 'textauto' */ EXTERN int p_to; /* 'tildeop' */ EXTERN int p_timeout; /* 'timeout' */ EXTERN long p_tm; /* 'timeoutlen' */ #ifdef FEAT_TITLE EXTERN int p_title; /* 'title' */ EXTERN long p_titlelen; /* 'titlelen' */ EXTERN char_u *p_titleold; /* 'titleold' */ EXTERN char_u *p_titlestring; /* 'titlestring' */ #endif #ifdef FEAT_INS_EXPAND EXTERN char_u *p_tsr; /* 'thesaurus' */ #endif EXTERN int p_ttimeout; /* 'ttimeout' */ EXTERN long p_ttm; /* 'ttimeoutlen' */ EXTERN int p_tbi; /* 'ttybuiltin' */ EXTERN int p_tf; /* 'ttyfast' */ #if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) EXTERN char_u *p_toolbar; /* 'toolbar' */ EXTERN unsigned toolbar_flags; # ifdef IN_OPTION_C static char *(p_toolbar_values[]) = {"text", "icons", "tooltips", "horiz", NULL}; # endif # define TOOLBAR_TEXT 0x01 # define TOOLBAR_ICONS 0x02 # define TOOLBAR_TOOLTIPS 0x04 # define TOOLBAR_HORIZ 0x08 #endif #if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_GTK) EXTERN char_u *p_tbis; /* 'toolbariconsize' */ EXTERN unsigned tbis_flags; # ifdef IN_OPTION_C static char *(p_tbis_values[]) = {"tiny", "small", "medium", "large", NULL}; # endif # define TBIS_TINY 0x01 # define TBIS_SMALL 0x02 # define TBIS_MEDIUM 0x04 # define TBIS_LARGE 0x08 #endif EXTERN long p_ttyscroll; /* 'ttyscroll' */ #if defined(FEAT_MOUSE) && (defined(UNIX) || defined(VMS)) EXTERN char_u *p_ttym; /* 'ttymouse' */ EXTERN unsigned ttym_flags; # ifdef IN_OPTION_C static char *(p_ttym_values[]) = {"xterm", "xterm2", "dec", "netterm", "jsbterm", "pterm", "urxvt", NULL}; # endif # define TTYM_XTERM 0x01 # define TTYM_XTERM2 0x02 # define TTYM_DEC 0x04 # define TTYM_NETTERM 0x08 # define TTYM_JSBTERM 0x10 # define TTYM_PTERM 0x20 # define TTYM_URXVT 0x40 #endif EXTERN char_u *p_udir; /* 'undodir' */ EXTERN long p_ul; /* 'undolevels' */ EXTERN long p_ur; /* 'undoreload' */ EXTERN long p_uc; /* 'updatecount' */ EXTERN long p_ut; /* 'updatetime' */ #if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) EXTERN char_u *p_fcs; /* 'fillchar' */ #endif #ifdef FEAT_VIMINFO EXTERN char_u *p_viminfo; /* 'viminfo' */ #endif #ifdef FEAT_SESSION EXTERN char_u *p_vdir; /* 'viewdir' */ EXTERN char_u *p_vop; /* 'viewoptions' */ EXTERN unsigned vop_flags; /* uses SSOP_ flags */ #endif EXTERN int p_vb; /* 'visualbell' */ #ifdef FEAT_VIRTUALEDIT EXTERN char_u *p_ve; /* 'virtualedit' */ EXTERN unsigned ve_flags; # ifdef IN_OPTION_C static char *(p_ve_values[]) = {"block", "insert", "all", "onemore", NULL}; # endif # define VE_BLOCK 5 /* includes "all" */ # define VE_INSERT 6 /* includes "all" */ # define VE_ALL 4 # define VE_ONEMORE 8 #endif EXTERN long p_verbose; /* 'verbose' */ #ifdef IN_OPTION_C char_u *p_vfile = (char_u *)""; /* used before options are initialized */ #else extern char_u *p_vfile; /* 'verbosefile' */ #endif EXTERN int p_warn; /* 'warn' */ #ifdef FEAT_CMDL_COMPL EXTERN char_u *p_wop; /* 'wildoptions' */ #endif EXTERN long p_window; /* 'window' */ #if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_MOTIF) || defined(LINT) \ || defined (FEAT_GUI_GTK) || defined(FEAT_GUI_PHOTON) #define FEAT_WAK EXTERN char_u *p_wak; /* 'winaltkeys' */ #endif #ifdef FEAT_WILDIGN EXTERN char_u *p_wig; /* 'wildignore' */ #endif EXTERN int p_wiv; /* 'weirdinvert' */ EXTERN char_u *p_ww; /* 'whichwrap' */ EXTERN long p_wc; /* 'wildchar' */ EXTERN long p_wcm; /* 'wildcharm' */ EXTERN long p_wic; /* 'wildignorecase' */ EXTERN char_u *p_wim; /* 'wildmode' */ #ifdef FEAT_WILDMENU EXTERN int p_wmnu; /* 'wildmenu' */ #endif #ifdef FEAT_WINDOWS EXTERN long p_wh; /* 'winheight' */ EXTERN long p_wmh; /* 'winminheight' */ #endif #ifdef FEAT_VERTSPLIT EXTERN long p_wmw; /* 'winminwidth' */ EXTERN long p_wiw; /* 'winwidth' */ #endif EXTERN int p_ws; /* 'wrapscan' */ EXTERN int p_write; /* 'write' */ EXTERN int p_wa; /* 'writeany' */ EXTERN int p_wb; /* 'writebackup' */ EXTERN long p_wd; /* 'writedelay' */ /* * "indir" values for buffer-local opions. * These need to be defined globally, so that the BV_COUNT can be used with * b_p_scriptID[]. */ enum { BV_AI = 0 , BV_AR #ifdef FEAT_QUICKFIX , BV_BH , BV_BT , BV_EFM , BV_GP , BV_MP #endif , BV_BIN , BV_BL #ifdef FEAT_MBYTE , BV_BOMB #endif , BV_CI #ifdef FEAT_CINDENT , BV_CIN , BV_CINK , BV_CINO #endif #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) , BV_CINW #endif , BV_CM #ifdef FEAT_FOLDING , BV_CMS #endif #ifdef FEAT_COMMENTS , BV_COM #endif #ifdef FEAT_INS_EXPAND , BV_CPT , BV_DICT , BV_TSR #endif #ifdef FEAT_COMPL_FUNC , BV_CFU #endif #ifdef FEAT_FIND_ID , BV_DEF , BV_INC #endif , BV_EOL , BV_EP , BV_ET , BV_FENC #ifdef FEAT_EVAL , BV_BEXPR , BV_FEX #endif , BV_FF , BV_FLP , BV_FO #ifdef FEAT_AUTOCMD , BV_FT #endif , BV_IMI , BV_IMS #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) , BV_INDE , BV_INDK #endif #if defined(FEAT_FIND_ID) && defined(FEAT_EVAL) , BV_INEX #endif , BV_INF , BV_ISK #ifdef FEAT_CRYPT , BV_KEY #endif #ifdef FEAT_KEYMAP , BV_KMAP #endif , BV_KP #ifdef FEAT_LISP , BV_LISP #endif , BV_MA , BV_ML , BV_MOD , BV_MPS , BV_NF #ifdef FEAT_COMPL_FUNC , BV_OFU #endif , BV_PATH , BV_PI #ifdef FEAT_TEXTOBJ , BV_QE #endif , BV_RO #ifdef FEAT_SMARTINDENT , BV_SI #endif #ifndef SHORT_FNAME , BV_SN #endif #ifdef FEAT_SYN_HL , BV_SMC , BV_SYN #endif #ifdef FEAT_SPELL , BV_SPC , BV_SPF , BV_SPL #endif , BV_STS #ifdef FEAT_SEARCHPATH , BV_SUA #endif , BV_SW , BV_SWF , BV_TAGS , BV_TS , BV_TW , BV_TX , BV_UDF , BV_WM , BV_COUNT /* must be the last one */ }; /* * "indir" values for window-local options. * These need to be defined globally, so that the WV_COUNT can be used in the * window structure. */ enum { WV_LIST = 0 #ifdef FEAT_ARABIC , WV_ARAB #endif #ifdef FEAT_CONCEAL , WV_COCU , WV_COLE #endif #ifdef FEAT_CURSORBIND , WV_CRBIND #endif #ifdef FEAT_DIFF , WV_DIFF #endif #ifdef FEAT_FOLDING , WV_FDC , WV_FEN , WV_FDI , WV_FDL , WV_FDM , WV_FML , WV_FDN # ifdef FEAT_EVAL , WV_FDE , WV_FDT # endif , WV_FMR #endif #ifdef FEAT_LINEBREAK , WV_LBR #endif , WV_NU , WV_RNU #ifdef FEAT_LINEBREAK , WV_NUW #endif #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) , WV_PVW #endif #ifdef FEAT_RIGHTLEFT , WV_RL , WV_RLC #endif #ifdef FEAT_SCROLLBIND , WV_SCBIND #endif , WV_SCROLL #ifdef FEAT_SPELL , WV_SPELL #endif #ifdef FEAT_SYN_HL , WV_CUC , WV_CUL , WV_CC #endif #ifdef FEAT_STL_OPT , WV_STL #endif #ifdef FEAT_WINDOWS , WV_WFH #endif #ifdef FEAT_VERTSPLIT , WV_WFW #endif , WV_WRAP , WV_COUNT /* must be the last one */ };
zyz2011-vim
src/option.h
C
gpl2
34,672
/* this file contains the actual definitions of */ /* the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* File created by MIDL compiler version 3.00.44 */ /* at Sat Jan 03 16:34:55 1998 */ /* Compiler settings for if_ole.idl: Os (OptLev=s), W1, Zp8, env=Win32, ms_ext, c_ext error checks: none */ //@@MIDL_FILE_HEADING( ) #ifdef __cplusplus extern "C"{ #endif #ifdef __MINGW32__ # include <w32api.h> # if __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 10 /* This define is missing from older MingW versions of w32api, even though * IID is defined. */ # define __IID_DEFINED__ # endif #endif #ifndef __IID_DEFINED__ # define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif #ifndef CLSID_DEFINED # define CLSID_DEFINED typedef IID CLSID; #endif const IID IID_IVim = {0x0F0BFAE2,0x4C90,0x11d1,{0x82,0xD7,0x00,0x04,0xAC,0x36,0x85,0x19}}; const IID LIBID_Vim = {0x0F0BFAE0,0x4C90,0x11d1,{0x82,0xD7,0x00,0x04,0xAC,0x36,0x85,0x19}}; const CLSID CLSID_Vim = {0x0F0BFAE1,0x4C90,0x11d1,{0x82,0xD7,0x00,0x04,0xAC,0x36,0x85,0x19}}; #ifdef __cplusplus } #endif
zyz2011-vim
src/iid_ole.c
C
gpl2
1,218
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * ex_eval.c: functions for Ex command line for the +eval feature. */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) static void free_msglist __ARGS((struct msglist *l)); static int throw_exception __ARGS((void *, int, char_u *)); static char_u *get_end_emsg __ARGS((struct condstack *cstack)); /* * Exception handling terms: * * :try ":try" command \ * ... try block | * :catch RE ":catch" command | * ... catch clause |- try conditional * :finally ":finally" command | * ... finally clause | * :endtry ":endtry" command / * * The try conditional may have any number of catch clauses and at most one * finally clause. A ":throw" command can be inside the try block, a catch * clause, the finally clause, or in a function called or script sourced from * there or even outside the try conditional. Try conditionals may be nested. */ /* * Configuration whether an exception is thrown on error or interrupt. When * the preprocessor macros below evaluate to FALSE, an error (did_emsg) or * interrupt (got_int) under an active try conditional terminates the script * after the non-active finally clauses of all active try conditionals have been * executed. Otherwise, errors and/or interrupts are converted into catchable * exceptions (did_throw additionally set), which terminate the script only if * not caught. For user exceptions, only did_throw is set. (Note: got_int can * be set asyncronously afterwards by a SIGINT, so did_throw && got_int is not * a reliant test that the exception currently being thrown is an interrupt * exception. Similarly, did_emsg can be set afterwards on an error in an * (unskipped) conditional command inside an inactive conditional, so did_throw * && did_emsg is not a reliant test that the exception currently being thrown * is an error exception.) - The macros can be defined as expressions checking * for a variable that is allowed to be changed during execution of a script. */ #if 0 /* Expressions used for testing during the development phase. */ # define THROW_ON_ERROR (!eval_to_number("$VIMNOERRTHROW")) # define THROW_ON_INTERRUPT (!eval_to_number("$VIMNOINTTHROW")) # define THROW_TEST #else /* Values used for the Vim release. */ # define THROW_ON_ERROR TRUE # define THROW_ON_ERROR_TRUE # define THROW_ON_INTERRUPT TRUE # define THROW_ON_INTERRUPT_TRUE #endif static void catch_exception __ARGS((except_T *excp)); static void finish_exception __ARGS((except_T *excp)); static void discard_exception __ARGS((except_T *excp, int was_finished)); static void report_pending __ARGS((int action, int pending, void *value)); /* * When several errors appear in a row, setting "force_abort" is delayed until * the failing command returned. "cause_abort" is set to TRUE meanwhile, in * order to indicate that situation. This is useful when "force_abort" was set * during execution of a function call from an expression: the aborting of the * expression evaluation is done without producing any error messages, but all * error messages on parsing errors during the expression evaluation are given * (even if a try conditional is active). */ static int cause_abort = FALSE; /* * Return TRUE when immediately aborting on error, or when an interrupt * occurred or an exception was thrown but not caught. Use for ":{range}call" * to check whether an aborted function that does not handle a range itself * should be called again for the next line in the range. Also used for * cancelling expression evaluation after a function call caused an immediate * abort. Note that the first emsg() call temporarily resets "force_abort" * until the throw point for error messages has been reached. That is, during * cancellation of an expression evaluation after an aborting function call or * due to a parsing error, aborting() always returns the same value. */ int aborting() { return (did_emsg && force_abort) || got_int || did_throw; } /* * The value of "force_abort" is temporarily reset by the first emsg() call * during an expression evaluation, and "cause_abort" is used instead. It might * be necessary to restore "force_abort" even before the throw point for the * error message has been reached. update_force_abort() should be called then. */ void update_force_abort() { if (cause_abort) force_abort = TRUE; } /* * Return TRUE if a command with a subcommand resulting in "retcode" should * abort the script processing. Can be used to suppress an autocommand after * execution of a failing subcommand as long as the error message has not been * displayed and actually caused the abortion. */ int should_abort(retcode) int retcode; { return ((retcode == FAIL && trylevel != 0 && !emsg_silent) || aborting()); } /* * Return TRUE if a function with the "abort" flag should not be considered * ended on an error. This means that parsing commands is continued in order * to find finally clauses to be executed, and that some errors in skipped * commands are still reported. */ int aborted_in_try() { /* This function is only called after an error. In this case, "force_abort" * determines whether searching for finally clauses is necessary. */ return force_abort; } /* * cause_errthrow(): Cause a throw of an error exception if appropriate. * Return TRUE if the error message should not be displayed by emsg(). * Sets "ignore", if the emsg() call should be ignored completely. * * When several messages appear in the same command, the first is usually the * most specific one and used as the exception value. The "severe" flag can be * set to TRUE, if a later but severer message should be used instead. */ int cause_errthrow(mesg, severe, ignore) char_u *mesg; int severe; int *ignore; { struct msglist *elem; struct msglist **plist; /* * Do nothing when displaying the interrupt message or reporting an * uncaught exception (which has already been discarded then) at the top * level. Also when no exception can be thrown. The message will be * displayed by emsg(). */ if (suppress_errthrow) return FALSE; /* * If emsg() has not been called previously, temporarily reset * "force_abort" until the throw point for error messages has been * reached. This ensures that aborting() returns the same value for all * errors that appear in the same command. This means particularly that * for parsing errors during expression evaluation emsg() will be called * multiply, even when the expression is evaluated from a finally clause * that was activated due to an aborting error, interrupt, or exception. */ if (!did_emsg) { cause_abort = force_abort; force_abort = FALSE; } /* * If no try conditional is active and no exception is being thrown and * there has not been an error in a try conditional or a throw so far, do * nothing (for compatibility of non-EH scripts). The message will then * be displayed by emsg(). When ":silent!" was used and we are not * currently throwing an exception, do nothing. The message text will * then be stored to v:errmsg by emsg() without displaying it. */ if (((trylevel == 0 && !cause_abort) || emsg_silent) && !did_throw) return FALSE; /* * Ignore an interrupt message when inside a try conditional or when an * exception is being thrown or when an error in a try conditional or * throw has been detected previously. This is important in order that an * interrupt exception is catchable by the innermost try conditional and * not replaced by an interrupt message error exception. */ if (mesg == (char_u *)_(e_interr)) { *ignore = TRUE; return TRUE; } /* * Ensure that all commands in nested function calls and sourced files * are aborted immediately. */ cause_abort = TRUE; /* * When an exception is being thrown, some commands (like conditionals) are * not skipped. Errors in those commands may affect what of the subsequent * commands are regarded part of catch and finally clauses. Catching the * exception would then cause execution of commands not intended by the * user, who wouldn't even get aware of the problem. Therefor, discard the * exception currently being thrown to prevent it from being caught. Just * execute finally clauses and terminate. */ if (did_throw) { /* When discarding an interrupt exception, reset got_int to prevent the * same interrupt being converted to an exception again and discarding * the error exception we are about to throw here. */ if (current_exception->type == ET_INTERRUPT) got_int = FALSE; discard_current_exception(); } #ifdef THROW_TEST if (!THROW_ON_ERROR) { /* * Print error message immediately without searching for a matching * catch clause; just finally clauses are executed before the script * is terminated. */ return FALSE; } else #endif { /* * Prepare the throw of an error exception, so that everything will * be aborted (except for executing finally clauses), until the error * exception is caught; if still uncaught at the top level, the error * message will be displayed and the script processing terminated * then. - This function has no access to the conditional stack. * Thus, the actual throw is made after the failing command has * returned. - Throw only the first of several errors in a row, except * a severe error is following. */ if (msg_list != NULL) { plist = msg_list; while (*plist != NULL) plist = &(*plist)->next; elem = (struct msglist *)alloc((unsigned)sizeof(struct msglist)); if (elem == NULL) { suppress_errthrow = TRUE; EMSG(_(e_outofmem)); } else { elem->msg = vim_strsave(mesg); if (elem->msg == NULL) { vim_free(elem); suppress_errthrow = TRUE; EMSG(_(e_outofmem)); } else { elem->next = NULL; elem->throw_msg = NULL; *plist = elem; if (plist == msg_list || severe) { char_u *tmsg; /* Skip the extra "Vim " prefix for message "E458". */ tmsg = elem->msg; if (STRNCMP(tmsg, "Vim E", 5) == 0 && VIM_ISDIGIT(tmsg[5]) && VIM_ISDIGIT(tmsg[6]) && VIM_ISDIGIT(tmsg[7]) && tmsg[8] == ':' && tmsg[9] == ' ') (*msg_list)->throw_msg = &tmsg[4]; else (*msg_list)->throw_msg = tmsg; } } } } return TRUE; } } /* * Free a "msg_list" and the messages it contains. */ static void free_msglist(l) struct msglist *l; { struct msglist *messages, *next; messages = l; while (messages != NULL) { next = messages->next; vim_free(messages->msg); vim_free(messages); messages = next; } } /* * Throw the message specified in the call to cause_errthrow() above as an * error exception. If cstack is NULL, postpone the throw until do_cmdline() * has returned (see do_one_cmd()). */ void do_errthrow(cstack, cmdname) struct condstack *cstack; char_u *cmdname; { /* * Ensure that all commands in nested function calls and sourced files * are aborted immediately. */ if (cause_abort) { cause_abort = FALSE; force_abort = TRUE; } /* If no exception is to be thrown or the conversion should be done after * returning to a previous invocation of do_one_cmd(), do nothing. */ if (msg_list == NULL || *msg_list == NULL) return; if (throw_exception(*msg_list, ET_ERROR, cmdname) == FAIL) free_msglist(*msg_list); else { if (cstack != NULL) do_throw(cstack); else need_rethrow = TRUE; } *msg_list = NULL; } /* * do_intthrow(): Replace the current exception by an interrupt or interrupt * exception if appropriate. Return TRUE if the current exception is discarded, * FALSE otherwise. */ int do_intthrow(cstack) struct condstack *cstack; { /* * If no interrupt occurred or no try conditional is active and no exception * is being thrown, do nothing (for compatibility of non-EH scripts). */ if (!got_int || (trylevel == 0 && !did_throw)) return FALSE; #ifdef THROW_TEST /* avoid warning for condition always true */ if (!THROW_ON_INTERRUPT) { /* * The interrupt aborts everything except for executing finally clauses. * Discard any user or error or interrupt exception currently being * thrown. */ if (did_throw) discard_current_exception(); } else #endif { /* * Throw an interrupt exception, so that everything will be aborted * (except for executing finally clauses), until the interrupt exception * is caught; if still uncaught at the top level, the script processing * will be terminated then. - If an interrupt exception is already * being thrown, do nothing. * */ if (did_throw) { if (current_exception->type == ET_INTERRUPT) return FALSE; /* An interrupt exception replaces any user or error exception. */ discard_current_exception(); } if (throw_exception("Vim:Interrupt", ET_INTERRUPT, NULL) != FAIL) do_throw(cstack); } return TRUE; } /* * Throw a new exception. Return FAIL when out of memory or it was tried to * throw an illegal user exception. "value" is the exception string for a user * or interrupt exception, or points to a message list in case of an error * exception. */ static int throw_exception(value, type, cmdname) void *value; int type; char_u *cmdname; { except_T *excp; char_u *p, *mesg, *val; int cmdlen; /* * Disallow faking Interrupt or error exceptions as user exceptions. They * would be treated differently from real interrupt or error exceptions when * no active try block is found, see do_cmdline(). */ if (type == ET_USER) { if (STRNCMP((char_u *)value, "Vim", 3) == 0 && (((char_u *)value)[3] == NUL || ((char_u *)value)[3] == ':' || ((char_u *)value)[3] == '(')) { EMSG(_("E608: Cannot :throw exceptions with 'Vim' prefix")); goto fail; } } excp = (except_T *)alloc((unsigned)sizeof(except_T)); if (excp == NULL) goto nomem; if (type == ET_ERROR) { /* Store the original message and prefix the exception value with * "Vim:" or, if a command name is given, "Vim(cmdname):". */ excp->messages = (struct msglist *)value; mesg = excp->messages->throw_msg; if (cmdname != NULL && *cmdname != NUL) { cmdlen = (int)STRLEN(cmdname); excp->value = vim_strnsave((char_u *)"Vim(", 4 + cmdlen + 2 + (int)STRLEN(mesg)); if (excp->value == NULL) goto nomem; STRCPY(&excp->value[4], cmdname); STRCPY(&excp->value[4 + cmdlen], "):"); val = excp->value + 4 + cmdlen + 2; } else { excp->value = vim_strnsave((char_u *)"Vim:", 4 + (int)STRLEN(mesg)); if (excp->value == NULL) goto nomem; val = excp->value + 4; } /* msg_add_fname may have been used to prefix the message with a file * name in quotes. In the exception value, put the file name in * parentheses and move it to the end. */ for (p = mesg; ; p++) { if (*p == NUL || (*p == 'E' && VIM_ISDIGIT(p[1]) && (p[2] == ':' || (VIM_ISDIGIT(p[2]) && (p[3] == ':' || (VIM_ISDIGIT(p[3]) && p[4] == ':')))))) { if (*p == NUL || p == mesg) STRCAT(val, mesg); /* 'E123' missing or at beginning */ else { /* '"filename" E123: message text' */ if (mesg[0] != '"' || p-2 < &mesg[1] || p[-2] != '"' || p[-1] != ' ') /* "E123:" is part of the file name. */ continue; STRCAT(val, p); p[-2] = NUL; sprintf((char *)(val + STRLEN(p)), " (%s)", &mesg[1]); p[-2] = '"'; } break; } } } else excp->value = value; excp->type = type; excp->throw_name = vim_strsave(sourcing_name == NULL ? (char_u *)"" : sourcing_name); if (excp->throw_name == NULL) { if (type == ET_ERROR) vim_free(excp->value); goto nomem; } excp->throw_lnum = sourcing_lnum; if (p_verbose >= 13 || debug_break_level > 0) { int save_msg_silent = msg_silent; if (debug_break_level > 0) msg_silent = FALSE; /* display messages */ else verbose_enter(); ++no_wait_return; if (debug_break_level > 0 || *p_vfile == NUL) msg_scroll = TRUE; /* always scroll up, don't overwrite */ smsg((char_u *)_("Exception thrown: %s"), excp->value); msg_puts((char_u *)"\n"); /* don't overwrite this either */ if (debug_break_level > 0 || *p_vfile == NUL) cmdline_row = msg_row; --no_wait_return; if (debug_break_level > 0) msg_silent = save_msg_silent; else verbose_leave(); } current_exception = excp; return OK; nomem: vim_free(excp); suppress_errthrow = TRUE; EMSG(_(e_outofmem)); fail: current_exception = NULL; return FAIL; } /* * Discard an exception. "was_finished" is set when the exception has been * caught and the catch clause has been ended normally. */ static void discard_exception(excp, was_finished) except_T *excp; int was_finished; { char_u *saved_IObuff; if (excp == NULL) { EMSG(_(e_internal)); return; } if (p_verbose >= 13 || debug_break_level > 0) { int save_msg_silent = msg_silent; saved_IObuff = vim_strsave(IObuff); if (debug_break_level > 0) msg_silent = FALSE; /* display messages */ else verbose_enter(); ++no_wait_return; if (debug_break_level > 0 || *p_vfile == NUL) msg_scroll = TRUE; /* always scroll up, don't overwrite */ smsg(was_finished ? (char_u *)_("Exception finished: %s") : (char_u *)_("Exception discarded: %s"), excp->value); msg_puts((char_u *)"\n"); /* don't overwrite this either */ if (debug_break_level > 0 || *p_vfile == NUL) cmdline_row = msg_row; --no_wait_return; if (debug_break_level > 0) msg_silent = save_msg_silent; else verbose_leave(); STRCPY(IObuff, saved_IObuff); vim_free(saved_IObuff); } if (excp->type != ET_INTERRUPT) vim_free(excp->value); if (excp->type == ET_ERROR) free_msglist(excp->messages); vim_free(excp->throw_name); vim_free(excp); } /* * Discard the exception currently being thrown. */ void discard_current_exception() { discard_exception(current_exception, FALSE); current_exception = NULL; did_throw = FALSE; need_rethrow = FALSE; } /* * Put an exception on the caught stack. */ static void catch_exception(excp) except_T *excp; { excp->caught = caught_stack; caught_stack = excp; set_vim_var_string(VV_EXCEPTION, excp->value, -1); if (*excp->throw_name != NUL) { if (excp->throw_lnum != 0) vim_snprintf((char *)IObuff, IOSIZE, _("%s, line %ld"), excp->throw_name, (long)excp->throw_lnum); else vim_snprintf((char *)IObuff, IOSIZE, "%s", excp->throw_name); set_vim_var_string(VV_THROWPOINT, IObuff, -1); } else /* throw_name not set on an exception from a command that was typed. */ set_vim_var_string(VV_THROWPOINT, NULL, -1); if (p_verbose >= 13 || debug_break_level > 0) { int save_msg_silent = msg_silent; if (debug_break_level > 0) msg_silent = FALSE; /* display messages */ else verbose_enter(); ++no_wait_return; if (debug_break_level > 0 || *p_vfile == NUL) msg_scroll = TRUE; /* always scroll up, don't overwrite */ smsg((char_u *)_("Exception caught: %s"), excp->value); msg_puts((char_u *)"\n"); /* don't overwrite this either */ if (debug_break_level > 0 || *p_vfile == NUL) cmdline_row = msg_row; --no_wait_return; if (debug_break_level > 0) msg_silent = save_msg_silent; else verbose_leave(); } } /* * Remove an exception from the caught stack. */ static void finish_exception(excp) except_T *excp; { if (excp != caught_stack) EMSG(_(e_internal)); caught_stack = caught_stack->caught; if (caught_stack != NULL) { set_vim_var_string(VV_EXCEPTION, caught_stack->value, -1); if (*caught_stack->throw_name != NUL) { if (caught_stack->throw_lnum != 0) vim_snprintf((char *)IObuff, IOSIZE, _("%s, line %ld"), caught_stack->throw_name, (long)caught_stack->throw_lnum); else vim_snprintf((char *)IObuff, IOSIZE, "%s", caught_stack->throw_name); set_vim_var_string(VV_THROWPOINT, IObuff, -1); } else /* throw_name not set on an exception from a command that was * typed. */ set_vim_var_string(VV_THROWPOINT, NULL, -1); } else { set_vim_var_string(VV_EXCEPTION, NULL, -1); set_vim_var_string(VV_THROWPOINT, NULL, -1); } /* Discard the exception, but use the finish message for 'verbose'. */ discard_exception(excp, TRUE); } /* * Flags specifying the message displayed by report_pending. */ #define RP_MAKE 0 #define RP_RESUME 1 #define RP_DISCARD 2 /* * Report information about something pending in a finally clause if required by * the 'verbose' option or when debugging. "action" tells whether something is * made pending or something pending is resumed or discarded. "pending" tells * what is pending. "value" specifies the return value for a pending ":return" * or the exception value for a pending exception. */ static void report_pending(action, pending, value) int action; int pending; void *value; { char_u *mesg; char *s; int save_msg_silent; switch (action) { case RP_MAKE: mesg = (char_u *)_("%s made pending"); break; case RP_RESUME: mesg = (char_u *)_("%s resumed"); break; /* case RP_DISCARD: */ default: mesg = (char_u *)_("%s discarded"); break; } switch (pending) { case CSTP_NONE: return; case CSTP_CONTINUE: s = ":continue"; break; case CSTP_BREAK: s = ":break"; break; case CSTP_FINISH: s = ":finish"; break; case CSTP_RETURN: /* ":return" command producing value, allocated */ s = (char *)get_return_cmd(value); break; default: if (pending & CSTP_THROW) { vim_snprintf((char *)IObuff, IOSIZE, (char *)mesg, _("Exception")); mesg = vim_strnsave(IObuff, (int)STRLEN(IObuff) + 4); STRCAT(mesg, ": %s"); s = (char *)((except_T *)value)->value; } else if ((pending & CSTP_ERROR) && (pending & CSTP_INTERRUPT)) s = _("Error and interrupt"); else if (pending & CSTP_ERROR) s = _("Error"); else /* if (pending & CSTP_INTERRUPT) */ s = _("Interrupt"); } save_msg_silent = msg_silent; if (debug_break_level > 0) msg_silent = FALSE; /* display messages */ ++no_wait_return; msg_scroll = TRUE; /* always scroll up, don't overwrite */ smsg(mesg, (char_u *)s); msg_puts((char_u *)"\n"); /* don't overwrite this either */ cmdline_row = msg_row; --no_wait_return; if (debug_break_level > 0) msg_silent = save_msg_silent; if (pending == CSTP_RETURN) vim_free(s); else if (pending & CSTP_THROW) vim_free(mesg); } /* * If something is made pending in a finally clause, report it if required by * the 'verbose' option or when debugging. */ void report_make_pending(pending, value) int pending; void *value; { if (p_verbose >= 14 || debug_break_level > 0) { if (debug_break_level <= 0) verbose_enter(); report_pending(RP_MAKE, pending, value); if (debug_break_level <= 0) verbose_leave(); } } /* * If something pending in a finally clause is resumed at the ":endtry", report * it if required by the 'verbose' option or when debugging. */ void report_resume_pending(pending, value) int pending; void *value; { if (p_verbose >= 14 || debug_break_level > 0) { if (debug_break_level <= 0) verbose_enter(); report_pending(RP_RESUME, pending, value); if (debug_break_level <= 0) verbose_leave(); } } /* * If something pending in a finally clause is discarded, report it if required * by the 'verbose' option or when debugging. */ void report_discard_pending(pending, value) int pending; void *value; { if (p_verbose >= 14 || debug_break_level > 0) { if (debug_break_level <= 0) verbose_enter(); report_pending(RP_DISCARD, pending, value); if (debug_break_level <= 0) verbose_leave(); } } /* * ":if". */ void ex_if(eap) exarg_T *eap; { int error; int skip; int result; struct condstack *cstack = eap->cstack; if (cstack->cs_idx == CSTACK_LEN - 1) eap->errmsg = (char_u *)N_("E579: :if nesting too deep"); else { ++cstack->cs_idx; cstack->cs_flags[cstack->cs_idx] = 0; /* * Don't do something after an error, interrupt, or throw, or when there * is a surrounding conditional and it was not active. */ skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0 && !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE)); result = eval_to_bool(eap->arg, &error, &eap->nextcmd, skip); if (!skip && !error) { if (result) cstack->cs_flags[cstack->cs_idx] = CSF_ACTIVE | CSF_TRUE; } else /* set TRUE, so this conditional will never get active */ cstack->cs_flags[cstack->cs_idx] = CSF_TRUE; } } /* * ":endif". */ void ex_endif(eap) exarg_T *eap; { did_endif = TRUE; if (eap->cstack->cs_idx < 0 || (eap->cstack->cs_flags[eap->cstack->cs_idx] & (CSF_WHILE | CSF_FOR | CSF_TRY))) eap->errmsg = (char_u *)N_("E580: :endif without :if"); else { /* * When debugging or a breakpoint was encountered, display the debug * prompt (if not already done). This shows the user that an ":endif" * is executed when the ":if" or a previous ":elseif" was not TRUE. * Handle a ">quit" debug command as if an interrupt had occurred before * the ":endif". That is, throw an interrupt exception if appropriate. * Doing this here prevents an exception for a parsing error being * discarded by throwing the interrupt exception later on. */ if (!(eap->cstack->cs_flags[eap->cstack->cs_idx] & CSF_TRUE) && dbg_check_skipped(eap)) (void)do_intthrow(eap->cstack); --eap->cstack->cs_idx; } } /* * ":else" and ":elseif". */ void ex_else(eap) exarg_T *eap; { int error; int skip; int result; struct condstack *cstack = eap->cstack; /* * Don't do something after an error, interrupt, or throw, or when there is * a surrounding conditional and it was not active. */ skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0 && !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE)); if (cstack->cs_idx < 0 || (cstack->cs_flags[cstack->cs_idx] & (CSF_WHILE | CSF_FOR | CSF_TRY))) { if (eap->cmdidx == CMD_else) { eap->errmsg = (char_u *)N_("E581: :else without :if"); return; } eap->errmsg = (char_u *)N_("E582: :elseif without :if"); skip = TRUE; } else if (cstack->cs_flags[cstack->cs_idx] & CSF_ELSE) { if (eap->cmdidx == CMD_else) { eap->errmsg = (char_u *)N_("E583: multiple :else"); return; } eap->errmsg = (char_u *)N_("E584: :elseif after :else"); skip = TRUE; } /* if skipping or the ":if" was TRUE, reset ACTIVE, otherwise set it */ if (skip || cstack->cs_flags[cstack->cs_idx] & CSF_TRUE) { if (eap->errmsg == NULL) cstack->cs_flags[cstack->cs_idx] = CSF_TRUE; skip = TRUE; /* don't evaluate an ":elseif" */ } else cstack->cs_flags[cstack->cs_idx] = CSF_ACTIVE; /* * When debugging or a breakpoint was encountered, display the debug prompt * (if not already done). This shows the user that an ":else" or ":elseif" * is executed when the ":if" or previous ":elseif" was not TRUE. Handle * a ">quit" debug command as if an interrupt had occurred before the * ":else" or ":elseif". That is, set "skip" and throw an interrupt * exception if appropriate. Doing this here prevents that an exception * for a parsing errors is discarded when throwing the interrupt exception * later on. */ if (!skip && dbg_check_skipped(eap) && got_int) { (void)do_intthrow(cstack); skip = TRUE; } if (eap->cmdidx == CMD_elseif) { result = eval_to_bool(eap->arg, &error, &eap->nextcmd, skip); /* When throwing error exceptions, we want to throw always the first * of several errors in a row. This is what actually happens when * a conditional error was detected above and there is another failure * when parsing the expression. Since the skip flag is set in this * case, the parsing error will be ignored by emsg(). */ if (!skip && !error) { if (result) cstack->cs_flags[cstack->cs_idx] = CSF_ACTIVE | CSF_TRUE; else cstack->cs_flags[cstack->cs_idx] = 0; } else if (eap->errmsg == NULL) /* set TRUE, so this conditional will never get active */ cstack->cs_flags[cstack->cs_idx] = CSF_TRUE; } else cstack->cs_flags[cstack->cs_idx] |= CSF_ELSE; } /* * Handle ":while" and ":for". */ void ex_while(eap) exarg_T *eap; { int error; int skip; int result; struct condstack *cstack = eap->cstack; if (cstack->cs_idx == CSTACK_LEN - 1) eap->errmsg = (char_u *)N_("E585: :while/:for nesting too deep"); else { /* * The loop flag is set when we have jumped back from the matching * ":endwhile" or ":endfor". When not set, need to initialise this * cstack entry. */ if ((cstack->cs_lflags & CSL_HAD_LOOP) == 0) { ++cstack->cs_idx; ++cstack->cs_looplevel; cstack->cs_line[cstack->cs_idx] = -1; } cstack->cs_flags[cstack->cs_idx] = eap->cmdidx == CMD_while ? CSF_WHILE : CSF_FOR; /* * Don't do something after an error, interrupt, or throw, or when * there is a surrounding conditional and it was not active. */ skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0 && !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE)); if (eap->cmdidx == CMD_while) { /* * ":while bool-expr" */ result = eval_to_bool(eap->arg, &error, &eap->nextcmd, skip); } else { void *fi; /* * ":for var in list-expr" */ if ((cstack->cs_lflags & CSL_HAD_LOOP) != 0) { /* Jumping here from a ":continue" or ":endfor": use the * previously evaluated list. */ fi = cstack->cs_forinfo[cstack->cs_idx]; error = FALSE; } else { /* Evaluate the argument and get the info in a structure. */ fi = eval_for_line(eap->arg, &error, &eap->nextcmd, skip); cstack->cs_forinfo[cstack->cs_idx] = fi; } /* use the element at the start of the list and advance */ if (!error && fi != NULL && !skip) result = next_for_item(fi, eap->arg); else result = FALSE; if (!result) { free_for_info(fi); cstack->cs_forinfo[cstack->cs_idx] = NULL; } } /* * If this cstack entry was just initialised and is active, set the * loop flag, so do_cmdline() will set the line number in cs_line[]. * If executing the command a second time, clear the loop flag. */ if (!skip && !error && result) { cstack->cs_flags[cstack->cs_idx] |= (CSF_ACTIVE | CSF_TRUE); cstack->cs_lflags ^= CSL_HAD_LOOP; } else { cstack->cs_lflags &= ~CSL_HAD_LOOP; /* If the ":while" evaluates to FALSE or ":for" is past the end of * the list, show the debug prompt at the ":endwhile"/":endfor" as * if there was a ":break" in a ":while"/":for" evaluating to * TRUE. */ if (!skip && !error) cstack->cs_flags[cstack->cs_idx] |= CSF_TRUE; } } } /* * ":continue" */ void ex_continue(eap) exarg_T *eap; { int idx; struct condstack *cstack = eap->cstack; if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0) eap->errmsg = (char_u *)N_("E586: :continue without :while or :for"); else { /* Try to find the matching ":while". This might stop at a try * conditional not in its finally clause (which is then to be executed * next). Therefor, inactivate all conditionals except the ":while" * itself (if reached). */ idx = cleanup_conditionals(cstack, CSF_WHILE | CSF_FOR, FALSE); if (idx >= 0 && (cstack->cs_flags[idx] & (CSF_WHILE | CSF_FOR))) { rewind_conditionals(cstack, idx, CSF_TRY, &cstack->cs_trylevel); /* * Set CSL_HAD_CONT, so do_cmdline() will jump back to the * matching ":while". */ cstack->cs_lflags |= CSL_HAD_CONT; /* let do_cmdline() handle it */ } else { /* If a try conditional not in its finally clause is reached first, * make the ":continue" pending for execution at the ":endtry". */ cstack->cs_pending[idx] = CSTP_CONTINUE; report_make_pending(CSTP_CONTINUE, NULL); } } } /* * ":break" */ void ex_break(eap) exarg_T *eap; { int idx; struct condstack *cstack = eap->cstack; if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0) eap->errmsg = (char_u *)N_("E587: :break without :while or :for"); else { /* Inactivate conditionals until the matching ":while" or a try * conditional not in its finally clause (which is then to be * executed next) is found. In the latter case, make the ":break" * pending for execution at the ":endtry". */ idx = cleanup_conditionals(cstack, CSF_WHILE | CSF_FOR, TRUE); if (idx >= 0 && !(cstack->cs_flags[idx] & (CSF_WHILE | CSF_FOR))) { cstack->cs_pending[idx] = CSTP_BREAK; report_make_pending(CSTP_BREAK, NULL); } } } /* * ":endwhile" and ":endfor" */ void ex_endwhile(eap) exarg_T *eap; { struct condstack *cstack = eap->cstack; int idx; char_u *err; int csf; int fl; if (eap->cmdidx == CMD_endwhile) { err = e_while; csf = CSF_WHILE; } else { err = e_for; csf = CSF_FOR; } if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0) eap->errmsg = err; else { fl = cstack->cs_flags[cstack->cs_idx]; if (!(fl & csf)) { /* If we are in a ":while" or ":for" but used the wrong endloop * command, do not rewind to the next enclosing ":for"/":while". */ if (fl & CSF_WHILE) eap->errmsg = (char_u *)_("E732: Using :endfor with :while"); else if (fl & CSF_FOR) eap->errmsg = (char_u *)_("E733: Using :endwhile with :for"); } if (!(fl & (CSF_WHILE | CSF_FOR))) { if (!(fl & CSF_TRY)) eap->errmsg = e_endif; else if (fl & CSF_FINALLY) eap->errmsg = e_endtry; /* Try to find the matching ":while" and report what's missing. */ for (idx = cstack->cs_idx; idx > 0; --idx) { fl = cstack->cs_flags[idx]; if ((fl & CSF_TRY) && !(fl & CSF_FINALLY)) { /* Give up at a try conditional not in its finally clause. * Ignore the ":endwhile"/":endfor". */ eap->errmsg = err; return; } if (fl & csf) break; } /* Cleanup and rewind all contained (and unclosed) conditionals. */ (void)cleanup_conditionals(cstack, CSF_WHILE | CSF_FOR, FALSE); rewind_conditionals(cstack, idx, CSF_TRY, &cstack->cs_trylevel); } /* * When debugging or a breakpoint was encountered, display the debug * prompt (if not already done). This shows the user that an * ":endwhile"/":endfor" is executed when the ":while" was not TRUE or * after a ":break". Handle a ">quit" debug command as if an * interrupt had occurred before the ":endwhile"/":endfor". That is, * throw an interrupt exception if appropriate. Doing this here * prevents that an exception for a parsing error is discarded when * throwing the interrupt exception later on. */ else if (cstack->cs_flags[cstack->cs_idx] & CSF_TRUE && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE) && dbg_check_skipped(eap)) (void)do_intthrow(cstack); /* * Set loop flag, so do_cmdline() will jump back to the matching * ":while" or ":for". */ cstack->cs_lflags |= CSL_HAD_ENDLOOP; } } /* * ":throw expr" */ void ex_throw(eap) exarg_T *eap; { char_u *arg = eap->arg; char_u *value; if (*arg != NUL && *arg != '|' && *arg != '\n') value = eval_to_string_skip(arg, &eap->nextcmd, eap->skip); else { EMSG(_(e_argreq)); value = NULL; } /* On error or when an exception is thrown during argument evaluation, do * not throw. */ if (!eap->skip && value != NULL) { if (throw_exception(value, ET_USER, NULL) == FAIL) vim_free(value); else do_throw(eap->cstack); } } /* * Throw the current exception through the specified cstack. Common routine * for ":throw" (user exception) and error and interrupt exceptions. Also * used for rethrowing an uncaught exception. */ void do_throw(cstack) struct condstack *cstack; { int idx; int inactivate_try = FALSE; /* * Cleanup and inactivate up to the next surrounding try conditional that * is not in its finally clause. Normally, do not inactivate the try * conditional itself, so that its ACTIVE flag can be tested below. But * if a previous error or interrupt has not been converted to an exception, * inactivate the try conditional, too, as if the conversion had been done, * and reset the did_emsg or got_int flag, so this won't happen again at * the next surrounding try conditional. */ #ifndef THROW_ON_ERROR_TRUE if (did_emsg && !THROW_ON_ERROR) { inactivate_try = TRUE; did_emsg = FALSE; } #endif #ifndef THROW_ON_INTERRUPT_TRUE if (got_int && !THROW_ON_INTERRUPT) { inactivate_try = TRUE; got_int = FALSE; } #endif idx = cleanup_conditionals(cstack, 0, inactivate_try); if (idx >= 0) { /* * If this try conditional is active and we are before its first * ":catch", set THROWN so that the ":catch" commands will check * whether the exception matches. When the exception came from any of * the catch clauses, it will be made pending at the ":finally" (if * present) and rethrown at the ":endtry". This will also happen if * the try conditional is inactive. This is the case when we are * throwing an exception due to an error or interrupt on the way from * a preceding ":continue", ":break", ":return", ":finish", error or * interrupt (not converted to an exception) to the finally clause or * from a preceding throw of a user or error or interrupt exception to * the matching catch clause or the finally clause. */ if (!(cstack->cs_flags[idx] & CSF_CAUGHT)) { if (cstack->cs_flags[idx] & CSF_ACTIVE) cstack->cs_flags[idx] |= CSF_THROWN; else /* THROWN may have already been set for a catchable exception * that has been discarded. Ensure it is reset for the new * exception. */ cstack->cs_flags[idx] &= ~CSF_THROWN; } cstack->cs_flags[idx] &= ~CSF_ACTIVE; cstack->cs_exception[idx] = current_exception; } #if 0 /* TODO: Add optimization below. Not yet done because of interface * problems to eval.c and ex_cmds2.c. (Servatius) */ else { /* * There are no catch clauses to check or finally clauses to execute. * End the current script or function. The exception will be rethrown * in the caller. */ if (getline_equal(eap->getline, eap->cookie, get_func_line)) current_funccal->returned = TRUE; elseif (eap->get_func_line == getsourceline) ((struct source_cookie *)eap->cookie)->finished = TRUE; } #endif did_throw = TRUE; } /* * ":try" */ void ex_try(eap) exarg_T *eap; { int skip; struct condstack *cstack = eap->cstack; if (cstack->cs_idx == CSTACK_LEN - 1) eap->errmsg = (char_u *)N_("E601: :try nesting too deep"); else { ++cstack->cs_idx; ++cstack->cs_trylevel; cstack->cs_flags[cstack->cs_idx] = CSF_TRY; cstack->cs_pending[cstack->cs_idx] = CSTP_NONE; /* * Don't do something after an error, interrupt, or throw, or when there * is a surrounding conditional and it was not active. */ skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0 && !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE)); if (!skip) { /* Set ACTIVE and TRUE. TRUE means that the corresponding ":catch" * commands should check for a match if an exception is thrown and * that the finally clause needs to be executed. */ cstack->cs_flags[cstack->cs_idx] |= CSF_ACTIVE | CSF_TRUE; /* * ":silent!", even when used in a try conditional, disables * displaying of error messages and conversion of errors to * exceptions. When the silent commands again open a try * conditional, save "emsg_silent" and reset it so that errors are * again converted to exceptions. The value is restored when that * try conditional is left. If it is left normally, the commands * following the ":endtry" are again silent. If it is left by * a ":continue", ":break", ":return", or ":finish", the commands * executed next are again silent. If it is left due to an * aborting error, an interrupt, or an exception, restoring * "emsg_silent" does not matter since we are already in the * aborting state and/or the exception has already been thrown. * The effect is then just freeing the memory that was allocated * to save the value. */ if (emsg_silent) { eslist_T *elem; elem = (eslist_T *)alloc((unsigned)sizeof(struct eslist_elem)); if (elem == NULL) EMSG(_(e_outofmem)); else { elem->saved_emsg_silent = emsg_silent; elem->next = cstack->cs_emsg_silent_list; cstack->cs_emsg_silent_list = elem; cstack->cs_flags[cstack->cs_idx] |= CSF_SILENT; emsg_silent = 0; } } } } } /* * ":catch /{pattern}/" and ":catch" */ void ex_catch(eap) exarg_T *eap; { int idx = 0; int give_up = FALSE; int skip = FALSE; int caught = FALSE; char_u *end; int save_char = 0; char_u *save_cpo; regmatch_T regmatch; int prev_got_int; struct condstack *cstack = eap->cstack; char_u *pat; if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0) { eap->errmsg = (char_u *)N_("E603: :catch without :try"); give_up = TRUE; } else { if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY)) { /* Report what's missing if the matching ":try" is not in its * finally clause. */ eap->errmsg = get_end_emsg(cstack); skip = TRUE; } for (idx = cstack->cs_idx; idx > 0; --idx) if (cstack->cs_flags[idx] & CSF_TRY) break; if (cstack->cs_flags[idx] & CSF_FINALLY) { /* Give up for a ":catch" after ":finally" and ignore it. * Just parse. */ eap->errmsg = (char_u *)N_("E604: :catch after :finally"); give_up = TRUE; } else rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR, &cstack->cs_looplevel); } if (ends_excmd(*eap->arg)) /* no argument, catch all errors */ { pat = (char_u *)".*"; end = NULL; eap->nextcmd = find_nextcmd(eap->arg); } else { pat = eap->arg + 1; end = skip_regexp(pat, *eap->arg, TRUE, NULL); } if (!give_up) { /* * Don't do something when no exception has been thrown or when the * corresponding try block never got active (because of an inactive * surrounding conditional or after an error or interrupt or throw). */ if (!did_throw || !(cstack->cs_flags[idx] & CSF_TRUE)) skip = TRUE; /* * Check for a match only if an exception is thrown but not caught by * a previous ":catch". An exception that has replaced a discarded * exception is not checked (THROWN is not set then). */ if (!skip && (cstack->cs_flags[idx] & CSF_THROWN) && !(cstack->cs_flags[idx] & CSF_CAUGHT)) { if (end != NULL && *end != NUL && !ends_excmd(*skipwhite(end + 1))) { EMSG(_(e_trailing)); return; } /* When debugging or a breakpoint was encountered, display the * debug prompt (if not already done) before checking for a match. * This is a helpful hint for the user when the regular expression * matching fails. Handle a ">quit" debug command as if an * interrupt had occurred before the ":catch". That is, discard * the original exception, replace it by an interrupt exception, * and don't catch it in this try block. */ if (!dbg_check_skipped(eap) || !do_intthrow(cstack)) { /* Terminate the pattern and avoid the 'l' flag in 'cpoptions' * while compiling it. */ if (end != NULL) { save_char = *end; *end = NUL; } save_cpo = p_cpo; p_cpo = (char_u *)""; regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING); regmatch.rm_ic = FALSE; if (end != NULL) *end = save_char; p_cpo = save_cpo; if (regmatch.regprog == NULL) EMSG2(_(e_invarg2), pat); else { /* * Save the value of got_int and reset it. We don't want * a previous interruption cancel matching, only hitting * CTRL-C while matching should abort it. */ prev_got_int = got_int; got_int = FALSE; caught = vim_regexec_nl(&regmatch, current_exception->value, (colnr_T)0); got_int |= prev_got_int; vim_free(regmatch.regprog); } } } if (caught) { /* Make this ":catch" clause active and reset did_emsg, got_int, * and did_throw. Put the exception on the caught stack. */ cstack->cs_flags[idx] |= CSF_ACTIVE | CSF_CAUGHT; did_emsg = got_int = did_throw = FALSE; catch_exception((except_T *)cstack->cs_exception[idx]); /* It's mandatory that the current exception is stored in the cstack * so that it can be discarded at the next ":catch", ":finally", or * ":endtry" or when the catch clause is left by a ":continue", * ":break", ":return", ":finish", error, interrupt, or another * exception. */ if (cstack->cs_exception[cstack->cs_idx] != current_exception) EMSG(_(e_internal)); } else { /* * If there is a preceding catch clause and it caught the exception, * finish the exception now. This happens also after errors except * when this ":catch" was after the ":finally" or not within * a ":try". Make the try conditional inactive so that the * following catch clauses are skipped. On an error or interrupt * after the preceding try block or catch clause was left by * a ":continue", ":break", ":return", or ":finish", discard the * pending action. */ cleanup_conditionals(cstack, CSF_TRY, TRUE); } } if (end != NULL) eap->nextcmd = find_nextcmd(end); } /* * ":finally" */ void ex_finally(eap) exarg_T *eap; { int idx; int skip = FALSE; int pending = CSTP_NONE; struct condstack *cstack = eap->cstack; if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0) eap->errmsg = (char_u *)N_("E606: :finally without :try"); else { if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY)) { eap->errmsg = get_end_emsg(cstack); for (idx = cstack->cs_idx - 1; idx > 0; --idx) if (cstack->cs_flags[idx] & CSF_TRY) break; /* Make this error pending, so that the commands in the following * finally clause can be executed. This overrules also a pending * ":continue", ":break", ":return", or ":finish". */ pending = CSTP_ERROR; } else idx = cstack->cs_idx; if (cstack->cs_flags[idx] & CSF_FINALLY) { /* Give up for a multiple ":finally" and ignore it. */ eap->errmsg = (char_u *)N_("E607: multiple :finally"); return; } rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR, &cstack->cs_looplevel); /* * Don't do something when the corresponding try block never got active * (because of an inactive surrounding conditional or after an error or * interrupt or throw) or for a ":finally" without ":try" or a multiple * ":finally". After every other error (did_emsg or the conditional * errors detected above) or after an interrupt (got_int) or an * exception (did_throw), the finally clause must be executed. */ skip = !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE); if (!skip) { /* When debugging or a breakpoint was encountered, display the * debug prompt (if not already done). The user then knows that the * finally clause is executed. */ if (dbg_check_skipped(eap)) { /* Handle a ">quit" debug command as if an interrupt had * occurred before the ":finally". That is, discard the * original exception and replace it by an interrupt * exception. */ (void)do_intthrow(cstack); } /* * If there is a preceding catch clause and it caught the exception, * finish the exception now. This happens also after errors except * when this is a multiple ":finally" or one not within a ":try". * After an error or interrupt, this also discards a pending * ":continue", ":break", ":finish", or ":return" from the preceding * try block or catch clause. */ cleanup_conditionals(cstack, CSF_TRY, FALSE); /* * Make did_emsg, got_int, did_throw pending. If set, they overrule * a pending ":continue", ":break", ":return", or ":finish". Then * we have particularly to discard a pending return value (as done * by the call to cleanup_conditionals() above when did_emsg or * got_int is set). The pending values are restored by the * ":endtry", except if there is a new error, interrupt, exception, * ":continue", ":break", ":return", or ":finish" in the following * finally clause. A missing ":endwhile", ":endfor" or ":endif" * detected here is treated as if did_emsg and did_throw had * already been set, respectively in case that the error is not * converted to an exception, did_throw had already been unset. * We must not set did_emsg here since that would suppress the * error message. */ if (pending == CSTP_ERROR || did_emsg || got_int || did_throw) { if (cstack->cs_pending[cstack->cs_idx] == CSTP_RETURN) { report_discard_pending(CSTP_RETURN, cstack->cs_rettv[cstack->cs_idx]); discard_pending_return(cstack->cs_rettv[cstack->cs_idx]); } if (pending == CSTP_ERROR && !did_emsg) pending |= (THROW_ON_ERROR) ? CSTP_THROW : 0; else pending |= did_throw ? CSTP_THROW : 0; pending |= did_emsg ? CSTP_ERROR : 0; pending |= got_int ? CSTP_INTERRUPT : 0; cstack->cs_pending[cstack->cs_idx] = pending; /* It's mandatory that the current exception is stored in the * cstack so that it can be rethrown at the ":endtry" or be * discarded if the finally clause is left by a ":continue", * ":break", ":return", ":finish", error, interrupt, or another * exception. When emsg() is called for a missing ":endif" or * a missing ":endwhile"/":endfor" detected here, the * exception will be discarded. */ if (did_throw && cstack->cs_exception[cstack->cs_idx] != current_exception) EMSG(_(e_internal)); } /* * Set CSL_HAD_FINA, so do_cmdline() will reset did_emsg, * got_int, and did_throw and make the finally clause active. * This will happen after emsg() has been called for a missing * ":endif" or a missing ":endwhile"/":endfor" detected here, so * that the following finally clause will be executed even then. */ cstack->cs_lflags |= CSL_HAD_FINA; } } } /* * ":endtry" */ void ex_endtry(eap) exarg_T *eap; { int idx; int skip; int rethrow = FALSE; int pending = CSTP_NONE; void *rettv = NULL; struct condstack *cstack = eap->cstack; if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0) eap->errmsg = (char_u *)N_("E602: :endtry without :try"); else { /* * Don't do something after an error, interrupt or throw in the try * block, catch clause, or finally clause preceding this ":endtry" or * when an error or interrupt occurred after a ":continue", ":break", * ":return", or ":finish" in a try block or catch clause preceding this * ":endtry" or when the try block never got active (because of an * inactive surrounding conditional or after an error or interrupt or * throw) or when there is a surrounding conditional and it has been * made inactive by a ":continue", ":break", ":return", or ":finish" in * the finally clause. The latter case need not be tested since then * anything pending has already been discarded. */ skip = did_emsg || got_int || did_throw || !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE); if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY)) { eap->errmsg = get_end_emsg(cstack); /* Find the matching ":try" and report what's missing. */ idx = cstack->cs_idx; do --idx; while (idx > 0 && !(cstack->cs_flags[idx] & CSF_TRY)); rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR, &cstack->cs_looplevel); skip = TRUE; /* * If an exception is being thrown, discard it to prevent it from * being rethrown at the end of this function. It would be * discarded by the error message, anyway. Resets did_throw. * This does not affect the script termination due to the error * since "trylevel" is decremented after emsg() has been called. */ if (did_throw) discard_current_exception(); } else { idx = cstack->cs_idx; /* * If we stopped with the exception currently being thrown at this * try conditional since we didn't know that it doesn't have * a finally clause, we need to rethrow it after closing the try * conditional. */ if (did_throw && (cstack->cs_flags[idx] & CSF_TRUE) && !(cstack->cs_flags[idx] & CSF_FINALLY)) rethrow = TRUE; } /* If there was no finally clause, show the user when debugging or * a breakpoint was encountered that the end of the try conditional has * been reached: display the debug prompt (if not already done). Do * this on normal control flow or when an exception was thrown, but not * on an interrupt or error not converted to an exception or when * a ":break", ":continue", ":return", or ":finish" is pending. These * actions are carried out immediately. */ if ((rethrow || (!skip && !(cstack->cs_flags[idx] & CSF_FINALLY) && !cstack->cs_pending[idx])) && dbg_check_skipped(eap)) { /* Handle a ">quit" debug command as if an interrupt had occurred * before the ":endtry". That is, throw an interrupt exception and * set "skip" and "rethrow". */ if (got_int) { skip = TRUE; (void)do_intthrow(cstack); /* The do_intthrow() call may have reset did_throw or * cstack->cs_pending[idx].*/ rethrow = FALSE; if (did_throw && !(cstack->cs_flags[idx] & CSF_FINALLY)) rethrow = TRUE; } } /* * If a ":return" is pending, we need to resume it after closing the * try conditional; remember the return value. If there was a finally * clause making an exception pending, we need to rethrow it. Make it * the exception currently being thrown. */ if (!skip) { pending = cstack->cs_pending[idx]; cstack->cs_pending[idx] = CSTP_NONE; if (pending == CSTP_RETURN) rettv = cstack->cs_rettv[idx]; else if (pending & CSTP_THROW) current_exception = cstack->cs_exception[idx]; } /* * Discard anything pending on an error, interrupt, or throw in the * finally clause. If there was no ":finally", discard a pending * ":continue", ":break", ":return", or ":finish" if an error or * interrupt occurred afterwards, but before the ":endtry" was reached. * If an exception was caught by the last of the catch clauses and there * was no finally clause, finish the exception now. This happens also * after errors except when this ":endtry" is not within a ":try". * Restore "emsg_silent" if it has been reset by this try conditional. */ (void)cleanup_conditionals(cstack, CSF_TRY | CSF_SILENT, TRUE); --cstack->cs_idx; --cstack->cs_trylevel; if (!skip) { report_resume_pending(pending, (pending == CSTP_RETURN) ? rettv : (pending & CSTP_THROW) ? (void *)current_exception : NULL); switch (pending) { case CSTP_NONE: break; /* Reactivate a pending ":continue", ":break", ":return", * ":finish" from the try block or a catch clause of this try * conditional. This is skipped, if there was an error in an * (unskipped) conditional command or an interrupt afterwards * or if the finally clause is present and executed a new error, * interrupt, throw, ":continue", ":break", ":return", or * ":finish". */ case CSTP_CONTINUE: ex_continue(eap); break; case CSTP_BREAK: ex_break(eap); break; case CSTP_RETURN: do_return(eap, FALSE, FALSE, rettv); break; case CSTP_FINISH: do_finish(eap, FALSE); break; /* When the finally clause was entered due to an error, * interrupt or throw (as opposed to a ":continue", ":break", * ":return", or ":finish"), restore the pending values of * did_emsg, got_int, and did_throw. This is skipped, if there * was a new error, interrupt, throw, ":continue", ":break", * ":return", or ":finish". in the finally clause. */ default: if (pending & CSTP_ERROR) did_emsg = TRUE; if (pending & CSTP_INTERRUPT) got_int = TRUE; if (pending & CSTP_THROW) rethrow = TRUE; break; } } if (rethrow) /* Rethrow the current exception (within this cstack). */ do_throw(cstack); } } /* * enter_cleanup() and leave_cleanup() * * Functions to be called before/after invoking a sequence of autocommands for * cleanup for a failed command. (Failure means here that a call to emsg() * has been made, an interrupt occurred, or there is an uncaught exception * from a previous autocommand execution of the same command.) * * Call enter_cleanup() with a pointer to a cleanup_T and pass the same * pointer to leave_cleanup(). The cleanup_T structure stores the pending * error/interrupt/exception state. */ /* * This function works a bit like ex_finally() except that there was not * actually an extra try block around the part that failed and an error or * interrupt has not (yet) been converted to an exception. This function * saves the error/interrupt/ exception state and prepares for the call to * do_cmdline() that is going to be made for the cleanup autocommand * execution. */ void enter_cleanup(csp) cleanup_T *csp; { int pending = CSTP_NONE; /* * Postpone did_emsg, got_int, did_throw. The pending values will be * restored by leave_cleanup() except if there was an aborting error, * interrupt, or uncaught exception after this function ends. */ if (did_emsg || got_int || did_throw || need_rethrow) { csp->pending = (did_emsg ? CSTP_ERROR : 0) | (got_int ? CSTP_INTERRUPT : 0) | (did_throw ? CSTP_THROW : 0) | (need_rethrow ? CSTP_THROW : 0); /* If we are currently throwing an exception (did_throw), save it as * well. On an error not yet converted to an exception, update * "force_abort" and reset "cause_abort" (as do_errthrow() would do). * This is needed for the do_cmdline() call that is going to be made * for autocommand execution. We need not save *msg_list because * there is an extra instance for every call of do_cmdline(), anyway. */ if (did_throw || need_rethrow) csp->exception = current_exception; else { csp->exception = NULL; if (did_emsg) { force_abort |= cause_abort; cause_abort = FALSE; } } did_emsg = got_int = did_throw = need_rethrow = FALSE; /* Report if required by the 'verbose' option or when debugging. */ report_make_pending(pending, csp->exception); } else { csp->pending = CSTP_NONE; csp->exception = NULL; } } /* * See comment above enter_cleanup() for how this function is used. * * This function is a bit like ex_endtry() except that there was not actually * an extra try block around the part that failed and an error or interrupt * had not (yet) been converted to an exception when the cleanup autocommand * sequence was invoked. * * This function has to be called with the address of the cleanup_T structure * filled by enter_cleanup() as an argument; it restores the error/interrupt/ * exception state saved by that function - except there was an aborting * error, an interrupt or an uncaught exception during execution of the * cleanup autocommands. In the latter case, the saved error/interrupt/ * exception state is discarded. */ void leave_cleanup(csp) cleanup_T *csp; { int pending = csp->pending; if (pending == CSTP_NONE) /* nothing to do */ return; /* If there was an aborting error, an interrupt, or an uncaught exception * after the corresponding call to enter_cleanup(), discard what has been * made pending by it. Report this to the user if required by the * 'verbose' option or when debugging. */ if (aborting() || need_rethrow) { if (pending & CSTP_THROW) /* Cancel the pending exception (includes report). */ discard_exception((except_T *)csp->exception, FALSE); else report_discard_pending(pending, NULL); /* If an error was about to be converted to an exception when * enter_cleanup() was called, free the message list. */ if (msg_list != NULL) { free_msglist(*msg_list); *msg_list = NULL; } } /* * If there was no new error, interrupt, or throw between the calls * to enter_cleanup() and leave_cleanup(), restore the pending * error/interrupt/exception state. */ else { /* * If there was an exception being thrown when enter_cleanup() was * called, we need to rethrow it. Make it the exception currently * being thrown. */ if (pending & CSTP_THROW) current_exception = csp->exception; /* * If an error was about to be converted to an exception when * enter_cleanup() was called, let "cause_abort" take the part of * "force_abort" (as done by cause_errthrow()). */ else if (pending & CSTP_ERROR) { cause_abort = force_abort; force_abort = FALSE; } /* * Restore the pending values of did_emsg, got_int, and did_throw. */ if (pending & CSTP_ERROR) did_emsg = TRUE; if (pending & CSTP_INTERRUPT) got_int = TRUE; if (pending & CSTP_THROW) need_rethrow = TRUE; /* did_throw will be set by do_one_cmd() */ /* Report if required by the 'verbose' option or when debugging. */ report_resume_pending(pending, (pending & CSTP_THROW) ? (void *)current_exception : NULL); } } /* * Make conditionals inactive and discard what's pending in finally clauses * until the conditional type searched for or a try conditional not in its * finally clause is reached. If this is in an active catch clause, finish * the caught exception. * Return the cstack index where the search stopped. * Values used for "searched_cond" are (CSF_WHILE | CSF_FOR) or CSF_TRY or 0, * the latter meaning the innermost try conditional not in its finally clause. * "inclusive" tells whether the conditional searched for should be made * inactive itself (a try conditional not in its finally claused possibly find * before is always made inactive). If "inclusive" is TRUE and * "searched_cond" is CSF_TRY|CSF_SILENT, the saved former value of * "emsg_silent", if reset when the try conditional finally reached was * entered, is restored (unsed by ex_endtry()). This is normally done only * when such a try conditional is left. */ int cleanup_conditionals(cstack, searched_cond, inclusive) struct condstack *cstack; int searched_cond; int inclusive; { int idx; int stop = FALSE; for (idx = cstack->cs_idx; idx >= 0; --idx) { if (cstack->cs_flags[idx] & CSF_TRY) { /* * Discard anything pending in a finally clause and continue the * search. There may also be a pending ":continue", ":break", * ":return", or ":finish" before the finally clause. We must not * discard it, unless an error or interrupt occurred afterwards. */ if (did_emsg || got_int || (cstack->cs_flags[idx] & CSF_FINALLY)) { switch (cstack->cs_pending[idx]) { case CSTP_NONE: break; case CSTP_CONTINUE: case CSTP_BREAK: case CSTP_FINISH: report_discard_pending(cstack->cs_pending[idx], NULL); cstack->cs_pending[idx] = CSTP_NONE; break; case CSTP_RETURN: report_discard_pending(CSTP_RETURN, cstack->cs_rettv[idx]); discard_pending_return(cstack->cs_rettv[idx]); cstack->cs_pending[idx] = CSTP_NONE; break; default: if (cstack->cs_flags[idx] & CSF_FINALLY) { if (cstack->cs_pending[idx] & CSTP_THROW) { /* Cancel the pending exception. This is in the * finally clause, so that the stack of the * caught exceptions is not involved. */ discard_exception((except_T *) cstack->cs_exception[idx], FALSE); } else report_discard_pending(cstack->cs_pending[idx], NULL); cstack->cs_pending[idx] = CSTP_NONE; } break; } } /* * Stop at a try conditional not in its finally clause. If this try * conditional is in an active catch clause, finish the caught * exception. */ if (!(cstack->cs_flags[idx] & CSF_FINALLY)) { if ((cstack->cs_flags[idx] & CSF_ACTIVE) && (cstack->cs_flags[idx] & CSF_CAUGHT)) finish_exception((except_T *)cstack->cs_exception[idx]); /* Stop at this try conditional - except the try block never * got active (because of an inactive surrounding conditional * or when the ":try" appeared after an error or interrupt or * throw). */ if (cstack->cs_flags[idx] & CSF_TRUE) { if (searched_cond == 0 && !inclusive) break; stop = TRUE; } } } /* Stop on the searched conditional type (even when the surrounding * conditional is not active or something has been made pending). * If "inclusive" is TRUE and "searched_cond" is CSF_TRY|CSF_SILENT, * check first whether "emsg_silent" needs to be restored. */ if (cstack->cs_flags[idx] & searched_cond) { if (!inclusive) break; stop = TRUE; } cstack->cs_flags[idx] &= ~CSF_ACTIVE; if (stop && searched_cond != (CSF_TRY | CSF_SILENT)) break; /* * When leaving a try conditional that reset "emsg_silent" on its * entry after saving the original value, restore that value here and * free the memory used to store it. */ if ((cstack->cs_flags[idx] & CSF_TRY) && (cstack->cs_flags[idx] & CSF_SILENT)) { eslist_T *elem; elem = cstack->cs_emsg_silent_list; cstack->cs_emsg_silent_list = elem->next; emsg_silent = elem->saved_emsg_silent; vim_free(elem); cstack->cs_flags[idx] &= ~CSF_SILENT; } if (stop) break; } return idx; } /* * Return an appropriate error message for a missing endwhile/endfor/endif. */ static char_u * get_end_emsg(cstack) struct condstack *cstack; { if (cstack->cs_flags[cstack->cs_idx] & CSF_WHILE) return e_endwhile; if (cstack->cs_flags[cstack->cs_idx] & CSF_FOR) return e_endfor; return e_endif; } /* * Rewind conditionals until index "idx" is reached. "cond_type" and * "cond_level" specify a conditional type and the address of a level variable * which is to be decremented with each skipped conditional of the specified * type. * Also free "for info" structures where needed. */ void rewind_conditionals(cstack, idx, cond_type, cond_level) struct condstack *cstack; int idx; int cond_type; int *cond_level; { while (cstack->cs_idx > idx) { if (cstack->cs_flags[cstack->cs_idx] & cond_type) --*cond_level; if (cstack->cs_flags[cstack->cs_idx] & CSF_FOR) free_for_info(cstack->cs_forinfo[cstack->cs_idx]); --cstack->cs_idx; } } /* * ":endfunction" when not after a ":function" */ void ex_endfunction(eap) exarg_T *eap UNUSED; { EMSG(_("E193: :endfunction not inside a function")); } /* * Return TRUE if the string "p" looks like a ":while" or ":for" command. */ int has_loop_cmd(p) char_u *p; { int len; /* skip modifiers, white space and ':' */ for (;;) { while (*p == ' ' || *p == '\t' || *p == ':') ++p; len = modifier_len(p); if (len == 0) break; p += len; } if ((p[0] == 'w' && p[1] == 'h') || (p[0] == 'f' && p[1] == 'o' && p[2] == 'r')) return TRUE; return FALSE; } #endif /* FEAT_EVAL */
zyz2011-vim
src/ex_eval.c
C
gpl2
68,914
@echo off rem To be used on MS-Windows for Visual C++ 2008 Express Edition rem aka Microsoft Visual Studio 9.0. rem See INSTALLpc.txt for information. @echo on call "%VS90COMNTOOLS%%vsvars32.bat"
zyz2011-vim
src/msvc2008.bat
Batchfile
gpl2
199
/* vi:set ts=8 sw=8: * * VIM - Vi IMproved by Bram Moolenaar * Visual Workshop integration by Gordon Prieur * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Integration with Sun Workshop. * * This file should not change much, it's also used by other editors that * connect to Workshop. Consider changing workshop.c instead. */ /* -> consider using MakeSelectionVisible instead of gotoLine hacks to show the line properly -> consider using glue instead of our own message wrapping functions (but can only use glue if we don't have to distribute source) */ #include "vim.h" #include <stdio.h> #include <stdlib.h> #ifdef INET_SOCKETS #include <netdb.h> #include <netinet/in.h> #else #include <sys/un.h> #endif #include <sys/types.h> #include <sys/socket.h> #include <sys/param.h> #ifdef HAVE_LIBGEN_H # include <libgen.h> #endif #include <unistd.h> #include <string.h> #include <X11/Intrinsic.h> #include <Xm/Xm.h> #include <Xm/AtomMgr.h> #include <Xm/PushB.h> #ifdef HAVE_X11_XPM_H # include <X11/xpm.h> #else # ifdef HAVE_XM_XPMP_H # include <Xm/XpmP.h> # endif #endif #ifdef HAVE_UTIL_DEBUG_H # include <util/debug.h> #endif #ifdef HAVE_UTIL_MSGI18N_H # include <util/msgi18n.h> #endif #include "integration.h" /* <EditPlugin/integration.h> */ #ifdef HAVE_FRAME_H # include <frame.h> #endif #ifndef MAX # define MAX(a, b) (a) > (b) ? (a) : (b) #endif #ifndef NOCATGETS # define NOCATGETS(x) x #endif /* Functions private to this file */ static void workshop_connection_closed(void); static void messageFromEserve(XtPointer clientData, int *dum1, XtInputId *dum2); static void workshop_disconnect(void); static void workshop_sensitivity(int num, char *table); static void adjust_sign_name(char *filename); static void process_menuItem(char *); static void process_toolbarButton(char *); static void workshop_set_option_first(char *name, char *value); static size_t dummy; /* to ignore return value of write() */ #define CMDBUFSIZ 2048 #ifdef DEBUG static FILE *dfd; static void pldebug(char *, ...); static void unrecognised_message(char *); #define HANDLE_ERRORS(cmd) else unrecognised_message(cmd); #else #define HANDLE_ERRORS(cmd) #endif /* * Version number of the protocol between an editor and eserve. * This number should be incremented when the protocol * is changed. */ #define PROTOCOL_VERSION "4.0.0" static int sd = -1; static XtInputId inputHandler; /* Cookie for input */ Boolean save_files = True; /* When true, save all files before build actions */ void workshop_connection_closed(void) { /* * socket closed on other end */ XtRemoveInput(inputHandler); inputHandler = 0; sd = -1; } static char * getCommand(void) { int len; /* length of this command */ char lenbuf[7]; /* get the length string here */ char *newcb; /* used to realloc cmdbuf */ static char *cmdbuf;/* get the command string here */ static int cbsize;/* size of cmdbuf */ if ((len = read(sd, &lenbuf, 6)) == 6) { lenbuf[6] = 0; /* Terminate buffer such that atoi() works right */ len = atoi(lenbuf); if (cbsize < (len + 1)) { newcb = (char *) realloc(cmdbuf, MAX((len + 256), CMDBUFSIZ)); if (newcb != NULL) { cmdbuf = newcb; cbsize = MAX((len + 256), CMDBUFSIZ); } } if (cbsize >= len && (len = read(sd, cmdbuf, len)) > 0) { cmdbuf[len] = 0; return cmdbuf; } else { return NULL; } } else { if (len == 0) { /* EOF */ workshop_connection_closed(); } return NULL; } } void messageFromEserve(XtPointer clientData UNUSED, int *dum1 UNUSED, XtInputId *dum2 UNUSED) { char *cmd; /* the 1st word of the command */ cmd = getCommand(); if (cmd == NULL) { /* We're being shut down by eserve and the "quit" message * didn't arrive before the socket connection got closed */ return; } #ifdef DEBUG pldebug("%s\n", cmd); #endif switch (*cmd) { case 'a': if (cmd[1] == 'c' && strncmp(cmd, NOCATGETS("ack "), 4) == 0) { int ackNum; char buf[20]; ackNum = atoi(&cmd[4]); vim_snprintf(buf, sizeof(buf), NOCATGETS("ack %d\n"), ackNum); dummy = write(sd, buf, strlen(buf)); } else if (strncmp(cmd, NOCATGETS("addMarkType "), 12) == 0) { int idx; char *color; char *sign; idx = atoi(strtok(&cmd[12], " ")); color = strtok(NULL, NOCATGETS("\001")); sign = strtok(NULL, NOCATGETS("\001")); /* Skip space that separates names */ if (color) { color++; } if (sign) { sign++; } /* Change sign name to accommodate a different size? */ adjust_sign_name(sign); workshop_add_mark_type(idx, color, sign); } HANDLE_ERRORS(cmd); break; case 'b': if (strncmp(cmd, NOCATGETS("balloon "), 8) == 0) { char *tip; tip = strtok(&cmd[8], NOCATGETS("\001")); workshop_show_balloon_tip(tip); } HANDLE_ERRORS(cmd); break; case 'c': if (strncmp(cmd, NOCATGETS("changeMarkType "), 15) == 0) { char *file; int markId; int type; file = strtok(&cmd[15], " "); markId = atoi(strtok(NULL, " ")); type = atoi(strtok(NULL, " ")); workshop_change_mark_type(file, markId, type); } HANDLE_ERRORS(cmd); break; case 'd': if (strncmp(cmd, NOCATGETS("deleteMark "), 11) == 0) { char *file; int markId; file = strtok(&cmd[11], " "); markId = atoi(strtok(NULL, " ")); workshop_delete_mark(file, markId); } HANDLE_ERRORS(cmd); break; case 'f': if (cmd[1] == 'o' && strncmp(cmd, NOCATGETS("footerMsg "), 10) == 0) { int severity; char *message; severity = atoi(strtok(&cmd[10], " ")); message = strtok(NULL, NOCATGETS("\001")); workshop_footer_message(message, severity); } else if (strncmp(cmd, NOCATGETS("frontFile "), 10) == 0) { char *file; file = strtok(&cmd[10], " "); workshop_front_file(file); } HANDLE_ERRORS(cmd); break; case 'g': if (cmd[1] == 'e' && strncmp(cmd, NOCATGETS("getMarkLine "), 12) == 0) { char *file; int markid; int line; char buf[100]; file = strtok(&cmd[12], " "); markid = atoi(strtok(NULL, " ")); line = workshop_get_mark_lineno(file, markid); vim_snprintf(buf, sizeof(buf), NOCATGETS("markLine %s %d %d\n"), file, markid, line); dummy = write(sd, buf, strlen(buf)); } else if (cmd[1] == 'o' && cmd[4] == 'L' && strncmp(cmd, NOCATGETS("gotoLine "), 9) == 0) { char *file; int lineno; file = strtok(&cmd[9], " "); lineno = atoi(strtok(NULL, " ")); workshop_goto_line(file, lineno); } else if (strncmp(cmd, NOCATGETS("gotoMark "), 9) == 0) { char *file; int markId; char *message; file = strtok(&cmd[9], " "); markId = atoi(strtok(NULL, " ")); message = strtok(NULL, NOCATGETS("\001")); workshop_goto_mark(file, markId, message); #ifdef NOHANDS_SUPPORT_FUNCTIONS } else if (strcmp(cmd, NOCATGETS("getCurrentFile")) == 0) { char *f = workshop_test_getcurrentfile(); char buffer[2*MAXPATHLEN]; vim_snprintf(buffer, sizeof(buffer), NOCATGETS("currentFile %d %s"), f ? strlen(f) : 0, f ? f : ""); workshop_send_message(buffer); } else if (strcmp(cmd, NOCATGETS("getCursorRow")) == 0) { int row = workshop_test_getcursorrow(); char buffer[2*MAXPATHLEN]; vim_snprintf(buffer, sizeof(buffer), NOCATGETS("cursorRow %d"), row); workshop_send_message(buffer); } else if (strcmp(cmd, NOCATGETS("getCursorCol")) == 0) { int col = workshop_test_getcursorcol(); char buffer[2*MAXPATHLEN]; vim_snprintf(buffer, sizeof(buffer), NOCATGETS("cursorCol %d"), col); workshop_send_message(buffer); } else if (strcmp(cmd, NOCATGETS("getCursorRowText")) == 0) { char *t = workshop_test_getcursorrowtext(); char buffer[2*MAXPATHLEN]; vim_snprintf(buffer, sizeof(buffer), NOCATGETS("cursorRowText %d %s"), t ? strlen(t) : 0, t ? t : ""); workshop_send_message(buffer); } else if (strcmp(cmd, NOCATGETS("getSelectedText")) == 0) { char *t = workshop_test_getselectedtext(); char buffer[2*MAXPATHLEN]; vim_snprintf(buffer, sizeof(buffer), NOCATGETS("selectedText %d %s"), t ? strlen(t) : 0, t ? t : ""); workshop_send_message(buffer); #endif } HANDLE_ERRORS(cmd); break; case 'l': if (strncmp(cmd, NOCATGETS("loadFile "), 9) == 0) { char *file; int line; char *frameid; file = strtok(&cmd[9], " "); line = atoi(strtok(NULL, " ")); frameid = strtok(NULL, " "); workshop_load_file(file, line, frameid); } HANDLE_ERRORS(cmd); break; case 'm': /* Menu, minimize, maximize */ if (cmd[1] == 'e' && cmd[4] == 'B' && strncmp(cmd, NOCATGETS("menuBegin "), 10) == 0) { workshop_menu_begin(&cmd[10]); } else if (cmd[1] == 'e' && cmd[4] == 'I' && strncmp(cmd, NOCATGETS("menuItem "), 9) == 0) { process_menuItem(cmd); } else if (cmd[1] == 'e' && cmd[4] == 'E' && strcmp(cmd, NOCATGETS("menuEnd")) == 0) { workshop_menu_end(); } else if (cmd[1] == 'a' && strcmp(cmd, NOCATGETS("maximize")) == 0) { workshop_maximize(); } else if (strcmp(cmd, NOCATGETS("minimize")) == 0) { workshop_minimize(); } HANDLE_ERRORS(cmd); break; case 'o': if (cmd[1] == 'p' && strcmp(cmd, NOCATGETS("option"))) { char *name; char *value; name = strtok(&cmd[7], " "); value = strtok(NULL, " "); workshop_set_option_first(name, value); } HANDLE_ERRORS(cmd); break; case 'p': if (strcmp(cmd, NOCATGETS("ping")) == 0) { #if 0 int pingNum; pingNum = atoi(&cmd[5]); workshop_send_ack(ackNum); /* WHAT DO I DO HERE? */ #endif } HANDLE_ERRORS(cmd); break; case 'q': if (strncmp(cmd, NOCATGETS("quit"), 4) == 0) { /* Close the connection. It's important to do * that now, since workshop_quit might be * looking at open files. For example, if you * have modified one of the files without * saving, NEdit will ask you what you want to * do, and spin loop by calling * XtAppProcessEvent while waiting for your * reply. In this case, if we still have an * input handler and the socket has been * closed on the other side when eserve * expired, we will hang in IoWait. */ workshop_disconnect(); workshop_quit(); } HANDLE_ERRORS(cmd); break; case 'r': if (cmd[1] == 'e' && strncmp(cmd, NOCATGETS("reloadFile "), 11) == 0) { char *file; int line; file = strtok(&cmd[11], " "); line = atoi(strtok(NULL, " ")); workshop_reload_file(file, line); } HANDLE_ERRORS(cmd); break; case 's': if (cmd[1] == 'e' && cmd[2] == 't' && strncmp(cmd, NOCATGETS("setMark "), 8) == 0) { char *file; int line; int markId; int type; file = strtok(&cmd[8], " "); line = atoi(strtok(NULL, " ")); markId = atoi(strtok(NULL, " ")); type = atoi(strtok(NULL, " ")); workshop_set_mark(file, line, markId, type); } else if (cmd[1] == 'h' && strncmp(cmd, NOCATGETS("showFile "), 9) == 0) { workshop_show_file(&cmd[9]); } else if (cmd[1] == 'u' && strncmp(cmd, NOCATGETS("subMenu "), 8) == 0) { char *label; label = strtok(&cmd[8], NOCATGETS("\001")); workshop_submenu_begin(label); } else if (cmd[1] == 'u' && strcmp(cmd, NOCATGETS("subMenuEnd")) == 0) { workshop_submenu_end(); } else if (cmd[1] == 'e' && cmd[2] == 'n' && strncmp(cmd, NOCATGETS("sensitivity "), 12) == 0) { int num; char *bracket; char *table; num = atoi(strtok(&cmd[12], " ")); bracket = strtok(NULL, " "); if (*bracket != '[') { fprintf(stderr, NOCATGETS("Parsing " "error for sensitivity\n")); } else { table = strtok(NULL, NOCATGETS("]")); workshop_sensitivity(num, table); } } else if (cmd[1] == 'e' && cmd[2] == 'n' && cmd[3] == 'd' && strncmp(cmd, NOCATGETS("sendVerb "), 9) == 0) { /* Send the given verb back (used for the * debug.lineno callback (such that other tools * can obtain the position coordinates or the * selection) */ char *verb; verb = strtok(&cmd[9], " "); workshop_perform_verb(verb, NULL); } else if (cmd[1] == 'a' && strncmp(cmd, NOCATGETS("saveFile "), 9) == 0) { workshop_save_file(&cmd[9]); #ifdef NOHANDS_SUPPORT_FUNCTIONS } else if (strncmp(cmd, NOCATGETS("saveSensitivity "), 16) == 0) { char *file; file = strtok(&cmd[16], " "); workshop_save_sensitivity(file); #endif } HANDLE_ERRORS(cmd); break; case 't': /* Toolbar */ if (cmd[8] == 'e' && strncmp(cmd, NOCATGETS("toolbarBegin"), 12) == 0) { workshop_toolbar_begin(); } else if (cmd[8] == 'u' && strncmp(cmd, NOCATGETS("toolbarButton"), 13) == 0) { process_toolbarButton(cmd); } else if (cmd[7] == 'E' && strcmp(cmd, NOCATGETS("toolbarEnd")) == 0) { workshop_toolbar_end(); } HANDLE_ERRORS(cmd); break; #ifdef DEBUG default: unrecognised_message(cmd); break; #endif } } static void process_menuItem( char *cmd) { char *label = strtok(&cmd[9], NOCATGETS("\001")); char *verb = strtok(NULL, NOCATGETS("\001")); char *acc = strtok(NULL, NOCATGETS("\001")); char *accText = strtok(NULL, NOCATGETS("\001")); char *name = strtok(NULL, NOCATGETS("\001")); char *sense = strtok(NULL, NOCATGETS("\n")); char *filepos = strtok(NULL, NOCATGETS("\n")); if (*acc == '-') { acc = NULL; } if (*accText == '-') { accText = NULL; } workshop_menu_item(label, verb, acc, accText, name, filepos, sense); } static void process_toolbarButton( char *cmd) /* button definition */ { char *label = strtok(&cmd[14], NOCATGETS("\001")); char *verb = strtok(NULL, NOCATGETS("\001")); char *senseVerb = strtok(NULL, NOCATGETS("\001")); char *filepos = strtok(NULL, NOCATGETS("\001")); char *help = strtok(NULL, NOCATGETS("\001")); char *sense = strtok(NULL, NOCATGETS("\001")); char *file = strtok(NULL, NOCATGETS("\001")); char *left = strtok(NULL, NOCATGETS("\n")); if (!strcmp(label, NOCATGETS("-"))) { label = NULL; } if (!strcmp(help, NOCATGETS("-"))) { help = NULL; } if (!strcmp(file, NOCATGETS("-"))) { file = NULL; } if (!strcmp(senseVerb, NOCATGETS("-"))) { senseVerb = NULL; } workshop_toolbar_button(label, verb, senseVerb, filepos, help, sense, file, left); } #ifdef DEBUG void unrecognised_message( char *cmd) { pldebug("Unrecognised eserve message:\n\t%s\n", cmd); /* abort(); */ } #endif /* Change sign name to accommodate a different size: * Create the filename based on the height. The filename format * of multisize icons are: * x.xpm : largest icon * x1.xpm : smaller icon * x2.xpm : smallest icon */ void adjust_sign_name(char *filename) { char *s; static int fontSize = -1; if (fontSize == -1) fontSize = workshop_get_font_height(); if (fontSize == 0) return; if (filename[0] == '-') return; /* This is ugly: later we should instead pass the fontheight over * to eserve on startup and let eserve just send the right filenames * to us in the first place * I know that the filename will end with 1.xpm (see * GuiEditor.cc`LispPrintSign if you wonder why) */ s = filename+strlen(filename)-5; if (fontSize <= 11) strcpy(s, "2.xpm"); else if (fontSize <= 15) strcpy(s, "1.xpm"); else strcpy(s, ".xpm"); } #if 0 /* Were we invoked by WorkShop? This function can be used early during startup if you want to do things differently if the editor is started standalone or in WorkShop mode. For example, in standalone mode you may not want to add a footer/message area or a sign gutter. */ int workshop_invoked() { static int result = -1; if (result == -1) { result = (getenv(NOCATGETS("SPRO_EDITOR_SOCKET")) != NULL); } return result; } #endif /* Connect back to eserve */ void workshop_connect(XtAppContext context) { #ifdef INET_SOCKETS struct sockaddr_in server; struct hostent * host; int port; #else struct sockaddr_un server; #endif char buf[32]; char * address; #ifdef DEBUG char *file; #endif address = getenv(NOCATGETS("SPRO_EDITOR_SOCKET")); if (address == NULL) { return; } #ifdef INET_SOCKETS port = atoi(address); if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { PERROR(NOCATGETS("workshop_connect")); return; } /* Get the server internet address and put into addr structure */ /* fill in the socket address structure and connect to server */ vim_memset((char *)&server, '\0', sizeof(server)); server.sin_family = AF_INET; server.sin_port = port; if ((host = gethostbyname(NOCATGETS("localhost"))) == NULL) { PERROR(NOCATGETS("gethostbyname")); sd = -1; return; } memcpy((char *)&server.sin_addr, host->h_addr, host->h_length); #else if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { PERROR(NOCATGETS("workshop_connect")); return; } server.sun_family = AF_UNIX; strcpy(server.sun_path, address); #endif /* Connect to server */ if (connect(sd, (struct sockaddr *)&server, sizeof(server))) { if (errno == ECONNREFUSED) { close(sd); #ifdef INET_SOCKETS if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { PERROR(NOCATGETS("workshop_connect")); return; } #else if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { PERROR(NOCATGETS("workshop_connect")); return; } #endif if (connect(sd, (struct sockaddr *)&server, sizeof(server))) { PERROR(NOCATGETS("workshop_connect")); return; } } else { PERROR(NOCATGETS("workshop_connect")); return; } } /* tell notifier we are interested in being called * when there is input on the editor connection socket */ inputHandler = XtAppAddInput(context, sd, (XtPointer) XtInputReadMask, messageFromEserve, NULL); #ifdef DEBUG if ((file = getenv(NOCATGETS("SPRO_PLUGIN_DEBUG"))) != NULL) { char buf[BUFSIZ]; unlink(file); vim_snprintf(buf, sizeof(buf), "date > %s", file); system(buf); dfd = fopen(file, "a"); } else { dfd = NULL; } #endif vim_snprintf(buf, sizeof(buf), NOCATGETS("connected %s %s %s\n"), workshop_get_editor_name(), PROTOCOL_VERSION, workshop_get_editor_version()); dummy = write(sd, buf, strlen(buf)); vim_snprintf(buf, sizeof(buf), NOCATGETS("ack 1\n")); dummy = write(sd, buf, strlen(buf)); } void workshop_disconnect() { /* Probably need to send some message here */ /* * socket closed on other end */ XtRemoveInput(inputHandler); close(sd); inputHandler = 0; sd = -1; } /* * Utility functions */ /* Minimize and maximize shells. From libutil's shell.cc. */ /* utility functions from libutil's shell.cc */ static Boolean isWindowMapped(Display *display, Window win) { XWindowAttributes winAttrs; XGetWindowAttributes(display, win, &winAttrs); if (winAttrs.map_state == IsViewable) { return(True); } else { return(False); } } static Boolean isMapped(Widget widget) { if (widget == NULL) { return(False); } if (XtIsRealized(widget) == False) { return(False); } return(isWindowMapped(XtDisplay(widget), XtWindow(widget))); } static Boolean widgetIsIconified( Widget w) { Atom wm_state; Atom act_type; /* actual Atom type returned */ int act_fmt; /* actual format returned */ u_long nitems_ret; /* number of items returned */ u_long bytes_after; /* number of bytes remaining */ u_long *property; /* actual property returned */ /* * If a window is iconified its WM_STATE is set to IconicState. See * ICCCM Version 2.0, section 4.1.3.1 for more details. */ wm_state = XmInternAtom(XtDisplay(w), NOCATGETS("WM_STATE"), False); if (XtWindow(w) != 0) { /* only check if window exists! */ XGetWindowProperty(XtDisplay(w), XtWindow(w), wm_state, 0L, 2L, False, AnyPropertyType, &act_type, &act_fmt, &nitems_ret, &bytes_after, (u_char **) &property); if (nitems_ret == 2 && property[0] == IconicState) { return True; } } return False; } /* end widgetIsIconified */ void workshop_minimize_shell(Widget shell) { if (shell != NULL && XtIsObject(shell) && XtIsRealized(shell) == True) { if (isMapped(shell) == True) { XIconifyWindow(XtDisplay(shell), XtWindow(shell), XScreenNumberOfScreen(XtScreen(shell))); } XtVaSetValues(shell, XmNiconic, True, NULL); } } void workshop_maximize_shell(Widget shell) { if (shell != NULL && XtIsRealized(shell) == True && widgetIsIconified(shell) == True && isMapped(shell) == False) { XtMapWidget(shell); /* This used to be XtPopdown(shell); XtPopup(shell, XtGrabNone); However, I found that that would drop any transient windows that had been iconified with the window. According to the ICCCM, XtMapWidget should be used to bring a window from Iconic to Normal state. However, Rich Mauri did a lot of work on this during Bart, and found that XtPopDown,XtPopup was required to fix several bugs involving multiple CDE workspaces. I've tested it now and things seem to work fine but I'm leaving this note for history in case this needs to be revisited. */ } } Boolean workshop_get_width_height(int *width, int *height) { static int wid = 0; static int hgt = 0; static Boolean firstTime = True; static Boolean success = False; if (firstTime) { char *settings; settings = getenv(NOCATGETS("SPRO_GUI_WIDTH_HEIGHT")); if (settings != NULL) { wid = atoi(settings); settings = strrchr(settings, ':'); if (settings++ != NULL) { hgt = atoi(settings); } if (wid > 0 && hgt > 0) { success = True; } firstTime = False; } } if (success) { *width = wid; *height = hgt; } return success; } /* * Toolbar code */ void workshop_sensitivity(int num, char *table) { /* build up a verb table */ VerbSense *vs; int i; char *s; if ((num < 1) || (num > 500)) { return; } vs = (VerbSense *)malloc((num+1)*sizeof(VerbSense)); /* Point to the individual names (destroys the table string, but * that's okay -- this is more efficient than duplicating strings) */ s = table; for (i = 0; i < num; i++) { while (*s == ' ') { s++; } vs[i].verb = s; while (*s && (*s != ' ') && (*s != '\001')) { s++; } if (*s == 0) { vs[i].verb = NULL; break; } if (*s == '\001') { *s = 0; s++; } *s = 0; s++; while (*s == ' ') { s++; } if (*s == '1') { vs[i].sense = 1; } else { vs[i].sense = 0; } s++; } vs[i].verb = NULL; workshop_frame_sensitivities(vs); free(vs); } /* * Options code */ /* Set an editor option. * IGNORE an option if you do not recognize it. */ void workshop_set_option_first(char *name, char *value) { /* Currently value can only be on/off. This may change later (for * example to set an option like "balloon evaluate delay", but * for now just convert it into a boolean */ Boolean on = !strcmp(value, "on"); if (!strcmp(name, "workshopkeys")) { workshop_hotkeys(on); } else if (!strcmp(name, "savefiles")) { save_files = on; } else if (!strcmp(name, "balloon")) { workshop_balloon_mode(on); } else if (!strcmp(name, "balloondelay")) { int delay = atoi(value); /* Should I validate the number here?? */ workshop_balloon_delay(delay); } else { /* Let editor interpret it */ workshop_set_option(name, value); } } void workshop_file_closed_lineno(char *filename, int lineno) { char buffer[2*MAXPATHLEN]; vim_snprintf(buffer, sizeof(buffer), NOCATGETS("deletedFile %s %d\n"), filename, lineno); dummy = write(sd, buffer, strlen(buffer)); } void workshop_file_opened(char *filename, int readOnly) { char buffer[2*MAXPATHLEN]; vim_snprintf(buffer, sizeof(buffer), NOCATGETS("loadedFile %s %d\n"), filename, readOnly); dummy = write(sd, buffer, strlen(buffer)); } void workshop_file_saved(char *filename) { char buffer[2*MAXPATHLEN]; vim_snprintf(buffer, sizeof(buffer), NOCATGETS("savedFile %s\n"), filename); dummy = write(sd, buffer, strlen(buffer)); /* Let editor report any moved marks that the eserve client * should deal with (for example, moving location-based breakpoints) */ workshop_moved_marks(filename); } void workshop_frame_moved(int new_x, int new_y, int new_w, int new_h) { char buffer[200]; if (sd >= 0) { vim_snprintf(buffer, sizeof(buffer), NOCATGETS("frameAt %d %d %d %d\n"), new_x, new_y, new_w, new_h); dummy = write(sd, buffer, strlen(buffer)); } } /* A button in the toolbar has been pushed. * Clientdata is a pointer used by the editor code to figure out the * positions for this toolbar (probably by storing a window pointer, * and then fetching the current buffer for that window and looking up * cursor and selection positions etc.) */ void workshop_perform_verb(char *verb, void *clientData) { char *filename; int curLine; int curCol; int selStartLine; int selStartCol; int selEndLine; int selEndCol; int selLength; char *selection; char buf[2*MAXPATHLEN]; /* Later: needsFilePos indicates whether or not we need to fetch all this * info for this verb... for now, however, it looks as if * eserve parsing routines depend on it always being present */ if (workshop_get_positions(clientData, &filename, &curLine, &curCol, &selStartLine, &selStartCol, &selEndLine, &selEndCol, &selLength, &selection)) { if (selection == NULL) { selection = NOCATGETS(""); } /* Should I save the files??? This is currently done by checking if the verb is one of a few recognized ones. Later we can pass this list from eserve to the editor (it's currently hardcoded in vi and emacs as well). */ if (save_files) { if (!strcmp(verb, "build.build") || !strcmp(verb, "build.build-file") || !strcmp(verb, "debug.fix") || !strcmp(verb, "debug.fix-all")) { workshop_save_files(); } } vim_snprintf(buf, sizeof(buf), NOCATGETS("toolVerb %s %s %d,%d %d,%d %d,%d %d %s\n"), verb, filename, curLine, curCol, selStartLine, selStartCol, selEndLine, selEndCol, selLength, selection); dummy = write(sd, buf, strlen(buf)); if (*selection) { free(selection); } } } /* Send a message to eserve */ #if defined(NOHANDS_SUPPORT_FUNCTIONS) || defined(FEAT_BEVAL) void workshop_send_message(char *buf) { dummy = write(sd, buf, strlen(buf)); } #endif /* Some methods, like currentFile, cursorPos, etc. are missing here. * But it looks like these are used for NoHands testing only so we * won't bother requiring editors to implement these */ #ifdef DEBUG void pldebug( char *fmt, /* a printf style format line */ ...) { va_list ap; if (dfd != NULL) { va_start(ap, fmt); vfprintf(dfd, fmt, ap); va_end(ap); fflush(dfd); } } /* end pldebug */ #endif
zyz2011-vim
src/integration.c
C
gpl2
26,831
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * hashtab.c: Handling of a hashtable with Vim-specific properties. * * Each item in a hashtable has a NUL terminated string key. A key can appear * only once in the table. * * A hash number is computed from the key for quick lookup. When the hashes * of two different keys point to the same entry an algorithm is used to * iterate over other entries in the table until the right one is found. * To make the iteration work removed keys are different from entries where a * key was never present. * * The mechanism has been partly based on how Python Dictionaries are * implemented. The algorithm is from Knuth Vol. 3, Sec. 6.4. * * The hashtable grows to accommodate more entries when needed. At least 1/3 * of the entries is empty to keep the lookup efficient (at the cost of extra * memory). */ #include "vim.h" #if defined(FEAT_EVAL) || defined(FEAT_SYN_HL) || defined(PROTO) #if 0 # define HT_DEBUG /* extra checks for table consistency and statistics */ static long hash_count_lookup = 0; /* count number of hashtab lookups */ static long hash_count_perturb = 0; /* count number of "misses" */ #endif /* Magic value for algorithm that walks through the array. */ #define PERTURB_SHIFT 5 static int hash_may_resize __ARGS((hashtab_T *ht, int minitems)); #if 0 /* currently not used */ /* * Create an empty hash table. * Returns NULL when out of memory. */ hashtab_T * hash_create() { hashtab_T *ht; ht = (hashtab_T *)alloc(sizeof(hashtab_T)); if (ht != NULL) hash_init(ht); return ht; } #endif /* * Initialize an empty hash table. */ void hash_init(ht) hashtab_T *ht; { /* This zeroes all "ht_" entries and all the "hi_key" in "ht_smallarray". */ vim_memset(ht, 0, sizeof(hashtab_T)); ht->ht_array = ht->ht_smallarray; ht->ht_mask = HT_INIT_SIZE - 1; } /* * Free the array of a hash table. Does not free the items it contains! * If "ht" is not freed then you should call hash_init() next! */ void hash_clear(ht) hashtab_T *ht; { if (ht->ht_array != ht->ht_smallarray) vim_free(ht->ht_array); } /* * Free the array of a hash table and all the keys it contains. The keys must * have been allocated. "off" is the offset from the start of the allocate * memory to the location of the key (it's always positive). */ void hash_clear_all(ht, off) hashtab_T *ht; int off; { long todo; hashitem_T *hi; todo = (long)ht->ht_used; for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { vim_free(hi->hi_key - off); --todo; } } hash_clear(ht); } /* * Find "key" in hashtable "ht". "key" must not be NULL. * Always returns a pointer to a hashitem. If the item was not found then * HASHITEM_EMPTY() is TRUE. The pointer is then the place where the key * would be added. * WARNING: The returned pointer becomes invalid when the hashtable is changed * (adding, setting or removing an item)! */ hashitem_T * hash_find(ht, key) hashtab_T *ht; char_u *key; { return hash_lookup(ht, key, hash_hash(key)); } /* * Like hash_find(), but caller computes "hash". */ hashitem_T * hash_lookup(ht, key, hash) hashtab_T *ht; char_u *key; hash_T hash; { hash_T perturb; hashitem_T *freeitem; hashitem_T *hi; int idx; #ifdef HT_DEBUG ++hash_count_lookup; #endif /* * Quickly handle the most common situations: * - return if there is no item at all * - skip over a removed item * - return if the item matches */ idx = (int)(hash & ht->ht_mask); hi = &ht->ht_array[idx]; if (hi->hi_key == NULL) return hi; if (hi->hi_key == HI_KEY_REMOVED) freeitem = hi; else if (hi->hi_hash == hash && STRCMP(hi->hi_key, key) == 0) return hi; else freeitem = NULL; /* * Need to search through the table to find the key. The algorithm * to step through the table starts with large steps, gradually becoming * smaller down to (1/4 table size + 1). This means it goes through all * table entries in the end. * When we run into a NULL key it's clear that the key isn't there. * Return the first available slot found (can be a slot of a removed * item). */ for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { #ifdef HT_DEBUG ++hash_count_perturb; /* count a "miss" for hashtab lookup */ #endif idx = (int)((idx << 2) + idx + perturb + 1); hi = &ht->ht_array[idx & ht->ht_mask]; if (hi->hi_key == NULL) return freeitem == NULL ? hi : freeitem; if (hi->hi_hash == hash && hi->hi_key != HI_KEY_REMOVED && STRCMP(hi->hi_key, key) == 0) return hi; if (hi->hi_key == HI_KEY_REMOVED && freeitem == NULL) freeitem = hi; } } /* * Print the efficiency of hashtable lookups. * Useful when trying different hash algorithms. * Called when exiting. */ void hash_debug_results() { #ifdef HT_DEBUG fprintf(stderr, "\r\n\r\n\r\n\r\n"); fprintf(stderr, "Number of hashtable lookups: %ld\r\n", hash_count_lookup); fprintf(stderr, "Number of perturb loops: %ld\r\n", hash_count_perturb); fprintf(stderr, "Percentage of perturb loops: %ld%%\r\n", hash_count_perturb * 100 / hash_count_lookup); #endif } /* * Add item with key "key" to hashtable "ht". * Returns FAIL when out of memory or the key is already present. */ int hash_add(ht, key) hashtab_T *ht; char_u *key; { hash_T hash = hash_hash(key); hashitem_T *hi; hi = hash_lookup(ht, key, hash); if (!HASHITEM_EMPTY(hi)) { EMSG2(_(e_intern2), "hash_add()"); return FAIL; } return hash_add_item(ht, hi, key, hash); } /* * Add item "hi" with "key" to hashtable "ht". "key" must not be NULL and * "hi" must have been obtained with hash_lookup() and point to an empty item. * "hi" is invalid after this! * Returns OK or FAIL (out of memory). */ int hash_add_item(ht, hi, key, hash) hashtab_T *ht; hashitem_T *hi; char_u *key; hash_T hash; { /* If resizing failed before and it fails again we can't add an item. */ if (ht->ht_error && hash_may_resize(ht, 0) == FAIL) return FAIL; ++ht->ht_used; if (hi->hi_key == NULL) ++ht->ht_filled; hi->hi_key = key; hi->hi_hash = hash; /* When the space gets low may resize the array. */ return hash_may_resize(ht, 0); } #if 0 /* not used */ /* * Overwrite hashtable item "hi" with "key". "hi" must point to the item that * is to be overwritten. Thus the number of items in the hashtable doesn't * change. * Although the key must be identical, the pointer may be different, thus it's * set anyway (the key is part of an item with that key). * The caller must take care of freeing the old item. * "hi" is invalid after this! */ void hash_set(hi, key) hashitem_T *hi; char_u *key; { hi->hi_key = key; } #endif /* * Remove item "hi" from hashtable "ht". "hi" must have been obtained with * hash_lookup(). * The caller must take care of freeing the item itself. */ void hash_remove(ht, hi) hashtab_T *ht; hashitem_T *hi; { --ht->ht_used; hi->hi_key = HI_KEY_REMOVED; hash_may_resize(ht, 0); } /* * Lock a hashtable: prevent that ht_array changes. * Don't use this when items are to be added! * Must call hash_unlock() later. */ void hash_lock(ht) hashtab_T *ht; { ++ht->ht_locked; } #if 0 /* currently not used */ /* * Lock a hashtable at the specified number of entries. * Caller must make sure no more than "size" entries will be added. * Must call hash_unlock() later. */ void hash_lock_size(ht, size) hashtab_T *ht; int size; { (void)hash_may_resize(ht, size); ++ht->ht_locked; } #endif /* * Unlock a hashtable: allow ht_array changes again. * Table will be resized (shrink) when necessary. * This must balance a call to hash_lock(). */ void hash_unlock(ht) hashtab_T *ht; { --ht->ht_locked; (void)hash_may_resize(ht, 0); } /* * Shrink a hashtable when there is too much empty space. * Grow a hashtable when there is not enough empty space. * Returns OK or FAIL (out of memory). */ static int hash_may_resize(ht, minitems) hashtab_T *ht; int minitems; /* minimal number of items */ { hashitem_T temparray[HT_INIT_SIZE]; hashitem_T *oldarray, *newarray; hashitem_T *olditem, *newitem; int newi; int todo; long_u oldsize, newsize; long_u minsize; long_u newmask; hash_T perturb; /* Don't resize a locked table. */ if (ht->ht_locked > 0) return OK; #ifdef HT_DEBUG if (ht->ht_used > ht->ht_filled) EMSG("hash_may_resize(): more used than filled"); if (ht->ht_filled >= ht->ht_mask + 1) EMSG("hash_may_resize(): table completely filled"); #endif if (minitems == 0) { /* Return quickly for small tables with at least two NULL items. NULL * items are required for the lookup to decide a key isn't there. */ if (ht->ht_filled < HT_INIT_SIZE - 1 && ht->ht_array == ht->ht_smallarray) return OK; /* * Grow or refill the array when it's more than 2/3 full (including * removed items, so that they get cleaned up). * Shrink the array when it's less than 1/5 full. When growing it is * at least 1/4 full (avoids repeated grow-shrink operations) */ oldsize = ht->ht_mask + 1; if (ht->ht_filled * 3 < oldsize * 2 && ht->ht_used > oldsize / 5) return OK; if (ht->ht_used > 1000) minsize = ht->ht_used * 2; /* it's big, don't make too much room */ else minsize = ht->ht_used * 4; /* make plenty of room */ } else { /* Use specified size. */ if ((long_u)minitems < ht->ht_used) /* just in case... */ minitems = (int)ht->ht_used; minsize = minitems * 3 / 2; /* array is up to 2/3 full */ } newsize = HT_INIT_SIZE; while (newsize < minsize) { newsize <<= 1; /* make sure it's always a power of 2 */ if (newsize == 0) return FAIL; /* overflow */ } if (newsize == HT_INIT_SIZE) { /* Use the small array inside the hashdict structure. */ newarray = ht->ht_smallarray; if (ht->ht_array == newarray) { /* Moving from ht_smallarray to ht_smallarray! Happens when there * are many removed items. Copy the items to be able to clean up * removed items. */ mch_memmove(temparray, newarray, sizeof(temparray)); oldarray = temparray; } else oldarray = ht->ht_array; } else { /* Allocate an array. */ newarray = (hashitem_T *)alloc((unsigned) (sizeof(hashitem_T) * newsize)); if (newarray == NULL) { /* Out of memory. When there are NULL items still return OK. * Otherwise set ht_error, because lookup may result in a hang if * we add another item. */ if (ht->ht_filled < ht->ht_mask) return OK; ht->ht_error = TRUE; return FAIL; } oldarray = ht->ht_array; } vim_memset(newarray, 0, (size_t)(sizeof(hashitem_T) * newsize)); /* * Move all the items from the old array to the new one, placing them in * the right spot. The new array won't have any removed items, thus this * is also a cleanup action. */ newmask = newsize - 1; todo = (int)ht->ht_used; for (olditem = oldarray; todo > 0; ++olditem) if (!HASHITEM_EMPTY(olditem)) { /* * The algorithm to find the spot to add the item is identical to * the algorithm to find an item in hash_lookup(). But we only * need to search for a NULL key, thus it's simpler. */ newi = (int)(olditem->hi_hash & newmask); newitem = &newarray[newi]; if (newitem->hi_key != NULL) for (perturb = olditem->hi_hash; ; perturb >>= PERTURB_SHIFT) { newi = (int)((newi << 2) + newi + perturb + 1); newitem = &newarray[newi & newmask]; if (newitem->hi_key == NULL) break; } *newitem = *olditem; --todo; } if (ht->ht_array != ht->ht_smallarray) vim_free(ht->ht_array); ht->ht_array = newarray; ht->ht_mask = newmask; ht->ht_filled = ht->ht_used; ht->ht_error = FALSE; return OK; } /* * Get the hash number for a key. * If you think you know a better hash function: Compile with HT_DEBUG set and * run a script that uses hashtables a lot. Vim will then print statistics * when exiting. Try that with the current hash algorithm and yours. The * lower the percentage the better. */ hash_T hash_hash(key) char_u *key; { hash_T hash; char_u *p; if ((hash = *key) == 0) return (hash_T)0; /* Empty keys are not allowed, but we don't want to crash if we get one. */ p = key + 1; /* A simplistic algorithm that appears to do very well. * Suggested by George Reilly. */ while (*p != NUL) hash = hash * 101 + *p++; return hash; } #endif
zyz2011-vim
src/hashtab.c
C
gpl2
13,086
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * QNX port by Julian Kinraid * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * os_qnx.c */ #include "vim.h" #if defined(FEAT_GUI_PHOTON) int is_photon_available; #endif void qnx_init() { #if defined(FEAT_GUI_PHOTON) PhChannelParms_t parms; memset(&parms, 0, sizeof(parms)); parms.flags = Ph_DYNAMIC_BUFFER; is_photon_available = (PhAttach(NULL, &parms) != NULL) ? TRUE : FALSE; #endif } #if (defined(FEAT_GUI_PHOTON) && defined(FEAT_CLIPBOARD)) || defined(PROTO) #define CLIP_TYPE_VIM "VIMTYPE" #define CLIP_TYPE_TEXT "TEXT" /* Turn on the clipboard for a console vim when photon is running */ void qnx_clip_init() { if (is_photon_available == TRUE && !gui.in_use) clip_init(TRUE); } /*****************************************************************************/ /* Clipboard */ /* No support for owning the clipboard */ int clip_mch_own_selection(VimClipboard *cbd) { return FALSE; } void clip_mch_lose_selection(VimClipboard *cbd) { } void clip_mch_request_selection(VimClipboard *cbd) { int type = MLINE, clip_length = 0, is_type_set = FALSE; void *cbdata; PhClipHeader *clip_header; char_u *clip_text = NULL; cbdata = PhClipboardPasteStart(PhInputGroup(NULL)); if (cbdata != NULL) { /* Look for the vim specific clip first */ clip_header = PhClipboardPasteType(cbdata, CLIP_TYPE_VIM); if (clip_header != NULL && clip_header->data != NULL) { switch(*(char *) clip_header->data) { default: /* fallthrough to line type */ case 'L': type = MLINE; break; case 'C': type = MCHAR; break; #ifdef FEAT_VISUAL case 'B': type = MBLOCK; break; #endif } is_type_set = TRUE; } /* Try for just normal text */ clip_header = PhClipboardPasteType(cbdata, CLIP_TYPE_TEXT); if (clip_header != NULL) { clip_text = clip_header->data; clip_length = clip_header->length - 1; if (clip_text != NULL && is_type_set == FALSE) type = MAUTO; } if ((clip_text != NULL) && (clip_length > 0)) { clip_yank_selection(type, clip_text, clip_length, cbd); } PhClipboardPasteFinish(cbdata); } } void clip_mch_set_selection(VimClipboard *cbd) { int type; long_u len; char_u *text_clip, vim_clip[2], *str = NULL; PhClipHeader clip_header[2]; /* Prevent recursion from clip_get_selection() */ if (cbd->owned == TRUE) return; cbd->owned = TRUE; clip_get_selection(cbd); cbd->owned = FALSE; type = clip_convert_selection(&str, &len, cbd); if (type >= 0) { text_clip = lalloc(len + 1, TRUE); /* Normal text */ if (text_clip && vim_clip) { memset(clip_header, 0, sizeof(clip_header)); STRNCPY(clip_header[0].type, CLIP_TYPE_VIM, 8); clip_header[0].length = sizeof(vim_clip); clip_header[0].data = vim_clip; STRNCPY(clip_header[1].type, CLIP_TYPE_TEXT, 8); clip_header[1].length = len + 1; clip_header[1].data = text_clip; switch(type) { default: /* fallthrough to MLINE */ case MLINE: *vim_clip = 'L'; break; case MCHAR: *vim_clip = 'C'; break; #ifdef FEAT_VISUAL case MBLOCK: *vim_clip = 'B'; break; #endif } vim_strncpy(text_clip, str, len); vim_clip[ 1 ] = NUL; PhClipboardCopy(PhInputGroup(NULL), 2, clip_header); } vim_free(text_clip); } vim_free(str); } #endif
zyz2011-vim
src/os_qnx.c
C
gpl2
3,508
/* vi:set ts=8 sts=4 sw=4: */ /* * The following software is (C) 1984 Peter da Silva, the Mad Australian, in * the public domain. It may be re-distributed for any purpose with the * inclusion of this notice. */ /* Modified by Bram Moolenaar for use with VIM - Vi Improved. */ /* A few bugs removed by Olaf 'Rhialto' Seibert. */ /* TERMLIB: Terminal independent database. */ #include "vim.h" #include "termlib.pro" #if !defined(AMIGA) && !defined(VMS) && !defined(MACOS) # include <sgtty.h> #endif static int getent __ARGS((char *, char *, FILE *, int)); static int nextent __ARGS((char *, FILE *, int)); static int _match __ARGS((char *, char *)); static char *_addfmt __ARGS((char *, char *, int)); static char *_find __ARGS((char *, char *)); /* * Global variables for termlib */ char *tent; /* Pointer to terminal entry, set by tgetent */ char PC = 0; /* Pad character, default NULL */ char *UP = 0, *BC = 0; /* Pointers to UP and BC strings from database */ short ospeed; /* Baud rate (1-16, 1=300, 16=19200), as in stty */ /* * Module: tgetent * * Purpose: Get termcap entry for <term> into buffer at <tbuf>. * * Calling conventions: char tbuf[TBUFSZ+], term=canonical name for terminal. * * Returned values: 1 = success, -1 = can't open file, * 0 = can't find terminal. * * Notes: * - Should probably supply static buffer. * - Uses environment variables "TERM" and "TERMCAP". If TERM = term (that is, * if the argument matches the environment) then it looks at TERMCAP. * - If TERMCAP begins with a slash, then it assumes this is the file to * search rather than /etc/termcap. * - If TERMCAP does not begin with a slash, and it matches TERM, then this is * used as the entry. * - This could be simplified considerably for non-UNIX systems. */ #ifndef TERMCAPFILE # ifdef AMIGA # define TERMCAPFILE "s:termcap" # else # ifdef VMS # define TERMCAPFILE "VIMRUNTIME:termcap" # else # define TERMCAPFILE "/etc/termcap" # endif # endif #endif int tgetent(tbuf, term) char *tbuf; /* Buffer to hold termcap entry, TBUFSZ bytes max */ char *term; /* Name of terminal */ { char tcbuf[32]; /* Temp buffer to handle */ char *tcptr = tcbuf; /* extended entries */ char *tcap = TERMCAPFILE; /* Default termcap file */ char *tmp; FILE *termcap; int retval = 0; int len; if ((tmp = (char *)mch_getenv((char_u *)"TERMCAP")) != NULL) { if (*tmp == '/') /* TERMCAP = name of termcap file */ { tcap = tmp ; #if defined(AMIGA) /* Convert /usr/share/lib/termcap to usr:share/lib/termcap */ tcap++; tmp = strchr(tcap, '/'); if (tmp) *tmp = ':'; #endif } else /* TERMCAP = termcap entry itself */ { int tlen = strlen(term); while (*tmp && *tmp != ':') /* Check if TERM matches */ { char *nexttmp; while (*tmp == '|') tmp++; nexttmp = _find(tmp, ":|"); /* Rhialto */ if (tmp+tlen == nexttmp && _match(tmp, term) == tlen) { strcpy(tbuf, tmp); tent = tbuf; return 1; } else tmp = nexttmp; } } } if (!(termcap = mch_fopen(tcap, "r"))) { strcpy(tbuf, tcap); return -1; } len = 0; while (getent(tbuf + len, term, termcap, TBUFSZ - len)) { tcptr = tcbuf; /* Rhialto */ if ((term = tgetstr("tc", &tcptr))) /* extended entry */ { rewind(termcap); len = strlen(tbuf); } else { retval = 1; tent = tbuf; /* reset it back to the beginning */ break; } } fclose(termcap); return retval; } static int getent(tbuf, term, termcap, buflen) char *tbuf, *term; FILE *termcap; int buflen; { char *tptr; int tlen = strlen(term); while (nextent(tbuf, termcap, buflen)) /* For each possible entry */ { tptr = tbuf; while (*tptr && *tptr != ':') /* : terminates name field */ { char *nexttptr; while (*tptr == '|') /* | separates names */ tptr++; nexttptr = _find(tptr, ":|"); /* Rhialto */ if (tptr + tlen == nexttptr && _match(tptr, term) == tlen) /* FOUND! */ { tent = tbuf; return 1; } else /* Look for next name */ tptr = nexttptr; } } return 0; } static int nextent(tbuf, termcap, buflen) /* Read 1 entry from TERMCAP file */ char *tbuf; FILE *termcap; int buflen; { char *lbuf = tbuf; /* lbuf=line buffer */ /* read lines straight into buffer */ while (lbuf < tbuf+buflen && /* There's room and */ fgets(lbuf, (int)(tbuf+buflen-lbuf), termcap)) /* another line */ { int llen = strlen(lbuf); if (*lbuf == '#') /* eat comments */ continue; if (lbuf[-1] == ':' && /* and whitespace */ lbuf[0] == '\t' && lbuf[1] == ':') { STRMOVE(lbuf, lbuf + 2); llen -= 2; } if (lbuf[llen-2] == '\\') /* and continuations */ lbuf += llen-2; else { lbuf[llen-1]=0; /* no continuation, return */ return 1; } } return 0; /* ran into end of file */ } /* * Module: tgetflag * * Purpose: returns flag true or false as to the existence of a given entry. * used with 'bs', 'am', etc... * * Calling conventions: id is the 2 character capability id. * * Returned values: 1 for success, 0 for failure. */ int tgetflag(id) char *id; { char buf[256], *ptr = buf; return tgetstr(id, &ptr) ? 1 : 0; } /* * Module: tgetnum * * Purpose: get numeric value such as 'li' or 'co' from termcap. * * Calling conventions: id = 2 character id. * * Returned values: -1 for failure, else numerical value. */ int tgetnum(id) char *id; { char *ptr, buf[256]; ptr = buf; if (tgetstr(id, &ptr)) return atoi(buf); else return 0; } /* * Module: tgetstr * * Purpose: get terminal capability string from database. * * Calling conventions: id is the two character capability id. * (*buf) points into a hold buffer for the * id. the capability is copied into the buffer * and (*buf) is advanced to point to the next * free byte in the buffer. * * Returned values: 0 = no such entry, otherwise returns original * (*buf) (now a pointer to the string). * * Notes * It also decodes certain escape sequences in the buffer. * they should be obvious from the code: * \E = escape. * \n, \r, \t, \f, \b match the 'c' escapes. * ^x matches control-x (^@...^_). * \nnn matches nnn octal. * \x, where x is anything else, matches x. I differ * from the standard library here, in that I allow ^: to match * :. * */ char * tgetstr(id, buf) char *id, **buf; { int len = strlen(id); char *tmp=tent; char *hold; int i; do { tmp = _find(tmp, ":"); /* For each field */ while (*tmp == ':') /* skip empty fields */ tmp++; if (!*tmp) break; if (_match(id, tmp) == len) { tmp += len; /* find '=' '@' or '#' */ if (*tmp == '@') /* :xx@: entry for tc */ return 0; /* deleted entry */ hold= *buf; while (*++tmp && *tmp != ':') { /* not at end of field */ switch(*tmp) { case '\\': /* Expand escapes here */ switch(*++tmp) { case 0: /* ignore backslashes */ tmp--; /* at end of entry */ break; /* shouldn't happen */ case 'e': case 'E': /* ESC */ *(*buf)++ = ESC; break; case 'n': /* \n */ *(*buf)++ = '\n'; break; case 'r': /* \r */ *(*buf)++ = '\r'; break; case 't': /* \t */ *(*buf)++ = '\t'; break; case 'b': /* \b */ *(*buf)++ = '\b'; break; case 'f': /* \f */ *(*buf)++ = '\f'; break; case '0': /* \nnn */ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': **buf = 0; /* get up to three digits */ for (i = 0; i < 3 && VIM_ISDIGIT(*tmp); ++i) **buf = **buf * 8 + *tmp++ - '0'; (*buf)++; tmp--; break; default: /* \x, for all other x */ *(*buf)++= *tmp; } break; case '^': /* control characters */ ++tmp; *(*buf)++ = Ctrl_chr(*tmp); break; default: *(*buf)++ = *tmp; } } *(*buf)++ = 0; return hold; } } while (*tmp); return 0; } /* * Module: tgoto * * Purpose: decode cm cursor motion string. * * Calling conventions: cm is cursor motion string. line, col, are the * desired destination. * * Returned values: a string pointing to the decoded string, or "OOPS" if it * cannot be decoded. * * Notes * The accepted escapes are: * %d as in printf, 0 origin. * %2, %3 like %02d, %03d in printf. * %. like %c * %+x adds <x> to value, then %. * %>xy if value>x, adds y. No output. * %i increments line& col, no output. * %r reverses order of line&col. No output. * %% prints as a single %. * %n exclusive or row & col with 0140. * %B BCD, no output. * %D reverse coding (x-2*(x%16)), no output. */ char * tgoto(cm, col, line) char *cm; /* cm string, from termcap */ int col, /* column, x position */ line; /* line, y position */ { char gx, gy, /* x, y */ *ptr, /* pointer in 'cm' */ reverse = 0, /* reverse flag */ *bufp, /* pointer in returned string */ addup = 0, /* add upline */ addbak = 0, /* add backup */ c; static char buffer[32]; if (!cm) return "OOPS"; /* Kludge, but standard */ bufp = buffer; ptr = cm; while (*ptr) { if ((c = *ptr++) != '%') { /* normal char */ *bufp++ = c; } else { /* % escape */ switch(c = *ptr++) { case 'd': /* decimal */ bufp = _addfmt(bufp, "%d", line); line = col; break; case '2': /* 2 digit decimal */ bufp = _addfmt(bufp, "%02d", line); line = col; break; case '3': /* 3 digit decimal */ bufp = _addfmt(bufp, "%03d", line); line = col; break; case '>': /* %>xy: if >x, add y */ gx = *ptr++; gy = *ptr++; if (col>gx) col += gy; if (line>gx) line += gy; break; case '+': /* %+c: add c */ line += *ptr++; case '.': /* print x/y */ if (line == '\t' || /* these are */ line == '\n' || /* chars that */ line == '\004' || /* UNIX hates */ line == '\0') { line++; /* so go to next pos */ if (reverse == (line == col)) addup=1; /* and mark UP */ else addbak=1; /* or BC */ } *bufp++=line; line = col; break; case 'r': /* r: reverse */ gx = line; line = col; col = gx; reverse = 1; break; case 'i': /* increment (1-origin screen) */ col++; line++; break; case '%': /* %%=% literally */ *bufp++='%'; break; case 'n': /* magic DM2500 code */ line ^= 0140; col ^= 0140; break; case 'B': /* bcd encoding */ line = line/10<<4+line%10; col = col/10<<4+col%10; break; case 'D': /* magic Delta Data code */ line = line-2*(line&15); col = col-2*(col&15); break; default: /* Unknown escape */ return "OOPS"; } } } if (addup) /* add upline */ if (UP) { ptr=UP; while (VIM_ISDIGIT(*ptr) || *ptr == '.') ptr++; if (*ptr == '*') ptr++; while (*ptr) *bufp++ = *ptr++; } if (addbak) /* add backspace */ if (BC) { ptr=BC; while (VIM_ISDIGIT(*ptr) || *ptr == '.') ptr++; if (*ptr == '*') ptr++; while (*ptr) *bufp++ = *ptr++; } else *bufp++='\b'; *bufp = 0; return(buffer); } /* * Module: tputs * * Purpose: decode padding information * * Calling conventions: cp = string to be padded, affcnt = # of items affected * (lines, characters, whatever), outc = routine to output 1 character. * * Returned values: none * * Notes * cp has padding information ahead of it, in the form * nnnTEXT or nnn*TEXT. nnn is the number of milliseconds to delay, * and may be a decimal (nnn.mmm). If the asterisk is given, then * the delay is multiplied by afcnt. The delay is produced by outputting * a number of nulls (or other padding char) after printing the * TEXT. * */ long _bauds[16]={ 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 19200 }; int tputs(cp, affcnt, outc) char *cp; /* string to print */ int affcnt; /* Number of lines affected */ void (*outc) __ARGS((unsigned int));/* routine to output 1 character */ { long frac, /* 10^(#digits after decimal point) */ counter, /* digits */ atol __ARGS((const char *)); if (VIM_ISDIGIT(*cp)) { counter = 0; frac = 1000; while (VIM_ISDIGIT(*cp)) counter = counter * 10L + (long)(*cp++ - '0'); if (*cp == '.') while (VIM_ISDIGIT(*++cp)) { counter = counter * 10L + (long)(*cp++ - '0'); frac = frac * 10; } if (*cp!='*') { /* multiply by affected lines */ if (affcnt>1) affcnt = 1; } else cp++; /* Calculate number of characters for padding counter/frac ms delay */ if (ospeed) counter = (counter * _bauds[ospeed] * (long)affcnt) / frac; while (*cp) /* output string */ (*outc)(*cp++); if (ospeed) while (counter--) /* followed by pad characters */ (*outc)(PC); } else while (*cp) (*outc)(*cp++); return 0; } /* * Module: tutil.c * * Purpose: Utility routines for TERMLIB functions. * */ static int _match(s1, s2) /* returns length of text common to s1 and s2 */ char *s1, *s2; { int i = 0; while (s1[i] && s1[i] == s2[i]) i++; return i; } /* * finds next c in s that's a member of set, returns pointer */ static char * _find(s, set) char *s, *set; { for(; *s; s++) { char *ptr = set; while (*ptr && *s != *ptr) ptr++; if (*ptr) return s; } return s; } /* * add val to buf according to format fmt */ static char * _addfmt(buf, fmt, val) char *buf, *fmt; int val; { sprintf(buf, fmt, val); while (*buf) buf++; return buf; }
zyz2011-vim
src/termlib.c
C
gpl2
14,051
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. * * Blowfish encryption for Vim; in Blowfish output feedback mode. * Contributed by Mohsin Ahmed, http://www.cs.albany.edu/~mosh * Based on http://www.schneier.com/blowfish.html by Bruce Schneier. */ #include "vim.h" #if defined(FEAT_CRYPT) #define ARRAY_LENGTH(A) (sizeof(A)/sizeof(A[0])) #define BF_BLOCK 8 #define BF_BLOCK_MASK 7 #define BF_OFB_LEN (8*(BF_BLOCK)) typedef union { UINT32_T ul[2]; char_u uc[8]; } block8; #if defined(WIN3264) || defined(DOS32) /* MS-Windows is always little endian */ #else # ifdef HAVE_CONFIG_H /* in configure.in AC_C_BIGENDIAN() defines WORDS_BIGENDIAN when needed */ # else error! Please change this code to define WORDS_BIGENDIAN for big-endian machines. # endif #endif static void bf_e_block __ARGS((UINT32_T *p_xl, UINT32_T *p_xr)); static void bf_e_cblock __ARGS((char_u *block)); static int bf_check_tables __ARGS((UINT32_T a_ipa[18], UINT32_T a_sbi[4][256], UINT32_T val)); static int bf_self_test __ARGS((void)); /* Blowfish code */ static UINT32_T pax[18]; static UINT32_T ipa[18] = { 0x243f6a88u, 0x85a308d3u, 0x13198a2eu, 0x03707344u, 0xa4093822u, 0x299f31d0u, 0x082efa98u, 0xec4e6c89u, 0x452821e6u, 0x38d01377u, 0xbe5466cfu, 0x34e90c6cu, 0xc0ac29b7u, 0xc97c50ddu, 0x3f84d5b5u, 0xb5470917u, 0x9216d5d9u, 0x8979fb1bu }; static UINT32_T sbx[4][256]; static UINT32_T sbi[4][256] = { {0xd1310ba6u, 0x98dfb5acu, 0x2ffd72dbu, 0xd01adfb7u, 0xb8e1afedu, 0x6a267e96u, 0xba7c9045u, 0xf12c7f99u, 0x24a19947u, 0xb3916cf7u, 0x0801f2e2u, 0x858efc16u, 0x636920d8u, 0x71574e69u, 0xa458fea3u, 0xf4933d7eu, 0x0d95748fu, 0x728eb658u, 0x718bcd58u, 0x82154aeeu, 0x7b54a41du, 0xc25a59b5u, 0x9c30d539u, 0x2af26013u, 0xc5d1b023u, 0x286085f0u, 0xca417918u, 0xb8db38efu, 0x8e79dcb0u, 0x603a180eu, 0x6c9e0e8bu, 0xb01e8a3eu, 0xd71577c1u, 0xbd314b27u, 0x78af2fdau, 0x55605c60u, 0xe65525f3u, 0xaa55ab94u, 0x57489862u, 0x63e81440u, 0x55ca396au, 0x2aab10b6u, 0xb4cc5c34u, 0x1141e8ceu, 0xa15486afu, 0x7c72e993u, 0xb3ee1411u, 0x636fbc2au, 0x2ba9c55du, 0x741831f6u, 0xce5c3e16u, 0x9b87931eu, 0xafd6ba33u, 0x6c24cf5cu, 0x7a325381u, 0x28958677u, 0x3b8f4898u, 0x6b4bb9afu, 0xc4bfe81bu, 0x66282193u, 0x61d809ccu, 0xfb21a991u, 0x487cac60u, 0x5dec8032u, 0xef845d5du, 0xe98575b1u, 0xdc262302u, 0xeb651b88u, 0x23893e81u, 0xd396acc5u, 0x0f6d6ff3u, 0x83f44239u, 0x2e0b4482u, 0xa4842004u, 0x69c8f04au, 0x9e1f9b5eu, 0x21c66842u, 0xf6e96c9au, 0x670c9c61u, 0xabd388f0u, 0x6a51a0d2u, 0xd8542f68u, 0x960fa728u, 0xab5133a3u, 0x6eef0b6cu, 0x137a3be4u, 0xba3bf050u, 0x7efb2a98u, 0xa1f1651du, 0x39af0176u, 0x66ca593eu, 0x82430e88u, 0x8cee8619u, 0x456f9fb4u, 0x7d84a5c3u, 0x3b8b5ebeu, 0xe06f75d8u, 0x85c12073u, 0x401a449fu, 0x56c16aa6u, 0x4ed3aa62u, 0x363f7706u, 0x1bfedf72u, 0x429b023du, 0x37d0d724u, 0xd00a1248u, 0xdb0fead3u, 0x49f1c09bu, 0x075372c9u, 0x80991b7bu, 0x25d479d8u, 0xf6e8def7u, 0xe3fe501au, 0xb6794c3bu, 0x976ce0bdu, 0x04c006bau, 0xc1a94fb6u, 0x409f60c4u, 0x5e5c9ec2u, 0x196a2463u, 0x68fb6fafu, 0x3e6c53b5u, 0x1339b2ebu, 0x3b52ec6fu, 0x6dfc511fu, 0x9b30952cu, 0xcc814544u, 0xaf5ebd09u, 0xbee3d004u, 0xde334afdu, 0x660f2807u, 0x192e4bb3u, 0xc0cba857u, 0x45c8740fu, 0xd20b5f39u, 0xb9d3fbdbu, 0x5579c0bdu, 0x1a60320au, 0xd6a100c6u, 0x402c7279u, 0x679f25feu, 0xfb1fa3ccu, 0x8ea5e9f8u, 0xdb3222f8u, 0x3c7516dfu, 0xfd616b15u, 0x2f501ec8u, 0xad0552abu, 0x323db5fau, 0xfd238760u, 0x53317b48u, 0x3e00df82u, 0x9e5c57bbu, 0xca6f8ca0u, 0x1a87562eu, 0xdf1769dbu, 0xd542a8f6u, 0x287effc3u, 0xac6732c6u, 0x8c4f5573u, 0x695b27b0u, 0xbbca58c8u, 0xe1ffa35du, 0xb8f011a0u, 0x10fa3d98u, 0xfd2183b8u, 0x4afcb56cu, 0x2dd1d35bu, 0x9a53e479u, 0xb6f84565u, 0xd28e49bcu, 0x4bfb9790u, 0xe1ddf2dau, 0xa4cb7e33u, 0x62fb1341u, 0xcee4c6e8u, 0xef20cadau, 0x36774c01u, 0xd07e9efeu, 0x2bf11fb4u, 0x95dbda4du, 0xae909198u, 0xeaad8e71u, 0x6b93d5a0u, 0xd08ed1d0u, 0xafc725e0u, 0x8e3c5b2fu, 0x8e7594b7u, 0x8ff6e2fbu, 0xf2122b64u, 0x8888b812u, 0x900df01cu, 0x4fad5ea0u, 0x688fc31cu, 0xd1cff191u, 0xb3a8c1adu, 0x2f2f2218u, 0xbe0e1777u, 0xea752dfeu, 0x8b021fa1u, 0xe5a0cc0fu, 0xb56f74e8u, 0x18acf3d6u, 0xce89e299u, 0xb4a84fe0u, 0xfd13e0b7u, 0x7cc43b81u, 0xd2ada8d9u, 0x165fa266u, 0x80957705u, 0x93cc7314u, 0x211a1477u, 0xe6ad2065u, 0x77b5fa86u, 0xc75442f5u, 0xfb9d35cfu, 0xebcdaf0cu, 0x7b3e89a0u, 0xd6411bd3u, 0xae1e7e49u, 0x00250e2du, 0x2071b35eu, 0x226800bbu, 0x57b8e0afu, 0x2464369bu, 0xf009b91eu, 0x5563911du, 0x59dfa6aau, 0x78c14389u, 0xd95a537fu, 0x207d5ba2u, 0x02e5b9c5u, 0x83260376u, 0x6295cfa9u, 0x11c81968u, 0x4e734a41u, 0xb3472dcau, 0x7b14a94au, 0x1b510052u, 0x9a532915u, 0xd60f573fu, 0xbc9bc6e4u, 0x2b60a476u, 0x81e67400u, 0x08ba6fb5u, 0x571be91fu, 0xf296ec6bu, 0x2a0dd915u, 0xb6636521u, 0xe7b9f9b6u, 0xff34052eu, 0xc5855664u, 0x53b02d5du, 0xa99f8fa1u, 0x08ba4799u, 0x6e85076au}, {0x4b7a70e9u, 0xb5b32944u, 0xdb75092eu, 0xc4192623u, 0xad6ea6b0u, 0x49a7df7du, 0x9cee60b8u, 0x8fedb266u, 0xecaa8c71u, 0x699a17ffu, 0x5664526cu, 0xc2b19ee1u, 0x193602a5u, 0x75094c29u, 0xa0591340u, 0xe4183a3eu, 0x3f54989au, 0x5b429d65u, 0x6b8fe4d6u, 0x99f73fd6u, 0xa1d29c07u, 0xefe830f5u, 0x4d2d38e6u, 0xf0255dc1u, 0x4cdd2086u, 0x8470eb26u, 0x6382e9c6u, 0x021ecc5eu, 0x09686b3fu, 0x3ebaefc9u, 0x3c971814u, 0x6b6a70a1u, 0x687f3584u, 0x52a0e286u, 0xb79c5305u, 0xaa500737u, 0x3e07841cu, 0x7fdeae5cu, 0x8e7d44ecu, 0x5716f2b8u, 0xb03ada37u, 0xf0500c0du, 0xf01c1f04u, 0x0200b3ffu, 0xae0cf51au, 0x3cb574b2u, 0x25837a58u, 0xdc0921bdu, 0xd19113f9u, 0x7ca92ff6u, 0x94324773u, 0x22f54701u, 0x3ae5e581u, 0x37c2dadcu, 0xc8b57634u, 0x9af3dda7u, 0xa9446146u, 0x0fd0030eu, 0xecc8c73eu, 0xa4751e41u, 0xe238cd99u, 0x3bea0e2fu, 0x3280bba1u, 0x183eb331u, 0x4e548b38u, 0x4f6db908u, 0x6f420d03u, 0xf60a04bfu, 0x2cb81290u, 0x24977c79u, 0x5679b072u, 0xbcaf89afu, 0xde9a771fu, 0xd9930810u, 0xb38bae12u, 0xdccf3f2eu, 0x5512721fu, 0x2e6b7124u, 0x501adde6u, 0x9f84cd87u, 0x7a584718u, 0x7408da17u, 0xbc9f9abcu, 0xe94b7d8cu, 0xec7aec3au, 0xdb851dfau, 0x63094366u, 0xc464c3d2u, 0xef1c1847u, 0x3215d908u, 0xdd433b37u, 0x24c2ba16u, 0x12a14d43u, 0x2a65c451u, 0x50940002u, 0x133ae4ddu, 0x71dff89eu, 0x10314e55u, 0x81ac77d6u, 0x5f11199bu, 0x043556f1u, 0xd7a3c76bu, 0x3c11183bu, 0x5924a509u, 0xf28fe6edu, 0x97f1fbfau, 0x9ebabf2cu, 0x1e153c6eu, 0x86e34570u, 0xeae96fb1u, 0x860e5e0au, 0x5a3e2ab3u, 0x771fe71cu, 0x4e3d06fau, 0x2965dcb9u, 0x99e71d0fu, 0x803e89d6u, 0x5266c825u, 0x2e4cc978u, 0x9c10b36au, 0xc6150ebau, 0x94e2ea78u, 0xa5fc3c53u, 0x1e0a2df4u, 0xf2f74ea7u, 0x361d2b3du, 0x1939260fu, 0x19c27960u, 0x5223a708u, 0xf71312b6u, 0xebadfe6eu, 0xeac31f66u, 0xe3bc4595u, 0xa67bc883u, 0xb17f37d1u, 0x018cff28u, 0xc332ddefu, 0xbe6c5aa5u, 0x65582185u, 0x68ab9802u, 0xeecea50fu, 0xdb2f953bu, 0x2aef7dadu, 0x5b6e2f84u, 0x1521b628u, 0x29076170u, 0xecdd4775u, 0x619f1510u, 0x13cca830u, 0xeb61bd96u, 0x0334fe1eu, 0xaa0363cfu, 0xb5735c90u, 0x4c70a239u, 0xd59e9e0bu, 0xcbaade14u, 0xeecc86bcu, 0x60622ca7u, 0x9cab5cabu, 0xb2f3846eu, 0x648b1eafu, 0x19bdf0cau, 0xa02369b9u, 0x655abb50u, 0x40685a32u, 0x3c2ab4b3u, 0x319ee9d5u, 0xc021b8f7u, 0x9b540b19u, 0x875fa099u, 0x95f7997eu, 0x623d7da8u, 0xf837889au, 0x97e32d77u, 0x11ed935fu, 0x16681281u, 0x0e358829u, 0xc7e61fd6u, 0x96dedfa1u, 0x7858ba99u, 0x57f584a5u, 0x1b227263u, 0x9b83c3ffu, 0x1ac24696u, 0xcdb30aebu, 0x532e3054u, 0x8fd948e4u, 0x6dbc3128u, 0x58ebf2efu, 0x34c6ffeau, 0xfe28ed61u, 0xee7c3c73u, 0x5d4a14d9u, 0xe864b7e3u, 0x42105d14u, 0x203e13e0u, 0x45eee2b6u, 0xa3aaabeau, 0xdb6c4f15u, 0xfacb4fd0u, 0xc742f442u, 0xef6abbb5u, 0x654f3b1du, 0x41cd2105u, 0xd81e799eu, 0x86854dc7u, 0xe44b476au, 0x3d816250u, 0xcf62a1f2u, 0x5b8d2646u, 0xfc8883a0u, 0xc1c7b6a3u, 0x7f1524c3u, 0x69cb7492u, 0x47848a0bu, 0x5692b285u, 0x095bbf00u, 0xad19489du, 0x1462b174u, 0x23820e00u, 0x58428d2au, 0x0c55f5eau, 0x1dadf43eu, 0x233f7061u, 0x3372f092u, 0x8d937e41u, 0xd65fecf1u, 0x6c223bdbu, 0x7cde3759u, 0xcbee7460u, 0x4085f2a7u, 0xce77326eu, 0xa6078084u, 0x19f8509eu, 0xe8efd855u, 0x61d99735u, 0xa969a7aau, 0xc50c06c2u, 0x5a04abfcu, 0x800bcadcu, 0x9e447a2eu, 0xc3453484u, 0xfdd56705u, 0x0e1e9ec9u, 0xdb73dbd3u, 0x105588cdu, 0x675fda79u, 0xe3674340u, 0xc5c43465u, 0x713e38d8u, 0x3d28f89eu, 0xf16dff20u, 0x153e21e7u, 0x8fb03d4au, 0xe6e39f2bu, 0xdb83adf7u}, {0xe93d5a68u, 0x948140f7u, 0xf64c261cu, 0x94692934u, 0x411520f7u, 0x7602d4f7u, 0xbcf46b2eu, 0xd4a20068u, 0xd4082471u, 0x3320f46au, 0x43b7d4b7u, 0x500061afu, 0x1e39f62eu, 0x97244546u, 0x14214f74u, 0xbf8b8840u, 0x4d95fc1du, 0x96b591afu, 0x70f4ddd3u, 0x66a02f45u, 0xbfbc09ecu, 0x03bd9785u, 0x7fac6dd0u, 0x31cb8504u, 0x96eb27b3u, 0x55fd3941u, 0xda2547e6u, 0xabca0a9au, 0x28507825u, 0x530429f4u, 0x0a2c86dau, 0xe9b66dfbu, 0x68dc1462u, 0xd7486900u, 0x680ec0a4u, 0x27a18deeu, 0x4f3ffea2u, 0xe887ad8cu, 0xb58ce006u, 0x7af4d6b6u, 0xaace1e7cu, 0xd3375fecu, 0xce78a399u, 0x406b2a42u, 0x20fe9e35u, 0xd9f385b9u, 0xee39d7abu, 0x3b124e8bu, 0x1dc9faf7u, 0x4b6d1856u, 0x26a36631u, 0xeae397b2u, 0x3a6efa74u, 0xdd5b4332u, 0x6841e7f7u, 0xca7820fbu, 0xfb0af54eu, 0xd8feb397u, 0x454056acu, 0xba489527u, 0x55533a3au, 0x20838d87u, 0xfe6ba9b7u, 0xd096954bu, 0x55a867bcu, 0xa1159a58u, 0xcca92963u, 0x99e1db33u, 0xa62a4a56u, 0x3f3125f9u, 0x5ef47e1cu, 0x9029317cu, 0xfdf8e802u, 0x04272f70u, 0x80bb155cu, 0x05282ce3u, 0x95c11548u, 0xe4c66d22u, 0x48c1133fu, 0xc70f86dcu, 0x07f9c9eeu, 0x41041f0fu, 0x404779a4u, 0x5d886e17u, 0x325f51ebu, 0xd59bc0d1u, 0xf2bcc18fu, 0x41113564u, 0x257b7834u, 0x602a9c60u, 0xdff8e8a3u, 0x1f636c1bu, 0x0e12b4c2u, 0x02e1329eu, 0xaf664fd1u, 0xcad18115u, 0x6b2395e0u, 0x333e92e1u, 0x3b240b62u, 0xeebeb922u, 0x85b2a20eu, 0xe6ba0d99u, 0xde720c8cu, 0x2da2f728u, 0xd0127845u, 0x95b794fdu, 0x647d0862u, 0xe7ccf5f0u, 0x5449a36fu, 0x877d48fau, 0xc39dfd27u, 0xf33e8d1eu, 0x0a476341u, 0x992eff74u, 0x3a6f6eabu, 0xf4f8fd37u, 0xa812dc60u, 0xa1ebddf8u, 0x991be14cu, 0xdb6e6b0du, 0xc67b5510u, 0x6d672c37u, 0x2765d43bu, 0xdcd0e804u, 0xf1290dc7u, 0xcc00ffa3u, 0xb5390f92u, 0x690fed0bu, 0x667b9ffbu, 0xcedb7d9cu, 0xa091cf0bu, 0xd9155ea3u, 0xbb132f88u, 0x515bad24u, 0x7b9479bfu, 0x763bd6ebu, 0x37392eb3u, 0xcc115979u, 0x8026e297u, 0xf42e312du, 0x6842ada7u, 0xc66a2b3bu, 0x12754cccu, 0x782ef11cu, 0x6a124237u, 0xb79251e7u, 0x06a1bbe6u, 0x4bfb6350u, 0x1a6b1018u, 0x11caedfau, 0x3d25bdd8u, 0xe2e1c3c9u, 0x44421659u, 0x0a121386u, 0xd90cec6eu, 0xd5abea2au, 0x64af674eu, 0xda86a85fu, 0xbebfe988u, 0x64e4c3feu, 0x9dbc8057u, 0xf0f7c086u, 0x60787bf8u, 0x6003604du, 0xd1fd8346u, 0xf6381fb0u, 0x7745ae04u, 0xd736fcccu, 0x83426b33u, 0xf01eab71u, 0xb0804187u, 0x3c005e5fu, 0x77a057beu, 0xbde8ae24u, 0x55464299u, 0xbf582e61u, 0x4e58f48fu, 0xf2ddfda2u, 0xf474ef38u, 0x8789bdc2u, 0x5366f9c3u, 0xc8b38e74u, 0xb475f255u, 0x46fcd9b9u, 0x7aeb2661u, 0x8b1ddf84u, 0x846a0e79u, 0x915f95e2u, 0x466e598eu, 0x20b45770u, 0x8cd55591u, 0xc902de4cu, 0xb90bace1u, 0xbb8205d0u, 0x11a86248u, 0x7574a99eu, 0xb77f19b6u, 0xe0a9dc09u, 0x662d09a1u, 0xc4324633u, 0xe85a1f02u, 0x09f0be8cu, 0x4a99a025u, 0x1d6efe10u, 0x1ab93d1du, 0x0ba5a4dfu, 0xa186f20fu, 0x2868f169u, 0xdcb7da83u, 0x573906feu, 0xa1e2ce9bu, 0x4fcd7f52u, 0x50115e01u, 0xa70683fau, 0xa002b5c4u, 0x0de6d027u, 0x9af88c27u, 0x773f8641u, 0xc3604c06u, 0x61a806b5u, 0xf0177a28u, 0xc0f586e0u, 0x006058aau, 0x30dc7d62u, 0x11e69ed7u, 0x2338ea63u, 0x53c2dd94u, 0xc2c21634u, 0xbbcbee56u, 0x90bcb6deu, 0xebfc7da1u, 0xce591d76u, 0x6f05e409u, 0x4b7c0188u, 0x39720a3du, 0x7c927c24u, 0x86e3725fu, 0x724d9db9u, 0x1ac15bb4u, 0xd39eb8fcu, 0xed545578u, 0x08fca5b5u, 0xd83d7cd3u, 0x4dad0fc4u, 0x1e50ef5eu, 0xb161e6f8u, 0xa28514d9u, 0x6c51133cu, 0x6fd5c7e7u, 0x56e14ec4u, 0x362abfceu, 0xddc6c837u, 0xd79a3234u, 0x92638212u, 0x670efa8eu, 0x406000e0u}, {0x3a39ce37u, 0xd3faf5cfu, 0xabc27737u, 0x5ac52d1bu, 0x5cb0679eu, 0x4fa33742u, 0xd3822740u, 0x99bc9bbeu, 0xd5118e9du, 0xbf0f7315u, 0xd62d1c7eu, 0xc700c47bu, 0xb78c1b6bu, 0x21a19045u, 0xb26eb1beu, 0x6a366eb4u, 0x5748ab2fu, 0xbc946e79u, 0xc6a376d2u, 0x6549c2c8u, 0x530ff8eeu, 0x468dde7du, 0xd5730a1du, 0x4cd04dc6u, 0x2939bbdbu, 0xa9ba4650u, 0xac9526e8u, 0xbe5ee304u, 0xa1fad5f0u, 0x6a2d519au, 0x63ef8ce2u, 0x9a86ee22u, 0xc089c2b8u, 0x43242ef6u, 0xa51e03aau, 0x9cf2d0a4u, 0x83c061bau, 0x9be96a4du, 0x8fe51550u, 0xba645bd6u, 0x2826a2f9u, 0xa73a3ae1u, 0x4ba99586u, 0xef5562e9u, 0xc72fefd3u, 0xf752f7dau, 0x3f046f69u, 0x77fa0a59u, 0x80e4a915u, 0x87b08601u, 0x9b09e6adu, 0x3b3ee593u, 0xe990fd5au, 0x9e34d797u, 0x2cf0b7d9u, 0x022b8b51u, 0x96d5ac3au, 0x017da67du, 0xd1cf3ed6u, 0x7c7d2d28u, 0x1f9f25cfu, 0xadf2b89bu, 0x5ad6b472u, 0x5a88f54cu, 0xe029ac71u, 0xe019a5e6u, 0x47b0acfdu, 0xed93fa9bu, 0xe8d3c48du, 0x283b57ccu, 0xf8d56629u, 0x79132e28u, 0x785f0191u, 0xed756055u, 0xf7960e44u, 0xe3d35e8cu, 0x15056dd4u, 0x88f46dbau, 0x03a16125u, 0x0564f0bdu, 0xc3eb9e15u, 0x3c9057a2u, 0x97271aecu, 0xa93a072au, 0x1b3f6d9bu, 0x1e6321f5u, 0xf59c66fbu, 0x26dcf319u, 0x7533d928u, 0xb155fdf5u, 0x03563482u, 0x8aba3cbbu, 0x28517711u, 0xc20ad9f8u, 0xabcc5167u, 0xccad925fu, 0x4de81751u, 0x3830dc8eu, 0x379d5862u, 0x9320f991u, 0xea7a90c2u, 0xfb3e7bceu, 0x5121ce64u, 0x774fbe32u, 0xa8b6e37eu, 0xc3293d46u, 0x48de5369u, 0x6413e680u, 0xa2ae0810u, 0xdd6db224u, 0x69852dfdu, 0x09072166u, 0xb39a460au, 0x6445c0ddu, 0x586cdecfu, 0x1c20c8aeu, 0x5bbef7ddu, 0x1b588d40u, 0xccd2017fu, 0x6bb4e3bbu, 0xdda26a7eu, 0x3a59ff45u, 0x3e350a44u, 0xbcb4cdd5u, 0x72eacea8u, 0xfa6484bbu, 0x8d6612aeu, 0xbf3c6f47u, 0xd29be463u, 0x542f5d9eu, 0xaec2771bu, 0xf64e6370u, 0x740e0d8du, 0xe75b1357u, 0xf8721671u, 0xaf537d5du, 0x4040cb08u, 0x4eb4e2ccu, 0x34d2466au, 0x0115af84u, 0xe1b00428u, 0x95983a1du, 0x06b89fb4u, 0xce6ea048u, 0x6f3f3b82u, 0x3520ab82u, 0x011a1d4bu, 0x277227f8u, 0x611560b1u, 0xe7933fdcu, 0xbb3a792bu, 0x344525bdu, 0xa08839e1u, 0x51ce794bu, 0x2f32c9b7u, 0xa01fbac9u, 0xe01cc87eu, 0xbcc7d1f6u, 0xcf0111c3u, 0xa1e8aac7u, 0x1a908749u, 0xd44fbd9au, 0xd0dadecbu, 0xd50ada38u, 0x0339c32au, 0xc6913667u, 0x8df9317cu, 0xe0b12b4fu, 0xf79e59b7u, 0x43f5bb3au, 0xf2d519ffu, 0x27d9459cu, 0xbf97222cu, 0x15e6fc2au, 0x0f91fc71u, 0x9b941525u, 0xfae59361u, 0xceb69cebu, 0xc2a86459u, 0x12baa8d1u, 0xb6c1075eu, 0xe3056a0cu, 0x10d25065u, 0xcb03a442u, 0xe0ec6e0eu, 0x1698db3bu, 0x4c98a0beu, 0x3278e964u, 0x9f1f9532u, 0xe0d392dfu, 0xd3a0342bu, 0x8971f21eu, 0x1b0a7441u, 0x4ba3348cu, 0xc5be7120u, 0xc37632d8u, 0xdf359f8du, 0x9b992f2eu, 0xe60b6f47u, 0x0fe3f11du, 0xe54cda54u, 0x1edad891u, 0xce6279cfu, 0xcd3e7e6fu, 0x1618b166u, 0xfd2c1d05u, 0x848fd2c5u, 0xf6fb2299u, 0xf523f357u, 0xa6327623u, 0x93a83531u, 0x56cccd02u, 0xacf08162u, 0x5a75ebb5u, 0x6e163697u, 0x88d273ccu, 0xde966292u, 0x81b949d0u, 0x4c50901bu, 0x71c65614u, 0xe6c6c7bdu, 0x327a140au, 0x45e1d006u, 0xc3f27b9au, 0xc9aa53fdu, 0x62a80f00u, 0xbb25bfe2u, 0x35bdd2f6u, 0x71126905u, 0xb2040222u, 0xb6cbcf7cu, 0xcd769c2bu, 0x53113ec0u, 0x1640e3d3u, 0x38abbd60u, 0x2547adf0u, 0xba38209cu, 0xf746ce76u, 0x77afa1c5u, 0x20756060u, 0x85cbfe4eu, 0x8ae88dd8u, 0x7aaaf9b0u, 0x4cf9aa7eu, 0x1948c25cu, 0x02fb8a8cu, 0x01c36ae4u, 0xd6ebe1f9u, 0x90d4f869u, 0xa65cdea0u, 0x3f09252du, 0xc208e69fu, 0xb74e6132u, 0xce77e25bu, 0x578fdfe3u, 0x3ac372e6u } }; #define F1(i) \ xl ^= pax[i]; \ xr ^= ((sbx[0][xl >> 24] + \ sbx[1][(xl & 0xFF0000) >> 16]) ^ \ sbx[2][(xl & 0xFF00) >> 8]) + \ sbx[3][xl & 0xFF]; #define F2(i) \ xr ^= pax[i]; \ xl ^= ((sbx[0][xr >> 24] + \ sbx[1][(xr & 0xFF0000) >> 16]) ^ \ sbx[2][(xr & 0xFF00) >> 8]) + \ sbx[3][xr & 0xFF]; static void bf_e_block(p_xl, p_xr) UINT32_T *p_xl; UINT32_T *p_xr; { UINT32_T temp, xl = *p_xl, xr = *p_xr; F1(0) F2(1) F1(2) F2(3) F1(4) F2(5) F1(6) F2(7) F1(8) F2(9) F1(10) F2(11) F1(12) F2(13) F1(14) F2(15) xl ^= pax[16]; xr ^= pax[17]; temp = xl; xl = xr; xr = temp; *p_xl = xl; *p_xr = xr; } #if 0 /* not used */ static void bf_d_block(p_xl, p_xr) UINT32_T *p_xl; UINT32_T *p_xr; { UINT32_T temp, xl = *p_xl, xr = *p_xr; F1(17) F2(16) F1(15) F2(14) F1(13) F2(12) F1(11) F2(10) F1(9) F2(8) F1(7) F2(6) F1(5) F2(4) F1(3) F2(2) xl ^= pax[1]; xr ^= pax[0]; temp = xl; xl = xr; xr = temp; *p_xl = xl; *p_xr = xr; } #endif #ifdef WORDS_BIGENDIAN # define htonl2(x) \ x = ((((x) & 0xffL) << 24) | (((x) & 0xff00L) << 8) | \ (((x) & 0xff0000L) >> 8) | (((x) & 0xff000000L) >> 24)) #else # define htonl2(x) #endif static void bf_e_cblock(block) char_u *block; { block8 bk; memcpy(bk.uc, block, 8); htonl2(bk.ul[0]); htonl2(bk.ul[1]); bf_e_block(&bk.ul[0], &bk.ul[1]); htonl2(bk.ul[0]); htonl2(bk.ul[1]); memcpy(block, bk.uc, 8); } #if 0 /* not used */ void bf_d_cblock(block) char_u *block; { block8 bk; memcpy(bk.uc, block, 8); htonl2(bk.ul[0]); htonl2(bk.ul[1]); bf_d_block(&bk.ul[0], &bk.ul[1]); htonl2(bk.ul[0]); htonl2(bk.ul[1]); memcpy(block, bk.uc, 8); } #endif /* * Initialize the crypt method using "password" as the encryption key and * "salt[salt_len]" as the salt. */ void bf_key_init(password, salt, salt_len) char_u *password; char_u *salt; int salt_len; { int i, j, keypos = 0; unsigned u; UINT32_T val, data_l, data_r; char_u *key; int keylen; /* Process the key 1000 times. * See http://en.wikipedia.org/wiki/Key_strengthening. */ key = sha256_key(password, salt, salt_len); for (i = 0; i < 1000; i++) key = sha256_key(key, salt, salt_len); /* Convert the key from 64 hex chars to 32 binary chars. */ keylen = (int)STRLEN(key) / 2; if (keylen == 0) { EMSG(_("E831: bf_key_init() called with empty password")); return; } for (i = 0; i < keylen; i++) { sscanf((char *)&key[i * 2], "%2x", &u); key[i] = u; } mch_memmove(sbx, sbi, 4 * 4 * 256); for (i = 0; i < 18; ++i) { val = 0; for (j = 0; j < 4; ++j) val = (val << 8) | key[keypos++ % keylen]; pax[i] = ipa[i] ^ val; } data_l = data_r = 0; for (i = 0; i < 18; i += 2) { bf_e_block(&data_l, &data_r); pax[i + 0] = data_l; pax[i + 1] = data_r; } for (i = 0; i < 4; ++i) { for (j = 0; j < 256; j += 2) { bf_e_block(&data_l, &data_r); sbx[i][j + 0] = data_l; sbx[i][j + 1] = data_r; } } } /* * BF Self test for corrupted tables or instructions */ static int bf_check_tables(a_ipa, a_sbi, val) UINT32_T a_ipa[18]; UINT32_T a_sbi[4][256]; UINT32_T val; { int i, j; UINT32_T c = 0; for (i = 0; i < 18; i++) c ^= a_ipa[i]; for (i = 0; i < 4; i++) for (j = 0; j < 256; j++) c ^= a_sbi[i][j]; return c == val; } typedef struct { char_u password[64]; char_u salt[9]; char_u plaintxt[9]; char_u cryptxt[9]; char_u badcryptxt[9]; /* cryptxt when big/little endian is wrong */ UINT32_T keysum; } struct_bf_test_data; /* * Assert bf(password, plaintxt) is cryptxt. * Assert csum(pax sbx(password)) is keysum. */ static struct_bf_test_data bf_test_data[] = { { "password", "salt", "plaintxt", "\xad\x3d\xfa\x7f\xe8\xea\x40\xf6", /* cryptxt */ "\x72\x50\x3b\x38\x10\x60\x22\xa7", /* badcryptxt */ 0x56701b5du /* keysum */ }, }; /* * Return FAIL when there is something wrong with blowfish encryption. */ static int bf_self_test() { int i, bn; int err = 0; block8 bk; UINT32_T ui = 0xffffffffUL; /* We can't simply use sizeof(UINT32_T), it would generate a compiler * warning. */ if (ui != 0xffffffffUL || ui + 1 != 0) { err++; EMSG(_("E820: sizeof(uint32_t) != 4")); } if (!bf_check_tables(ipa, sbi, 0x6ffa520a)) err++; bn = ARRAY_LENGTH(bf_test_data); for (i = 0; i < bn; i++) { bf_key_init((char_u *)(bf_test_data[i].password), bf_test_data[i].salt, (int)STRLEN(bf_test_data[i].salt)); if (!bf_check_tables(pax, sbx, bf_test_data[i].keysum)) err++; /* Don't modify bf_test_data[i].plaintxt, self test is idempotent. */ memcpy(bk.uc, bf_test_data[i].plaintxt, 8); bf_e_cblock(bk.uc); if (memcmp(bk.uc, bf_test_data[i].cryptxt, 8) != 0) { if (err == 0 && memcmp(bk.uc, bf_test_data[i].badcryptxt, 8) == 0) EMSG(_("E817: Blowfish big/little endian use wrong")); err++; } } return err > 0 ? FAIL : OK; } /* Output feedback mode. */ static int randbyte_offset = 0; static int update_offset = 0; static char_u ofb_buffer[BF_OFB_LEN]; /* 64 bytes */ /* * Initialize with seed "iv[iv_len]". */ void bf_ofb_init(iv, iv_len) char_u *iv; int iv_len; { int i, mi; randbyte_offset = update_offset = 0; vim_memset(ofb_buffer, 0, BF_OFB_LEN); if (iv_len > 0) { mi = iv_len > BF_OFB_LEN ? iv_len : BF_OFB_LEN; for (i = 0; i < mi; i++) ofb_buffer[i % BF_OFB_LEN] ^= iv[i % iv_len]; } } #define BF_OFB_UPDATE(c) { \ ofb_buffer[update_offset] ^= (char_u)c; \ if (++update_offset == BF_OFB_LEN) \ update_offset = 0; \ } #define BF_RANBYTE(t) { \ if ((randbyte_offset & BF_BLOCK_MASK) == 0) \ bf_e_cblock(&ofb_buffer[randbyte_offset]); \ t = ofb_buffer[randbyte_offset]; \ if (++randbyte_offset == BF_OFB_LEN) \ randbyte_offset = 0; \ } /* * Encrypt "from[len]" into "to[len]". * "from" and "to" can be equal to encrypt in place. */ void bf_crypt_encode(from, len, to) char_u *from; size_t len; char_u *to; { size_t i; int ztemp, t; for (i = 0; i < len; ++i) { ztemp = from[i]; BF_RANBYTE(t); BF_OFB_UPDATE(ztemp); to[i] = t ^ ztemp; } } /* * Decrypt "ptr[len]" in place. */ void bf_crypt_decode(ptr, len) char_u *ptr; long len; { char_u *p; int t; for (p = ptr; p < ptr + len; ++p) { BF_RANBYTE(t); *p ^= t; BF_OFB_UPDATE(*p); } } /* * Initialize the encryption keys and the random header according to * the given password. */ void bf_crypt_init_keys(passwd) char_u *passwd; /* password string with which to modify keys */ { char_u *p; for (p = passwd; *p != NUL; ++p) { BF_OFB_UPDATE(*p); } } static int save_randbyte_offset; static int save_update_offset; static char_u save_ofb_buffer[BF_OFB_LEN]; static UINT32_T save_pax[18]; static UINT32_T save_sbx[4][256]; /* * Save the current crypt state. Can only be used once before * bf_crypt_restore(). */ void bf_crypt_save() { save_randbyte_offset = randbyte_offset; save_update_offset = update_offset; mch_memmove(save_ofb_buffer, ofb_buffer, BF_OFB_LEN); mch_memmove(save_pax, pax, 4 * 18); mch_memmove(save_sbx, sbx, 4 * 4 * 256); } /* * Restore the current crypt state. Can only be used after * bf_crypt_save(). */ void bf_crypt_restore() { randbyte_offset = save_randbyte_offset; update_offset = save_update_offset; mch_memmove(ofb_buffer, save_ofb_buffer, BF_OFB_LEN); mch_memmove(pax, save_pax, 4 * 18); mch_memmove(sbx, save_sbx, 4 * 4 * 256); } /* * Run a test to check if the encryption works as expected. * Give an error and return FAIL when not. */ int blowfish_self_test() { if (sha256_self_test() == FAIL) { EMSG(_("E818: sha256 test failed")); return FAIL; } if (bf_self_test() == FAIL) { EMSG(_("E819: Blowfish test failed")); return FAIL; } return OK; } #endif /* FEAT_CRYPT */
zyz2011-vim
src/blowfish.c
C
gpl2
24,231
/* vim:ts=8 sts=4:sw=4 * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * Atari MiNT Machine-dependent things. */ #define BINARY_FILE_IO
zyz2011-vim
src/os_mint.h
C
gpl2
281
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * GUI/Motif support by Robert Webb * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Common code for the Motif and Athena GUI. * Not used for GTK. */ #include <X11/keysym.h> #include <X11/Xatom.h> #include <X11/StringDefs.h> #include <X11/Intrinsic.h> #include <X11/Shell.h> #include <X11/cursorfont.h> #include "vim.h" /* * For Workshop XpmP.h is preferred, because it makes the signs drawn with a * transparent background instead of black. */ #if defined(HAVE_XM_XPMP_H) && defined(FEAT_GUI_MOTIF) \ && (!defined(HAVE_X11_XPM_H) || defined(FEAT_SUN_WORKSHOP)) # include <Xm/XpmP.h> #else # ifdef HAVE_X11_XPM_H # include <X11/xpm.h> # endif #endif #ifdef FEAT_XFONTSET # ifdef X_LOCALE # include <X11/Xlocale.h> # else # include <locale.h> # endif #endif #ifdef HAVE_X11_SUNKEYSYM_H # include <X11/Sunkeysym.h> #endif #ifdef HAVE_X11_XMU_EDITRES_H # include <X11/Xmu/Editres.h> #endif #ifdef FEAT_BEVAL_TIP # include "gui_beval.h" #endif #define VIM_NAME "vim" #define VIM_CLASS "Vim" /* Default resource values */ #define DFLT_FONT "7x13" #ifdef FONTSET_ALWAYS # define DFLT_MENU_FONT XtDefaultFontSet #else # define DFLT_MENU_FONT XtDefaultFont #endif #define DFLT_TOOLTIP_FONT XtDefaultFontSet #ifdef FEAT_GUI_ATHENA # define DFLT_MENU_BG_COLOR "gray77" # define DFLT_MENU_FG_COLOR "black" # define DFLT_SCROLL_BG_COLOR "gray60" # define DFLT_SCROLL_FG_COLOR "gray77" # define DFLT_TOOLTIP_BG_COLOR "#ffffffff9191" # define DFLT_TOOLTIP_FG_COLOR "#000000000000" #else /* use the default (CDE) colors */ # define DFLT_MENU_BG_COLOR "" # define DFLT_MENU_FG_COLOR "" # define DFLT_SCROLL_BG_COLOR "" # define DFLT_SCROLL_FG_COLOR "" # define DFLT_TOOLTIP_BG_COLOR "#ffffffff9191" # define DFLT_TOOLTIP_FG_COLOR "#000000000000" #endif Widget vimShell = (Widget)0; static Atom wm_atoms[2]; /* Window Manager Atoms */ #define DELETE_WINDOW_IDX 0 /* index in wm_atoms[] for WM_DELETE_WINDOW */ #define SAVE_YOURSELF_IDX 1 /* index in wm_atoms[] for WM_SAVE_YOURSELF */ #ifdef FEAT_XFONTSET /* * We either draw with a fontset (when current_fontset != NULL) or with a * normal font (current_fontset == NULL, use gui.text_gc and gui.back_gc). */ static XFontSet current_fontset = NULL; #define XDrawString(dpy, win, gc, x, y, str, n) \ do \ { \ if (current_fontset != NULL) \ XmbDrawString(dpy, win, current_fontset, gc, x, y, str, n); \ else \ XDrawString(dpy, win, gc, x, y, str, n); \ } while (0) #define XDrawString16(dpy, win, gc, x, y, str, n) \ do \ { \ if (current_fontset != NULL) \ XwcDrawString(dpy, win, current_fontset, gc, x, y, (wchar_t *)str, n); \ else \ XDrawString16(dpy, win, gc, x, y, (XChar2b *)str, n); \ } while (0) #define XDrawImageString16(dpy, win, gc, x, y, str, n) \ do \ { \ if (current_fontset != NULL) \ XwcDrawImageString(dpy, win, current_fontset, gc, x, y, (wchar_t *)str, n); \ else \ XDrawImageString16(dpy, win, gc, x, y, (XChar2b *)str, n); \ } while (0) static int check_fontset_sanity __ARGS((XFontSet fs)); static int fontset_width __ARGS((XFontSet fs)); static int fontset_ascent __ARGS((XFontSet fs)); #endif static guicolor_T prev_fg_color = INVALCOLOR; static guicolor_T prev_bg_color = INVALCOLOR; static guicolor_T prev_sp_color = INVALCOLOR; #if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU) static XButtonPressedEvent last_mouse_event; #endif static int find_closest_color __ARGS((Colormap colormap, XColor *colorPtr)); static void gui_x11_timer_cb __ARGS((XtPointer timed_out, XtIntervalId *interval_id)); static void gui_x11_visibility_cb __ARGS((Widget w, XtPointer dud, XEvent *event, Boolean *dum)); static void gui_x11_expose_cb __ARGS((Widget w, XtPointer dud, XEvent *event, Boolean *dum)); static void gui_x11_resize_window_cb __ARGS((Widget w, XtPointer dud, XEvent *event, Boolean *dum)); static void gui_x11_focus_change_cb __ARGS((Widget w, XtPointer data, XEvent *event, Boolean *dum)); static void gui_x11_enter_cb __ARGS((Widget w, XtPointer data, XEvent *event, Boolean *dum)); static void gui_x11_leave_cb __ARGS((Widget w, XtPointer data, XEvent *event, Boolean *dum)); static void gui_x11_mouse_cb __ARGS((Widget w, XtPointer data, XEvent *event, Boolean *dum)); #ifdef FEAT_SNIFF static void gui_x11_sniff_request_cb __ARGS((XtPointer closure, int *source, XtInputId *id)); #endif static void gui_x11_check_copy_area __ARGS((void)); #ifdef FEAT_CLIENTSERVER static void gui_x11_send_event_handler __ARGS((Widget, XtPointer, XEvent *, Boolean *)); #endif static void gui_x11_wm_protocol_handler __ARGS((Widget, XtPointer, XEvent *, Boolean *)); static void gui_x11_blink_cb __ARGS((XtPointer timed_out, XtIntervalId *interval_id)); static Cursor gui_x11_create_blank_mouse __ARGS((void)); static void draw_curl __ARGS((int row, int col, int cells)); /* * Keycodes recognized by vim. * NOTE: when changing this, the table in gui_gtk_x11.c probably needs the * same change! */ static struct specialkey { KeySym key_sym; char_u vim_code0; char_u vim_code1; } special_keys[] = { {XK_Up, 'k', 'u'}, {XK_Down, 'k', 'd'}, {XK_Left, 'k', 'l'}, {XK_Right, 'k', 'r'}, {XK_F1, 'k', '1'}, {XK_F2, 'k', '2'}, {XK_F3, 'k', '3'}, {XK_F4, 'k', '4'}, {XK_F5, 'k', '5'}, {XK_F6, 'k', '6'}, {XK_F7, 'k', '7'}, {XK_F8, 'k', '8'}, {XK_F9, 'k', '9'}, {XK_F10, 'k', ';'}, {XK_F11, 'F', '1'}, {XK_F12, 'F', '2'}, {XK_F13, 'F', '3'}, {XK_F14, 'F', '4'}, {XK_F15, 'F', '5'}, {XK_F16, 'F', '6'}, {XK_F17, 'F', '7'}, {XK_F18, 'F', '8'}, {XK_F19, 'F', '9'}, {XK_F20, 'F', 'A'}, {XK_F21, 'F', 'B'}, {XK_F22, 'F', 'C'}, {XK_F23, 'F', 'D'}, {XK_F24, 'F', 'E'}, {XK_F25, 'F', 'F'}, {XK_F26, 'F', 'G'}, {XK_F27, 'F', 'H'}, {XK_F28, 'F', 'I'}, {XK_F29, 'F', 'J'}, {XK_F30, 'F', 'K'}, {XK_F31, 'F', 'L'}, {XK_F32, 'F', 'M'}, {XK_F33, 'F', 'N'}, {XK_F34, 'F', 'O'}, {XK_F35, 'F', 'P'}, /* keysymdef.h defines up to F35 */ #ifdef SunXK_F36 {SunXK_F36, 'F', 'Q'}, {SunXK_F37, 'F', 'R'}, #endif {XK_Help, '%', '1'}, {XK_Undo, '&', '8'}, {XK_BackSpace, 'k', 'b'}, {XK_Insert, 'k', 'I'}, {XK_Delete, 'k', 'D'}, {XK_Home, 'k', 'h'}, {XK_End, '@', '7'}, {XK_Prior, 'k', 'P'}, {XK_Next, 'k', 'N'}, {XK_Print, '%', '9'}, /* Keypad keys: */ #ifdef XK_KP_Left {XK_KP_Left, 'k', 'l'}, {XK_KP_Right, 'k', 'r'}, {XK_KP_Up, 'k', 'u'}, {XK_KP_Down, 'k', 'd'}, {XK_KP_Insert, KS_EXTRA, (char_u)KE_KINS}, {XK_KP_Delete, KS_EXTRA, (char_u)KE_KDEL}, {XK_KP_Home, 'K', '1'}, {XK_KP_End, 'K', '4'}, {XK_KP_Prior, 'K', '3'}, {XK_KP_Next, 'K', '5'}, {XK_KP_Add, 'K', '6'}, {XK_KP_Subtract, 'K', '7'}, {XK_KP_Divide, 'K', '8'}, {XK_KP_Multiply, 'K', '9'}, {XK_KP_Enter, 'K', 'A'}, {XK_KP_Decimal, 'K', 'B'}, {XK_KP_0, 'K', 'C'}, {XK_KP_1, 'K', 'D'}, {XK_KP_2, 'K', 'E'}, {XK_KP_3, 'K', 'F'}, {XK_KP_4, 'K', 'G'}, {XK_KP_5, 'K', 'H'}, {XK_KP_6, 'K', 'I'}, {XK_KP_7, 'K', 'J'}, {XK_KP_8, 'K', 'K'}, {XK_KP_9, 'K', 'L'}, #endif /* End of list marker: */ {(KeySym)0, 0, 0} }; #define XtNboldFont "boldFont" #define XtCBoldFont "BoldFont" #define XtNitalicFont "italicFont" #define XtCItalicFont "ItalicFont" #define XtNboldItalicFont "boldItalicFont" #define XtCBoldItalicFont "BoldItalicFont" #define XtNscrollbarWidth "scrollbarWidth" #define XtCScrollbarWidth "ScrollbarWidth" #define XtNmenuHeight "menuHeight" #define XtCMenuHeight "MenuHeight" #define XtNmenuFont "menuFont" #define XtCMenuFont "MenuFont" #define XtNmenuFontSet "menuFontSet" #define XtCMenuFontSet "MenuFontSet" /* Resources for setting the foreground and background colors of menus */ #define XtNmenuBackground "menuBackground" #define XtCMenuBackground "MenuBackground" #define XtNmenuForeground "menuForeground" #define XtCMenuForeground "MenuForeground" /* Resources for setting the foreground and background colors of scrollbars */ #define XtNscrollBackground "scrollBackground" #define XtCScrollBackground "ScrollBackground" #define XtNscrollForeground "scrollForeground" #define XtCScrollForeground "ScrollForeground" /* Resources for setting the foreground and background colors of tooltip */ #define XtNtooltipBackground "tooltipBackground" #define XtCTooltipBackground "TooltipBackground" #define XtNtooltipForeground "tooltipForeground" #define XtCTooltipForeground "TooltipForeground" #define XtNtooltipFont "tooltipFont" #define XtCTooltipFont "TooltipFont" /* * X Resources: */ static XtResource vim_resources[] = { { XtNforeground, XtCForeground, XtRPixel, sizeof(Pixel), XtOffsetOf(gui_T, def_norm_pixel), XtRString, XtDefaultForeground }, { XtNbackground, XtCBackground, XtRPixel, sizeof(Pixel), XtOffsetOf(gui_T, def_back_pixel), XtRString, XtDefaultBackground }, { XtNfont, XtCFont, XtRString, sizeof(String *), XtOffsetOf(gui_T, rsrc_font_name), XtRImmediate, XtDefaultFont }, { XtNboldFont, XtCBoldFont, XtRString, sizeof(String *), XtOffsetOf(gui_T, rsrc_bold_font_name), XtRImmediate, "" }, { XtNitalicFont, XtCItalicFont, XtRString, sizeof(String *), XtOffsetOf(gui_T, rsrc_ital_font_name), XtRImmediate, "" }, { XtNboldItalicFont, XtCBoldItalicFont, XtRString, sizeof(String *), XtOffsetOf(gui_T, rsrc_boldital_font_name), XtRImmediate, "" }, { XtNgeometry, XtCGeometry, XtRString, sizeof(String *), XtOffsetOf(gui_T, geom), XtRImmediate, "" }, { XtNreverseVideo, XtCReverseVideo, XtRBool, sizeof(Bool), XtOffsetOf(gui_T, rsrc_rev_video), XtRImmediate, (XtPointer)False }, { XtNborderWidth, XtCBorderWidth, XtRInt, sizeof(int), XtOffsetOf(gui_T, border_width), XtRImmediate, (XtPointer)2 }, { XtNscrollbarWidth, XtCScrollbarWidth, XtRInt, sizeof(int), XtOffsetOf(gui_T, scrollbar_width), XtRImmediate, (XtPointer)SB_DEFAULT_WIDTH }, #ifdef FEAT_MENU # ifdef FEAT_GUI_ATHENA /* with Motif the height is always computed */ { XtNmenuHeight, XtCMenuHeight, XtRInt, sizeof(int), XtOffsetOf(gui_T, menu_height), XtRImmediate, (XtPointer)MENU_DEFAULT_HEIGHT /* Should figure out at run time */ }, # endif { # ifdef FONTSET_ALWAYS XtNmenuFontSet, XtCMenuFontSet, #else XtNmenuFont, XtCMenuFont, #endif XtRString, sizeof(char *), XtOffsetOf(gui_T, rsrc_menu_font_name), XtRString, DFLT_MENU_FONT }, #endif { XtNmenuForeground, XtCMenuForeground, XtRString, sizeof(char *), XtOffsetOf(gui_T, rsrc_menu_fg_name), XtRString, DFLT_MENU_FG_COLOR }, { XtNmenuBackground, XtCMenuBackground, XtRString, sizeof(char *), XtOffsetOf(gui_T, rsrc_menu_bg_name), XtRString, DFLT_MENU_BG_COLOR }, { XtNscrollForeground, XtCScrollForeground, XtRString, sizeof(char *), XtOffsetOf(gui_T, rsrc_scroll_fg_name), XtRString, DFLT_SCROLL_FG_COLOR }, { XtNscrollBackground, XtCScrollBackground, XtRString, sizeof(char *), XtOffsetOf(gui_T, rsrc_scroll_bg_name), XtRString, DFLT_SCROLL_BG_COLOR }, #ifdef FEAT_BEVAL { XtNtooltipForeground, XtCTooltipForeground, XtRString, sizeof(char *), XtOffsetOf(gui_T, rsrc_tooltip_fg_name), XtRString, DFLT_TOOLTIP_FG_COLOR }, { XtNtooltipBackground, XtCTooltipBackground, XtRString, sizeof(char *), XtOffsetOf(gui_T, rsrc_tooltip_bg_name), XtRString, DFLT_TOOLTIP_BG_COLOR }, { XtNtooltipFont, XtCTooltipFont, XtRString, sizeof(char *), XtOffsetOf(gui_T, rsrc_tooltip_font_name), XtRString, DFLT_TOOLTIP_FONT }, /* This one isn't really needed, keep for Sun Workshop? */ { "balloonEvalFontSet", XtCFontSet, XtRFontSet, sizeof(XFontSet), XtOffsetOf(gui_T, tooltip_fontset), XtRImmediate, (XtPointer)NOFONTSET }, #endif /* FEAT_BEVAL */ #ifdef FEAT_XIM { "preeditType", "PreeditType", XtRString, sizeof(char*), XtOffsetOf(gui_T, rsrc_preedit_type_name), XtRString, (XtPointer)"OverTheSpot,OffTheSpot,Root" }, { "inputMethod", "InputMethod", XtRString, sizeof(char*), XtOffsetOf(gui_T, rsrc_input_method), XtRString, NULL }, #endif /* FEAT_XIM */ }; /* * This table holds all the X GUI command line options allowed. This includes * the standard ones so that we can skip them when vim is started without the * GUI (but the GUI might start up later). * When changing this, also update doc/vim_gui.txt and the usage message!!! */ static XrmOptionDescRec cmdline_options[] = { /* We handle these options ourselves */ {"-bg", ".background", XrmoptionSepArg, NULL}, {"-background", ".background", XrmoptionSepArg, NULL}, {"-fg", ".foreground", XrmoptionSepArg, NULL}, {"-foreground", ".foreground", XrmoptionSepArg, NULL}, {"-fn", ".font", XrmoptionSepArg, NULL}, {"-font", ".font", XrmoptionSepArg, NULL}, {"-boldfont", ".boldFont", XrmoptionSepArg, NULL}, {"-italicfont", ".italicFont", XrmoptionSepArg, NULL}, {"-geom", ".geometry", XrmoptionSepArg, NULL}, {"-geometry", ".geometry", XrmoptionSepArg, NULL}, {"-reverse", "*reverseVideo", XrmoptionNoArg, "True"}, {"-rv", "*reverseVideo", XrmoptionNoArg, "True"}, {"+reverse", "*reverseVideo", XrmoptionNoArg, "False"}, {"+rv", "*reverseVideo", XrmoptionNoArg, "False"}, {"-display", ".display", XrmoptionSepArg, NULL}, {"-iconic", ".iconic", XrmoptionNoArg, "True"}, {"-name", ".name", XrmoptionSepArg, NULL}, {"-bw", ".borderWidth", XrmoptionSepArg, NULL}, {"-borderwidth", ".borderWidth", XrmoptionSepArg, NULL}, {"-sw", ".scrollbarWidth", XrmoptionSepArg, NULL}, {"-scrollbarwidth", ".scrollbarWidth", XrmoptionSepArg, NULL}, {"-mh", ".menuHeight", XrmoptionSepArg, NULL}, {"-menuheight", ".menuHeight", XrmoptionSepArg, NULL}, #ifdef FONTSET_ALWAYS {"-mf", ".menuFontSet", XrmoptionSepArg, NULL}, {"-menufont", ".menuFontSet", XrmoptionSepArg, NULL}, {"-menufontset", ".menuFontSet", XrmoptionSepArg, NULL}, #else {"-mf", ".menuFont", XrmoptionSepArg, NULL}, {"-menufont", ".menuFont", XrmoptionSepArg, NULL}, #endif {"-xrm", NULL, XrmoptionResArg, NULL} }; static int gui_argc = 0; static char **gui_argv = NULL; /* * Call-back routines. */ static void gui_x11_timer_cb(timed_out, interval_id) XtPointer timed_out; XtIntervalId *interval_id UNUSED; { *((int *)timed_out) = TRUE; } static void gui_x11_visibility_cb(w, dud, event, dum) Widget w UNUSED; XtPointer dud UNUSED; XEvent *event; Boolean *dum UNUSED; { if (event->type != VisibilityNotify) return; gui.visibility = event->xvisibility.state; /* * When we do an XCopyArea(), and the window is partially obscured, we want * to receive an event to tell us whether it worked or not. */ XSetGraphicsExposures(gui.dpy, gui.text_gc, gui.visibility != VisibilityUnobscured); /* This is needed for when redrawing is slow. */ gui_mch_update(); } static void gui_x11_expose_cb(w, dud, event, dum) Widget w UNUSED; XtPointer dud UNUSED; XEvent *event; Boolean *dum UNUSED; { XExposeEvent *gevent; int new_x; if (event->type != Expose) return; out_flush(); /* make sure all output has been processed */ gevent = (XExposeEvent *)event; gui_redraw(gevent->x, gevent->y, gevent->width, gevent->height); new_x = FILL_X(0); /* Clear the border areas if needed */ if (gevent->x < new_x) XClearArea(gui.dpy, gui.wid, 0, 0, new_x, 0, False); if (gevent->y < FILL_Y(0)) XClearArea(gui.dpy, gui.wid, 0, 0, 0, FILL_Y(0), False); if (gevent->x > FILL_X(Columns)) XClearArea(gui.dpy, gui.wid, FILL_X((int)Columns), 0, 0, 0, False); if (gevent->y > FILL_Y(Rows)) XClearArea(gui.dpy, gui.wid, 0, FILL_Y((int)Rows), 0, 0, False); /* This is needed for when redrawing is slow. */ gui_mch_update(); } #if ((defined(FEAT_NETBEANS_INTG) || defined(FEAT_SUN_WORKSHOP)) \ && defined(FEAT_GUI_MOTIF)) || defined(PROTO) /* * This function fills in the XRectangle object with the current x,y * coordinates and height, width so that an XtVaSetValues to the same shell of * those resources will restore the window to its former position and * dimensions. * * Note: This function may fail, in which case the XRectangle will be * unchanged. Be sure to have the XRectangle set with the proper values for a * failed condition prior to calling this function. */ static void shellRectangle(Widget shell, XRectangle *r) { Window rootw, shellw, child, parentw; int absx, absy; XWindowAttributes a; Window *children; unsigned int childrenCount; shellw = XtWindow(shell); if (shellw == 0) return; for (;;) { XQueryTree(XtDisplay(shell), shellw, &rootw, &parentw, &children, &childrenCount); XFree(children); if (parentw == rootw) break; shellw = parentw; } XGetWindowAttributes(XtDisplay(shell), shellw, &a); XTranslateCoordinates(XtDisplay(shell), shellw, a.root, 0, 0, &absx, &absy, &child); r->x = absx; r->y = absy; XtVaGetValues(shell, XmNheight, &r->height, XmNwidth, &r->width, NULL); } #endif static void gui_x11_resize_window_cb(w, dud, event, dum) Widget w UNUSED; XtPointer dud UNUSED; XEvent *event; Boolean *dum UNUSED; { static int lastWidth, lastHeight; if (event->type != ConfigureNotify) return; if (event->xconfigure.width != lastWidth || event->xconfigure.height != lastHeight) { lastWidth = event->xconfigure.width; lastHeight = event->xconfigure.height; gui_resize_shell(event->xconfigure.width, event->xconfigure.height #ifdef FEAT_XIM - xim_get_status_area_height() #endif ); } #ifdef FEAT_SUN_WORKSHOP if (usingSunWorkShop) { XRectangle rec; shellRectangle(w, &rec); workshop_frame_moved(rec.x, rec.y, rec.width, rec.height); } #endif #if defined(FEAT_NETBEANS_INTG) && defined(FEAT_GUI_MOTIF) if (netbeans_active()) { XRectangle rec; shellRectangle(w, &rec); netbeans_frame_moved(rec.x, rec.y); } #endif #ifdef FEAT_XIM xim_set_preedit(); #endif } static void gui_x11_focus_change_cb(w, data, event, dum) Widget w UNUSED; XtPointer data UNUSED; XEvent *event; Boolean *dum UNUSED; { gui_focus_change(event->type == FocusIn); } static void gui_x11_enter_cb(w, data, event, dum) Widget w UNUSED; XtPointer data UNUSED; XEvent *event UNUSED; Boolean *dum UNUSED; { gui_focus_change(TRUE); } static void gui_x11_leave_cb(w, data, event, dum) Widget w UNUSED; XtPointer data UNUSED; XEvent *event UNUSED; Boolean *dum UNUSED; { gui_focus_change(FALSE); } #if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE) # if X_HAVE_UTF8_STRING # define USE_UTF8LOOKUP # endif #endif void gui_x11_key_hit_cb(w, dud, event, dum) Widget w UNUSED; XtPointer dud UNUSED; XEvent *event; Boolean *dum UNUSED; { XKeyPressedEvent *ev_press; #ifdef FEAT_XIM char_u string2[256]; char_u string_shortbuf[256]; char_u *string = string_shortbuf; Boolean string_alloced = False; Status status; #else char_u string[4], string2[3]; #endif KeySym key_sym, key_sym2; int len, len2; int i; int modifiers; int key; ev_press = (XKeyPressedEvent *)event; #ifdef FEAT_XIM if (xic) { # ifdef USE_UTF8LOOKUP /* XFree86 4.0.2 or newer: Be able to get UTF-8 characters even when * the locale isn't utf-8. */ if (enc_utf8) len = Xutf8LookupString(xic, ev_press, (char *)string, sizeof(string_shortbuf), &key_sym, &status); else # endif len = XmbLookupString(xic, ev_press, (char *)string, sizeof(string_shortbuf), &key_sym, &status); if (status == XBufferOverflow) { string = (char_u *)XtMalloc(len + 1); string_alloced = True; # ifdef USE_UTF8LOOKUP /* XFree86 4.0.2 or newer: Be able to get UTF-8 characters even * when the locale isn't utf-8. */ if (enc_utf8) len = Xutf8LookupString(xic, ev_press, (char *)string, len, &key_sym, &status); else # endif len = XmbLookupString(xic, ev_press, (char *)string, len, &key_sym, &status); } if (status == XLookupNone || status == XLookupChars) key_sym = XK_VoidSymbol; # ifdef FEAT_MBYTE /* Do conversion from 'termencoding' to 'encoding'. When using * Xutf8LookupString() it has already been done. */ if (len > 0 && input_conv.vc_type != CONV_NONE # ifdef USE_UTF8LOOKUP && !enc_utf8 # endif ) { int maxlen = len * 4 + 40; /* guessed */ char_u *p = (char_u *)XtMalloc(maxlen); mch_memmove(p, string, len); if (string_alloced) XtFree((char *)string); string = p; string_alloced = True; len = convert_input(p, len, maxlen); } # endif /* Translate CSI to K_CSI, otherwise it could be recognized as the * start of a special key. */ for (i = 0; i < len; ++i) if (string[i] == CSI) { char_u *p = (char_u *)XtMalloc(len + 3); mch_memmove(p, string, i + 1); p[i + 1] = KS_EXTRA; p[i + 2] = (int)KE_CSI; mch_memmove(p + i + 3, string + i + 1, len - i); if (string_alloced) XtFree((char *)string); string = p; string_alloced = True; i += 2; len += 2; } } else #endif len = XLookupString(ev_press, (char *)string, sizeof(string), &key_sym, NULL); #ifdef SunXK_F36 /* * These keys have bogus lookup strings, and trapping them here is * easier than trying to XRebindKeysym() on them with every possible * combination of modifiers. */ if (key_sym == SunXK_F36 || key_sym == SunXK_F37) len = 0; #endif #ifdef FEAT_HANGULIN if ((key_sym == XK_space) && (ev_press->state & ShiftMask)) { hangul_input_state_toggle(); goto theend; } #endif if (key_sym == XK_space) string[0] = ' '; /* Otherwise Ctrl-Space doesn't work */ /* * Only on some machines ^_ requires Ctrl+Shift+minus. For consistency, * allow just Ctrl+minus too. */ if (key_sym == XK_minus && (ev_press->state & ControlMask)) string[0] = Ctrl__; #ifdef XK_ISO_Left_Tab /* why do we get XK_ISO_Left_Tab instead of XK_Tab for shift-tab? */ if (key_sym == XK_ISO_Left_Tab) { key_sym = XK_Tab; string[0] = TAB; len = 1; } #endif /* Check for Alt/Meta key (Mod1Mask), but not for a BS, DEL or character * that already has the 8th bit set. And not when using a double-byte * encoding, setting the 8th bit may make it the lead byte of a * double-byte character. */ if (len == 1 && (ev_press->state & Mod1Mask) && !(key_sym == XK_BackSpace || key_sym == XK_Delete) && (string[0] & 0x80) == 0 #ifdef FEAT_MBYTE && !enc_dbcs #endif ) { #if defined(FEAT_MENU) && defined(FEAT_GUI_MOTIF) /* Ignore ALT keys when they are used for the menu only */ if (gui.menu_is_active && (p_wak[0] == 'y' || (p_wak[0] == 'm' && gui_is_menu_shortcut(string[0])))) goto theend; #endif /* * Before we set the 8th bit, check to make sure the user doesn't * already have a mapping defined for this sequence. We determine this * by checking to see if the input would be the same without the * Alt/Meta key. * Don't do this for <S-M-Tab>, that should become K_S_TAB with ALT. */ ev_press->state &= ~Mod1Mask; len2 = XLookupString(ev_press, (char *)string2, sizeof(string2), &key_sym2, NULL); if (key_sym2 == XK_space) string2[0] = ' '; /* Otherwise Meta-Ctrl-Space doesn't work */ if ( len2 == 1 && string[0] == string2[0] && !(key_sym == XK_Tab && (ev_press->state & ShiftMask))) { string[0] |= 0x80; #ifdef FEAT_MBYTE if (enc_utf8) /* convert to utf-8 */ { string[1] = string[0] & 0xbf; string[0] = ((unsigned)string[0] >> 6) + 0xc0; if (string[1] == CSI) { string[2] = KS_EXTRA; string[3] = (int)KE_CSI; len = 4; } else len = 2; } #endif } else ev_press->state |= Mod1Mask; } if (len == 1 && string[0] == CSI) { string[1] = KS_EXTRA; string[2] = (int)KE_CSI; len = -3; } /* Check for special keys. Also do this when len == 1 (key has an ASCII * value) to detect backspace, delete and keypad keys. */ if (len == 0 || len == 1) { for (i = 0; special_keys[i].key_sym != (KeySym)0; i++) { if (special_keys[i].key_sym == key_sym) { string[0] = CSI; string[1] = special_keys[i].vim_code0; string[2] = special_keys[i].vim_code1; len = -3; break; } } } /* Unrecognised key is ignored. */ if (len == 0) goto theend; /* Special keys (and a few others) may have modifiers. Also when using a * double-byte encoding (can't set the 8th bit). */ if (len == -3 || key_sym == XK_space || key_sym == XK_Tab || key_sym == XK_Return || key_sym == XK_Linefeed || key_sym == XK_Escape #ifdef FEAT_MBYTE || (enc_dbcs && len == 1 && (ev_press->state & Mod1Mask)) #endif ) { modifiers = 0; if (ev_press->state & ShiftMask) modifiers |= MOD_MASK_SHIFT; if (ev_press->state & ControlMask) modifiers |= MOD_MASK_CTRL; if (ev_press->state & Mod1Mask) modifiers |= MOD_MASK_ALT; if (ev_press->state & Mod4Mask) modifiers |= MOD_MASK_META; /* * For some keys a shift modifier is translated into another key * code. */ if (len == -3) key = TO_SPECIAL(string[1], string[2]); else key = string[0]; key = simplify_key(key, &modifiers); if (key == CSI) key = K_CSI; if (IS_SPECIAL(key)) { string[0] = CSI; string[1] = K_SECOND(key); string[2] = K_THIRD(key); len = 3; } else { string[0] = key; len = 1; } if (modifiers != 0) { string2[0] = CSI; string2[1] = KS_MODIFIER; string2[2] = modifiers; add_to_input_buf(string2, 3); } } if (len == 1 && ((string[0] == Ctrl_C && ctrl_c_interrupts) #ifdef UNIX || (intr_char != 0 && string[0] == intr_char) #endif )) { trash_input_buf(); got_int = TRUE; } add_to_input_buf(string, len); /* * blank out the pointer if necessary */ if (p_mh) gui_mch_mousehide(TRUE); #if defined(FEAT_BEVAL_TIP) { BalloonEval *be; if ((be = gui_mch_currently_showing_beval()) != NULL) gui_mch_unpost_balloon(be); } #endif theend: {} /* some compilers need a statement here */ #ifdef FEAT_XIM if (string_alloced) XtFree((char *)string); #endif } static void gui_x11_mouse_cb(w, dud, event, dum) Widget w UNUSED; XtPointer dud UNUSED; XEvent *event; Boolean *dum UNUSED; { static XtIntervalId timer = (XtIntervalId)0; static int timed_out = TRUE; int button; int repeated_click = FALSE; int x, y; int_u x_modifiers; int_u vim_modifiers; if (event->type == MotionNotify) { /* Get the latest position, avoids lagging behind on a drag. */ x = event->xmotion.x; y = event->xmotion.y; x_modifiers = event->xmotion.state; button = (x_modifiers & (Button1Mask | Button2Mask | Button3Mask)) ? MOUSE_DRAG : ' '; /* * if our pointer is currently hidden, then we should show it. */ gui_mch_mousehide(FALSE); if (button != MOUSE_DRAG) /* just moving the rodent */ { #ifdef FEAT_MENU if (dud) /* moved in vimForm */ y -= gui.menu_height; #endif gui_mouse_moved(x, y); return; } } else { x = event->xbutton.x; y = event->xbutton.y; if (event->type == ButtonPress) { /* Handle multiple clicks */ if (!timed_out) { XtRemoveTimeOut(timer); repeated_click = TRUE; } timed_out = FALSE; timer = XtAppAddTimeOut(app_context, (long_u)p_mouset, gui_x11_timer_cb, &timed_out); switch (event->xbutton.button) { case Button1: button = MOUSE_LEFT; break; case Button2: button = MOUSE_MIDDLE; break; case Button3: button = MOUSE_RIGHT; break; case Button4: button = MOUSE_4; break; case Button5: button = MOUSE_5; break; default: return; /* Unknown button */ } } else if (event->type == ButtonRelease) button = MOUSE_RELEASE; else return; /* Unknown mouse event type */ x_modifiers = event->xbutton.state; #if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU) last_mouse_event = event->xbutton; #endif } vim_modifiers = 0x0; if (x_modifiers & ShiftMask) vim_modifiers |= MOUSE_SHIFT; if (x_modifiers & ControlMask) vim_modifiers |= MOUSE_CTRL; if (x_modifiers & Mod1Mask) /* Alt or Meta key */ vim_modifiers |= MOUSE_ALT; gui_send_mouse_event(button, x, y, repeated_click, vim_modifiers); } #ifdef FEAT_SNIFF /* ARGSUSED */ static void gui_x11_sniff_request_cb(closure, source, id) XtPointer closure UNUSED; int *source UNUSED; XtInputId *id UNUSED; { static char_u bytes[3] = {CSI, (int)KS_EXTRA, (int)KE_SNIFF}; add_to_input_buf(bytes, 3); } #endif /* * End of call-back routines */ /* * Parse the GUI related command-line arguments. Any arguments used are * deleted from argv, and *argc is decremented accordingly. This is called * when vim is started, whether or not the GUI has been started. */ void gui_mch_prepare(argc, argv) int *argc; char **argv; { int arg; int i; /* * Move all the entries in argv which are relevant to X into gui_argv. */ gui_argc = 0; gui_argv = (char **)lalloc((long_u)(*argc * sizeof(char *)), FALSE); if (gui_argv == NULL) return; gui_argv[gui_argc++] = argv[0]; arg = 1; while (arg < *argc) { /* Look for argv[arg] in cmdline_options[] table */ for (i = 0; i < (int)XtNumber(cmdline_options); i++) if (strcmp(argv[arg], cmdline_options[i].option) == 0) break; if (i < (int)XtNumber(cmdline_options)) { /* Remember finding "-rv" or "-reverse" */ if (strcmp("-rv", argv[arg]) == 0 || strcmp("-reverse", argv[arg]) == 0) found_reverse_arg = TRUE; else if ((strcmp("-fn", argv[arg]) == 0 || strcmp("-font", argv[arg]) == 0) && arg + 1 < *argc) font_argument = argv[arg + 1]; /* Found match in table, so move it into gui_argv */ gui_argv[gui_argc++] = argv[arg]; if (--*argc > arg) { mch_memmove(&argv[arg], &argv[arg + 1], (*argc - arg) * sizeof(char *)); if (cmdline_options[i].argKind != XrmoptionNoArg) { /* Move the options argument as well */ gui_argv[gui_argc++] = argv[arg]; if (--*argc > arg) mch_memmove(&argv[arg], &argv[arg + 1], (*argc - arg) * sizeof(char *)); } } argv[*argc] = NULL; } else #ifdef FEAT_SUN_WORKSHOP if (strcmp("-ws", argv[arg]) == 0) { usingSunWorkShop++; p_acd = TRUE; gui.dofork = FALSE; /* don't fork() when starting GUI */ mch_memmove(&argv[arg], &argv[arg + 1], (--*argc - arg) * sizeof(char *)); argv[*argc] = NULL; # ifdef WSDEBUG wsdebug_wait(WT_ENV | WT_WAIT | WT_STOP, "SPRO_GVIM_WAIT", 20); wsdebug_log_init("SPRO_GVIM_DEBUG", "SPRO_GVIM_DLEVEL"); # endif } else #endif #ifdef FEAT_NETBEANS_INTG if (strncmp("-nb", argv[arg], 3) == 0) { gui.dofork = FALSE; /* don't fork() when starting GUI */ netbeansArg = argv[arg]; mch_memmove(&argv[arg], &argv[arg + 1], (--*argc - arg) * sizeof(char *)); argv[*argc] = NULL; } else #endif arg++; } } #ifndef XtSpecificationRelease # define CARDINAL (Cardinal *) #else # if XtSpecificationRelease == 4 # define CARDINAL (Cardinal *) # else # define CARDINAL (int *) # endif #endif /* * Check if the GUI can be started. Called before gvimrc is sourced. * Return OK or FAIL. */ int gui_mch_init_check() { #ifdef FEAT_XIM XtSetLanguageProc(NULL, NULL, NULL); #endif open_app_context(); if (app_context != NULL) gui.dpy = XtOpenDisplay(app_context, 0, VIM_NAME, VIM_CLASS, cmdline_options, XtNumber(cmdline_options), CARDINAL &gui_argc, gui_argv); if (app_context == NULL || gui.dpy == NULL) { gui.dying = TRUE; EMSG(_(e_opendisp)); return FAIL; } return OK; } #ifdef USE_XSMP /* * Handle XSMP processing, de-registering the attachment upon error */ static XtInputId _xsmp_xtinputid; static void local_xsmp_handle_requests __ARGS((XtPointer c, int *s, XtInputId *i)); static void local_xsmp_handle_requests(c, s, i) XtPointer c UNUSED; int *s UNUSED; XtInputId *i UNUSED; { if (xsmp_handle_requests() == FAIL) XtRemoveInput(_xsmp_xtinputid); } #endif /* * Initialise the X GUI. Create all the windows, set up all the call-backs etc. * Returns OK for success, FAIL when the GUI can't be started. */ int gui_mch_init() { XtGCMask gc_mask; XGCValues gc_vals; int x, y, mask; unsigned w, h; #if 0 /* Uncomment this to enable synchronous mode for debugging */ XSynchronize(gui.dpy, True); #endif vimShell = XtVaAppCreateShell(VIM_NAME, VIM_CLASS, applicationShellWidgetClass, gui.dpy, NULL); /* * Get the application resources */ XtVaGetApplicationResources(vimShell, (XtPointer)&gui, vim_resources, XtNumber(vim_resources), NULL); gui.scrollbar_height = gui.scrollbar_width; /* * Get the colors ourselves. Using the automatic conversion doesn't * handle looking for approximate colors. */ /* NOTE: These next few lines are an exact duplicate of gui_athena.c's * gui_mch_def_colors(). Why? */ gui.menu_fg_pixel = gui_get_color((char_u *)gui.rsrc_menu_fg_name); gui.menu_bg_pixel = gui_get_color((char_u *)gui.rsrc_menu_bg_name); gui.scroll_fg_pixel = gui_get_color((char_u *)gui.rsrc_scroll_fg_name); gui.scroll_bg_pixel = gui_get_color((char_u *)gui.rsrc_scroll_bg_name); #ifdef FEAT_BEVAL gui.tooltip_fg_pixel = gui_get_color((char_u *)gui.rsrc_tooltip_fg_name); gui.tooltip_bg_pixel = gui_get_color((char_u *)gui.rsrc_tooltip_bg_name); #endif #if defined(FEAT_MENU) && defined(FEAT_GUI_ATHENA) /* If the menu height was set, don't change it at runtime */ if (gui.menu_height != MENU_DEFAULT_HEIGHT) gui.menu_height_fixed = TRUE; #endif /* Set default foreground and background colours */ gui.norm_pixel = gui.def_norm_pixel; gui.back_pixel = gui.def_back_pixel; /* Check if reverse video needs to be applied (on Sun it's done by X) */ if (gui.rsrc_rev_video && gui_get_lightness(gui.back_pixel) > gui_get_lightness(gui.norm_pixel)) { gui.norm_pixel = gui.def_back_pixel; gui.back_pixel = gui.def_norm_pixel; gui.def_norm_pixel = gui.norm_pixel; gui.def_back_pixel = gui.back_pixel; } /* Get the colors from the "Normal", "Tooltip", "Scrollbar" and "Menu" * group (set in syntax.c or in a vimrc file) */ set_normal_colors(); /* * Check that none of the colors are the same as the background color */ gui_check_colors(); /* * Set up the GCs. The font attributes will be set in gui_init_font(). */ gc_mask = GCForeground | GCBackground; gc_vals.foreground = gui.norm_pixel; gc_vals.background = gui.back_pixel; gui.text_gc = XtGetGC(vimShell, gc_mask, &gc_vals); gc_vals.foreground = gui.back_pixel; gc_vals.background = gui.norm_pixel; gui.back_gc = XtGetGC(vimShell, gc_mask, &gc_vals); gc_mask |= GCFunction; gc_vals.foreground = gui.norm_pixel ^ gui.back_pixel; gc_vals.background = gui.norm_pixel ^ gui.back_pixel; gc_vals.function = GXxor; gui.invert_gc = XtGetGC(vimShell, gc_mask, &gc_vals); gui.visibility = VisibilityUnobscured; x11_setup_atoms(gui.dpy); if (gui_win_x != -1 && gui_win_y != -1) gui_mch_set_winpos(gui_win_x, gui_win_y); /* Now adapt the supplied(?) geometry-settings */ /* Added by Kjetil Jacobsen <kjetilja@stud.cs.uit.no> */ if (gui.geom != NULL && *gui.geom != NUL) { mask = XParseGeometry((char *)gui.geom, &x, &y, &w, &h); if (mask & WidthValue) Columns = w; if (mask & HeightValue) { if (p_window > (long)h - 1 || !option_was_set((char_u *)"window")) p_window = h - 1; Rows = h; } /* * Set the (x,y) position of the main window only if specified in the * users geometry, so we get good defaults when they don't. This needs * to be done before the shell is popped up. */ if (mask & (XValue|YValue)) XtVaSetValues(vimShell, XtNgeometry, gui.geom, NULL); } gui_x11_create_widgets(); /* * Add an icon to Vim (Marcel Douben: 11 May 1998). */ if (vim_strchr(p_go, GO_ICON) != NULL) { #ifndef HAVE_XPM # include "vim_icon.xbm" # include "vim_mask.xbm" Arg arg[2]; XtSetArg(arg[0], XtNiconPixmap, XCreateBitmapFromData(gui.dpy, DefaultRootWindow(gui.dpy), (char *)vim_icon_bits, vim_icon_width, vim_icon_height)); XtSetArg(arg[1], XtNiconMask, XCreateBitmapFromData(gui.dpy, DefaultRootWindow(gui.dpy), (char *)vim_mask_icon_bits, vim_mask_icon_width, vim_mask_icon_height)); XtSetValues(vimShell, arg, (Cardinal)2); #else /* Use Pixmaps, looking much nicer. */ /* If you get an error message here, you still need to unpack the runtime * archive! */ # ifdef magick # undef magick # endif # define magick vim32x32 # include "../runtime/vim32x32.xpm" # undef magick # define magick vim16x16 # include "../runtime/vim16x16.xpm" # undef magick # define magick vim48x48 # include "../runtime/vim48x48.xpm" # undef magick static Pixmap icon = 0; static Pixmap icon_mask = 0; static char **magick = vim32x32; Window root_window; XIconSize *size; int number_sizes; Display *dsp; Screen *scr; XpmAttributes attr; Colormap cmap; /* * Adjust the icon to the preferences of the actual window manager. */ root_window = XRootWindowOfScreen(XtScreen(vimShell)); if (XGetIconSizes(XtDisplay(vimShell), root_window, &size, &number_sizes) != 0) { if (number_sizes > 0) { if (size->max_height >= 48 && size->max_height >= 48) magick = vim48x48; else if (size->max_height >= 32 && size->max_height >= 32) magick = vim32x32; else if (size->max_height >= 16 && size->max_height >= 16) magick = vim16x16; } } dsp = XtDisplay(vimShell); scr = XtScreen(vimShell); cmap = DefaultColormap(dsp, DefaultScreen(dsp)); XtVaSetValues(vimShell, XtNcolormap, cmap, NULL); attr.valuemask = 0L; attr.valuemask = XpmCloseness | XpmReturnPixels | XpmColormap | XpmDepth; attr.closeness = 65535; /* accuracy isn't crucial */ attr.colormap = cmap; attr.depth = DefaultDepthOfScreen(scr); if (!icon) { XpmCreatePixmapFromData(dsp, root_window, magick, &icon, &icon_mask, &attr); XpmFreeAttributes(&attr); } # ifdef FEAT_GUI_ATHENA XtVaSetValues(vimShell, XtNiconPixmap, icon, XtNiconMask, icon_mask, NULL); # else XtVaSetValues(vimShell, XmNiconPixmap, icon, XmNiconMask, icon_mask, NULL); # endif #endif } if (gui.color_approx) EMSG(_("Vim E458: Cannot allocate colormap entry, some colors may be incorrect")); #ifdef FEAT_SUN_WORKSHOP if (usingSunWorkShop) workshop_connect(app_context); #endif #ifdef FEAT_BEVAL gui_init_tooltip_font(); #endif #ifdef FEAT_MENU gui_init_menu_font(); #endif #ifdef USE_XSMP /* Attach listener on ICE connection */ if (-1 != xsmp_icefd) _xsmp_xtinputid = XtAppAddInput(app_context, xsmp_icefd, (XtPointer)XtInputReadMask, local_xsmp_handle_requests, NULL); #endif return OK; } /* * Called when starting the GUI fails after calling gui_mch_init(). */ void gui_mch_uninit() { gui_x11_destroy_widgets(); XtCloseDisplay(gui.dpy); gui.dpy = NULL; vimShell = (Widget)0; vim_free(gui_argv); gui_argv = NULL; } /* * Called when the foreground or background color has been changed. */ void gui_mch_new_colors() { long_u gc_mask; XGCValues gc_vals; gc_mask = GCForeground | GCBackground; gc_vals.foreground = gui.norm_pixel; gc_vals.background = gui.back_pixel; if (gui.text_gc != NULL) XChangeGC(gui.dpy, gui.text_gc, gc_mask, &gc_vals); gc_vals.foreground = gui.back_pixel; gc_vals.background = gui.norm_pixel; if (gui.back_gc != NULL) XChangeGC(gui.dpy, gui.back_gc, gc_mask, &gc_vals); gc_mask |= GCFunction; gc_vals.foreground = gui.norm_pixel ^ gui.back_pixel; gc_vals.background = gui.norm_pixel ^ gui.back_pixel; gc_vals.function = GXxor; if (gui.invert_gc != NULL) XChangeGC(gui.dpy, gui.invert_gc, gc_mask, &gc_vals); gui_x11_set_back_color(); } /* * Open the GUI window which was created by a call to gui_mch_init(). */ int gui_mch_open() { /* Actually open the window */ XtRealizeWidget(vimShell); XtManageChild(XtNameToWidget(vimShell, "*vimForm")); gui.wid = gui_x11_get_wid(); gui.blank_pointer = gui_x11_create_blank_mouse(); /* * Add a callback for the Close item on the window managers menu, and the * save-yourself event. */ wm_atoms[SAVE_YOURSELF_IDX] = XInternAtom(gui.dpy, "WM_SAVE_YOURSELF", False); wm_atoms[DELETE_WINDOW_IDX] = XInternAtom(gui.dpy, "WM_DELETE_WINDOW", False); XSetWMProtocols(gui.dpy, XtWindow(vimShell), wm_atoms, 2); XtAddEventHandler(vimShell, NoEventMask, True, gui_x11_wm_protocol_handler, NULL); #ifdef HAVE_X11_XMU_EDITRES_H /* * Enable editres protocol (see "man editres"). * Usually will need to add -lXmu to the linker line as well. */ XtAddEventHandler(vimShell, (EventMask)0, True, _XEditResCheckMessages, (XtPointer)NULL); #endif #ifdef FEAT_CLIENTSERVER if (serverName == NULL && serverDelayedStartName != NULL) { /* This is a :gui command in a plain vim with no previous server */ commWindow = XtWindow(vimShell); (void)serverRegisterName(gui.dpy, serverDelayedStartName); } else { /* * Cannot handle "widget-less" windows with XtProcessEvent() we'll * have to change the "server" registration to that of the main window * If we have not registered a name yet, remember the window */ serverChangeRegisteredWindow(gui.dpy, XtWindow(vimShell)); } XtAddEventHandler(vimShell, PropertyChangeMask, False, gui_x11_send_event_handler, NULL); #endif #if defined(FEAT_MENU) && defined(FEAT_GUI_ATHENA) /* The Athena GUI needs this again after opening the window */ gui_position_menu(); # ifdef FEAT_TOOLBAR gui_mch_set_toolbar_pos(0, gui.menu_height, gui.menu_width, gui.toolbar_height); # endif #endif /* Get the colors for the highlight groups (gui_check_colors() might have * changed them) */ highlight_gui_started(); /* re-init colors and fonts */ #ifdef FEAT_HANGULIN hangul_keyboard_set(); #endif #ifdef FEAT_XIM xim_init(); #endif #ifdef FEAT_SUN_WORKSHOP workshop_postinit(); #endif return OK; } #if defined(FEAT_BEVAL) || defined(PROTO) /* * Convert the tooltip fontset name to an XFontSet. */ void gui_init_tooltip_font() { XrmValue from, to; from.addr = (char *)gui.rsrc_tooltip_font_name; from.size = strlen(from.addr); to.addr = (XtPointer)&gui.tooltip_fontset; to.size = sizeof(XFontSet); if (XtConvertAndStore(vimShell, XtRString, &from, XtRFontSet, &to) == False) { /* Failed. What to do? */ } } #endif #if defined(FEAT_MENU) || defined(PROTO) /* Convert the menu font/fontset name to an XFontStruct/XFontset */ void gui_init_menu_font() { XrmValue from, to; #ifdef FONTSET_ALWAYS from.addr = (char *)gui.rsrc_menu_font_name; from.size = strlen(from.addr); to.addr = (XtPointer)&gui.menu_fontset; to.size = sizeof(GuiFontset); if (XtConvertAndStore(vimShell, XtRString, &from, XtRFontSet, &to) == False) { /* Failed. What to do? */ } #else from.addr = (char *)gui.rsrc_menu_font_name; from.size = strlen(from.addr); to.addr = (XtPointer)&gui.menu_font; to.size = sizeof(GuiFont); if (XtConvertAndStore(vimShell, XtRString, &from, XtRFontStruct, &to) == False) { /* Failed. What to do? */ } #endif } #endif void gui_mch_exit(rc) int rc UNUSED; { #if 0 /* Lesstif gives an error message here, and so does Solaris. The man page * says that this isn't needed when exiting, so just skip it. */ XtCloseDisplay(gui.dpy); #endif vim_free(gui_argv); gui_argv = NULL; } /* * Get the position of the top left corner of the window. */ int gui_mch_get_winpos(x, y) int *x, *y; { Dimension xpos, ypos; XtVaGetValues(vimShell, XtNx, &xpos, XtNy, &ypos, NULL); *x = xpos; *y = ypos; return OK; } /* * Set the position of the top left corner of the window to the given * coordinates. */ void gui_mch_set_winpos(x, y) int x, y; { XtVaSetValues(vimShell, XtNx, x, XtNy, y, NULL); } void gui_mch_set_shellsize(width, height, min_width, min_height, base_width, base_height, direction) int width; int height; int min_width; int min_height; int base_width; int base_height; int direction UNUSED; { #ifdef FEAT_XIM height += xim_get_status_area_height(), #endif XtVaSetValues(vimShell, XtNwidthInc, gui.char_width, XtNheightInc, gui.char_height, #if defined(XtSpecificationRelease) && XtSpecificationRelease >= 4 XtNbaseWidth, base_width, XtNbaseHeight, base_height, #endif XtNminWidth, min_width, XtNminHeight, min_height, XtNwidth, width, XtNheight, height, NULL); } /* * Allow 10 pixels for horizontal borders, 'guiheadroom' for vertical borders. * Is there no way in X to find out how wide the borders really are? */ void gui_mch_get_screen_dimensions(screen_w, screen_h) int *screen_w; int *screen_h; { *screen_w = DisplayWidth(gui.dpy, DefaultScreen(gui.dpy)) - 10; *screen_h = DisplayHeight(gui.dpy, DefaultScreen(gui.dpy)) - p_ghr; } /* * Initialise vim to use the font "font_name". If it's NULL, pick a default * font. * If "fontset" is TRUE, load the "font_name" as a fontset. * Return FAIL if the font could not be loaded, OK otherwise. */ int gui_mch_init_font(font_name, do_fontset) char_u *font_name; int do_fontset UNUSED; { XFontStruct *font = NULL; #ifdef FEAT_XFONTSET XFontSet fontset = NULL; #endif #ifdef FEAT_GUI_MOTIF /* A font name equal "*" is indicating, that we should activate the font * selection dialogue to get a new font name. So let us do it here. */ if (font_name != NULL && STRCMP(font_name, "*") == 0) font_name = gui_xm_select_font(hl_get_font_name()); #endif #ifdef FEAT_XFONTSET if (do_fontset) { /* If 'guifontset' is set, VIM treats all font specifications as if * they were fontsets, and 'guifontset' becomes the default. */ if (font_name != NULL) { fontset = (XFontSet)gui_mch_get_fontset(font_name, FALSE, TRUE); if (fontset == NULL) return FAIL; } } else #endif { if (font_name == NULL) { /* * If none of the fonts in 'font' could be loaded, try the one set * in the X resource, and finally just try using DFLT_FONT, which * will hopefully always be there. */ font_name = gui.rsrc_font_name; font = (XFontStruct *)gui_mch_get_font(font_name, FALSE); if (font == NULL) font_name = (char_u *)DFLT_FONT; } if (font == NULL) font = (XFontStruct *)gui_mch_get_font(font_name, FALSE); if (font == NULL) return FAIL; } gui_mch_free_font(gui.norm_font); #ifdef FEAT_XFONTSET gui_mch_free_fontset(gui.fontset); if (fontset != NULL) { gui.norm_font = NOFONT; gui.fontset = (GuiFontset)fontset; gui.char_width = fontset_width(fontset); gui.char_height = fontset_height(fontset) + p_linespace; gui.char_ascent = fontset_ascent(fontset) + p_linespace / 2; } else #endif { gui.norm_font = (GuiFont)font; #ifdef FEAT_XFONTSET gui.fontset = NOFONTSET; #endif gui.char_width = font->max_bounds.width; gui.char_height = font->ascent + font->descent + p_linespace; gui.char_ascent = font->ascent + p_linespace / 2; } hl_set_font_name(font_name); /* * Try to load other fonts for bold, italic, and bold-italic. * We should also try to work out what font to use for these when they are * not specified by X resources, but we don't yet. */ if (font_name == gui.rsrc_font_name) { if (gui.bold_font == NOFONT && gui.rsrc_bold_font_name != NULL && *gui.rsrc_bold_font_name != NUL) gui.bold_font = gui_mch_get_font(gui.rsrc_bold_font_name, FALSE); if (gui.ital_font == NOFONT && gui.rsrc_ital_font_name != NULL && *gui.rsrc_ital_font_name != NUL) gui.ital_font = gui_mch_get_font(gui.rsrc_ital_font_name, FALSE); if (gui.boldital_font == NOFONT && gui.rsrc_boldital_font_name != NULL && *gui.rsrc_boldital_font_name != NUL) gui.boldital_font = gui_mch_get_font(gui.rsrc_boldital_font_name, FALSE); } else { /* When not using the font specified by the resources, also don't use * the bold/italic fonts, otherwise setting 'guifont' will look very * strange. */ if (gui.bold_font != NOFONT) { XFreeFont(gui.dpy, (XFontStruct *)gui.bold_font); gui.bold_font = NOFONT; } if (gui.ital_font != NOFONT) { XFreeFont(gui.dpy, (XFontStruct *)gui.ital_font); gui.ital_font = NOFONT; } if (gui.boldital_font != NOFONT) { XFreeFont(gui.dpy, (XFontStruct *)gui.boldital_font); gui.boldital_font = NOFONT; } } #ifdef FEAT_GUI_MOTIF gui_motif_synch_fonts(); #endif return OK; } /* * Get a font structure for highlighting. */ GuiFont gui_mch_get_font(name, giveErrorIfMissing) char_u *name; int giveErrorIfMissing; { XFontStruct *font; if (!gui.in_use || name == NULL) /* can't do this when GUI not running */ return NOFONT; font = XLoadQueryFont(gui.dpy, (char *)name); if (font == NULL) { if (giveErrorIfMissing) EMSG2(_(e_font), name); return NOFONT; } #ifdef DEBUG printf("Font Information for '%s':\n", name); printf(" w = %d, h = %d, ascent = %d, descent = %d\n", font->max_bounds.width, font->ascent + font->descent, font->ascent, font->descent); printf(" max ascent = %d, max descent = %d, max h = %d\n", font->max_bounds.ascent, font->max_bounds.descent, font->max_bounds.ascent + font->max_bounds.descent); printf(" min lbearing = %d, min rbearing = %d\n", font->min_bounds.lbearing, font->min_bounds.rbearing); printf(" max lbearing = %d, max rbearing = %d\n", font->max_bounds.lbearing, font->max_bounds.rbearing); printf(" leftink = %d, rightink = %d\n", (font->min_bounds.lbearing < 0), (font->max_bounds.rbearing > font->max_bounds.width)); printf("\n"); #endif if (font->max_bounds.width != font->min_bounds.width) { EMSG2(_(e_fontwidth), name); XFreeFont(gui.dpy, font); return NOFONT; } return (GuiFont)font; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return the name of font "font" in allocated memory. * Don't know how to get the actual name, thus use the provided name. */ char_u * gui_mch_get_fontname(font, name) GuiFont font UNUSED; char_u *name; { if (name == NULL) return NULL; return vim_strsave(name); } #endif /* * Adjust gui.char_height (after 'linespace' was changed). */ int gui_mch_adjust_charheight() { #ifdef FEAT_XFONTSET if (gui.fontset != NOFONTSET) { gui.char_height = fontset_height((XFontSet)gui.fontset) + p_linespace; gui.char_ascent = fontset_ascent((XFontSet)gui.fontset) + p_linespace / 2; } else #endif { XFontStruct *font = (XFontStruct *)gui.norm_font; gui.char_height = font->ascent + font->descent + p_linespace; gui.char_ascent = font->ascent + p_linespace / 2; } return OK; } /* * Set the current text font. */ void gui_mch_set_font(font) GuiFont font; { static Font prev_font = (Font)-1; Font fid = ((XFontStruct *)font)->fid; if (fid != prev_font) { XSetFont(gui.dpy, gui.text_gc, fid); XSetFont(gui.dpy, gui.back_gc, fid); prev_font = fid; gui.char_ascent = ((XFontStruct *)font)->ascent + p_linespace / 2; } #ifdef FEAT_XFONTSET current_fontset = (XFontSet)NULL; #endif } #if defined(FEAT_XFONTSET) || defined(PROTO) /* * Set the current text fontset. * Adjust the ascent, in case it's different. */ void gui_mch_set_fontset(fontset) GuiFontset fontset; { current_fontset = (XFontSet)fontset; gui.char_ascent = fontset_ascent(current_fontset) + p_linespace / 2; } #endif /* * If a font is not going to be used, free its structure. */ void gui_mch_free_font(font) GuiFont font; { if (font != NOFONT) XFreeFont(gui.dpy, (XFontStruct *)font); } #if defined(FEAT_XFONTSET) || defined(PROTO) /* * If a fontset is not going to be used, free its structure. */ void gui_mch_free_fontset(fontset) GuiFontset fontset; { if (fontset != NOFONTSET) XFreeFontSet(gui.dpy, (XFontSet)fontset); } /* * Load the fontset "name". * Return a reference to the fontset, or NOFONTSET when failing. */ GuiFontset gui_mch_get_fontset(name, giveErrorIfMissing, fixed_width) char_u *name; int giveErrorIfMissing; int fixed_width; { XFontSet fontset; char **missing, *def_str; int num_missing; if (!gui.in_use || name == NULL) return NOFONTSET; fontset = XCreateFontSet(gui.dpy, (char *)name, &missing, &num_missing, &def_str); if (num_missing > 0) { int i; if (giveErrorIfMissing) { EMSG2(_("E250: Fonts for the following charsets are missing in fontset %s:"), name); for (i = 0; i < num_missing; i++) EMSG2("%s", missing[i]); } XFreeStringList(missing); } if (fontset == NULL) { if (giveErrorIfMissing) EMSG2(_(e_fontset), name); return NOFONTSET; } if (fixed_width && check_fontset_sanity(fontset) == FAIL) { XFreeFontSet(gui.dpy, fontset); return NOFONTSET; } return (GuiFontset)fontset; } /* * Check if fontset "fs" is fixed width. */ static int check_fontset_sanity(fs) XFontSet fs; { XFontStruct **xfs; char **font_name; int fn; char *base_name; int i; int min_width; int min_font_idx = 0; base_name = XBaseFontNameListOfFontSet(fs); fn = XFontsOfFontSet(fs, &xfs, &font_name); for (i = 0; i < fn; i++) { if (xfs[i]->max_bounds.width != xfs[i]->min_bounds.width) { EMSG2(_("E252: Fontset name: %s"), base_name); EMSG2(_("Font '%s' is not fixed-width"), font_name[i]); return FAIL; } } /* scan base font width */ min_width = 32767; for (i = 0; i < fn; i++) { if (xfs[i]->max_bounds.width<min_width) { min_width = xfs[i]->max_bounds.width; min_font_idx = i; } } for (i = 0; i < fn; i++) { if ( xfs[i]->max_bounds.width != 2 * min_width && xfs[i]->max_bounds.width != min_width) { EMSG2(_("E253: Fontset name: %s\n"), base_name); EMSG2(_("Font0: %s\n"), font_name[min_font_idx]); EMSG2(_("Font1: %s\n"), font_name[i]); EMSGN(_("Font%ld width is not twice that of font0\n"), i); EMSGN(_("Font0 width: %ld\n"), xfs[min_font_idx]->max_bounds.width); EMSGN(_("Font1 width: %ld\n\n"), xfs[i]->max_bounds.width); return FAIL; } } /* it seems ok. Good Luck!! */ return OK; } static int fontset_width(fs) XFontSet fs; { return XmbTextEscapement(fs, "Vim", 3) / 3; } int fontset_height(fs) XFontSet fs; { XFontSetExtents *extents; extents = XExtentsOfFontSet(fs); return extents->max_logical_extent.height; } #if (defined(FONTSET_ALWAYS) && defined(FEAT_GUI_ATHENA) \ && defined(FEAT_MENU)) || defined(PROTO) /* * Returns the bounding box height around the actual glyph image of all * characters in all fonts of the fontset. */ int fontset_height2(fs) XFontSet fs; { XFontSetExtents *extents; extents = XExtentsOfFontSet(fs); return extents->max_ink_extent.height; } #endif /* NOT USED YET static int fontset_descent(fs) XFontSet fs; { XFontSetExtents *extents; extents = XExtentsOfFontSet (fs); return extents->max_logical_extent.height + extents->max_logical_extent.y; } */ static int fontset_ascent(fs) XFontSet fs; { XFontSetExtents *extents; extents = XExtentsOfFontSet(fs); return -extents->max_logical_extent.y; } #endif /* FEAT_XFONTSET */ /* * Return the Pixel value (color) for the given color name. * Return INVALCOLOR for error. */ guicolor_T gui_mch_get_color(reqname) char_u *reqname; { int i; char_u *name = reqname; Colormap colormap; XColor color; static char *(vimnames[][2]) = { /* A number of colors that some X11 systems don't have */ {"LightRed", "#FFBBBB"}, {"LightGreen", "#88FF88"}, {"LightMagenta","#FFBBFF"}, {"DarkCyan", "#008888"}, {"DarkBlue", "#0000BB"}, {"DarkRed", "#BB0000"}, {"DarkMagenta", "#BB00BB"}, {"DarkGrey", "#BBBBBB"}, {"DarkYellow", "#BBBB00"}, {"Gray10", "#1A1A1A"}, {"Grey10", "#1A1A1A"}, {"Gray20", "#333333"}, {"Grey20", "#333333"}, {"Gray30", "#4D4D4D"}, {"Grey30", "#4D4D4D"}, {"Gray40", "#666666"}, {"Grey40", "#666666"}, {"Gray50", "#7F7F7F"}, {"Grey50", "#7F7F7F"}, {"Gray60", "#999999"}, {"Grey60", "#999999"}, {"Gray70", "#B3B3B3"}, {"Grey70", "#B3B3B3"}, {"Gray80", "#CCCCCC"}, {"Grey80", "#CCCCCC"}, {"Gray90", "#E5E5E5"}, {"Grey90", "#E5E5E5"}, {NULL, NULL} }; /* can't do this when GUI not running */ if (!gui.in_use || *reqname == NUL) return INVALCOLOR; colormap = DefaultColormap(gui.dpy, XDefaultScreen(gui.dpy)); /* Do this twice if the name isn't recognized. */ while (name != NULL) { i = XParseColor(gui.dpy, colormap, (char *)name, &color); #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) if (i == 0) { char *old; /* The X11 system is trying to resolve named colors only by names * corresponding to the current locale language. But Vim scripts * usually contain the English color names. Therefore we have to * try a second time here with the native "C" locale set. * Hopefully, restoring the old locale this way works on all * systems... */ old = setlocale(LC_ALL, NULL); if (old != NULL && STRCMP(old, "C") != 0) { old = (char *)vim_strsave((char_u *)old); setlocale(LC_ALL, "C"); i = XParseColor(gui.dpy, colormap, (char *)name, &color); setlocale(LC_ALL, old); vim_free(old); } } #endif if (i != 0 && (XAllocColor(gui.dpy, colormap, &color) != 0 || find_closest_color(colormap, &color) == OK)) return (guicolor_T)color.pixel; /* check for a few builtin names */ for (i = 0; ; ++i) { if (vimnames[i][0] == NULL) { name = NULL; break; } if (STRICMP(name, vimnames[i][0]) == 0) { name = (char_u *)vimnames[i][1]; break; } } } return INVALCOLOR; } /* * Find closest color for "colorPtr" in "colormap". set "colorPtr" to the * resulting color. * Based on a similar function in TCL. * Return FAIL if not able to find or allocate a color. */ static int find_closest_color(colormap, colorPtr) Colormap colormap; XColor *colorPtr; { double tmp, distance, closestDistance; int i, closest, numFound, cmap_size; XColor *colortable; XVisualInfo template, *visInfoPtr; template.visualid = XVisualIDFromVisual(DefaultVisual(gui.dpy, XDefaultScreen(gui.dpy))); visInfoPtr = XGetVisualInfo(gui.dpy, (long)VisualIDMask, &template, &numFound); if (numFound < 1) /* FindClosestColor couldn't lookup visual */ return FAIL; cmap_size = visInfoPtr->colormap_size; XFree((char *)visInfoPtr); colortable = (XColor *)alloc((unsigned)(cmap_size * sizeof(XColor))); if (!colortable) return FAIL; /* out of memory */ for (i = 0; i < cmap_size; i++) colortable[i].pixel = (unsigned long)i; XQueryColors (gui.dpy, colormap, colortable, cmap_size); /* * Find the color that best approximates the desired one, then * try to allocate that color. If that fails, it must mean that * the color was read-write (so we can't use it, since it's owner * might change it) or else it was already freed. Try again, * over and over again, until something succeeds. */ closestDistance = 1e30; closest = 0; for (i = 0; i < cmap_size; i++) { /* * Use Euclidean distance in RGB space, weighted by Y (of YIQ) * as the objective function; this accounts for differences * in the color sensitivity of the eye. */ tmp = .30 * (((int)colorPtr->red) - (int)colortable[i].red); distance = tmp * tmp; tmp = .61 * (((int)colorPtr->green) - (int)colortable[i].green); distance += tmp * tmp; tmp = .11 * (((int)colorPtr->blue) - (int)colortable[i].blue); distance += tmp * tmp; if (distance < closestDistance) { closest = i; closestDistance = distance; } } if (XAllocColor(gui.dpy, colormap, &colortable[closest]) != 0) { gui.color_approx = TRUE; *colorPtr = colortable[closest]; } vim_free(colortable); return OK; } /* * Set the current text foreground color. */ void gui_mch_set_fg_color(color) guicolor_T color; { if (color != prev_fg_color) { XSetForeground(gui.dpy, gui.text_gc, (Pixel)color); prev_fg_color = color; } } /* * Set the current text background color. */ void gui_mch_set_bg_color(color) guicolor_T color; { if (color != prev_bg_color) { XSetBackground(gui.dpy, gui.text_gc, (Pixel)color); prev_bg_color = color; } } /* * Set the current text special color. */ void gui_mch_set_sp_color(color) guicolor_T color; { prev_sp_color = color; } /* * create a mouse pointer that is blank */ static Cursor gui_x11_create_blank_mouse() { Pixmap blank_pixmap = XCreatePixmap(gui.dpy, gui.wid, 1, 1, 1); GC gc = XCreateGC(gui.dpy, blank_pixmap, (unsigned long)0, (XGCValues*)0); XDrawPoint(gui.dpy, blank_pixmap, gc, 0, 0); XFreeGC(gui.dpy, gc); return XCreatePixmapCursor(gui.dpy, blank_pixmap, blank_pixmap, (XColor*)&gui.norm_pixel, (XColor*)&gui.norm_pixel, 0, 0); } /* * Draw a curled line at the bottom of the character cell. */ static void draw_curl(row, col, cells) int row; int col; int cells; { int i; int offset; static const int val[8] = {1, 0, 0, 0, 1, 2, 2, 2 }; XSetForeground(gui.dpy, gui.text_gc, prev_sp_color); for (i = FILL_X(col); i < FILL_X(col + cells); ++i) { offset = val[i % 8]; XDrawPoint(gui.dpy, gui.wid, gui.text_gc, i, FILL_Y(row + 1) - 1 - offset); } XSetForeground(gui.dpy, gui.text_gc, prev_fg_color); } void gui_mch_draw_string(row, col, s, len, flags) int row; int col; char_u *s; int len; int flags; { int cells = len; #ifdef FEAT_MBYTE static void *buf = NULL; static int buflen = 0; char_u *p; int wlen = 0; int c; if (enc_utf8) { /* Convert UTF-8 byte sequence to 16 bit characters for the X * functions. Need a buffer for the 16 bit characters. Keep it * between calls, because allocating it each time is slow. */ if (buflen < len) { XtFree((char *)buf); buf = (void *)XtMalloc(len * (sizeof(XChar2b) < sizeof(wchar_t) ? sizeof(wchar_t) : sizeof(XChar2b))); buflen = len; } p = s; cells = 0; while (p < s + len) { c = utf_ptr2char(p); # ifdef FEAT_XFONTSET if (current_fontset != NULL) { # ifdef SMALL_WCHAR_T if (c >= 0x10000) c = 0xbf; /* show chars > 0xffff as ? */ # endif ((wchar_t *)buf)[wlen] = c; } else # endif { if (c >= 0x10000) c = 0xbf; /* show chars > 0xffff as ? */ ((XChar2b *)buf)[wlen].byte1 = (unsigned)c >> 8; ((XChar2b *)buf)[wlen].byte2 = c; } ++wlen; cells += utf_char2cells(c); p += utf_ptr2len(p); } } else if (has_mbyte) { cells = 0; for (p = s; p < s + len; ) { cells += ptr2cells(p); p += (*mb_ptr2len)(p); } } #endif #ifdef FEAT_XFONTSET if (current_fontset != NULL) { /* Setup a clip rectangle to avoid spilling over in the next or * previous line. This is apparently needed for some fonts which are * used in a fontset. */ XRectangle clip; clip.x = 0; clip.y = 0; clip.height = gui.char_height; clip.width = gui.char_width * cells + 1; XSetClipRectangles(gui.dpy, gui.text_gc, FILL_X(col), FILL_Y(row), &clip, 1, Unsorted); } #endif if (flags & DRAW_TRANSP) { #ifdef FEAT_MBYTE if (enc_utf8) XDrawString16(gui.dpy, gui.wid, gui.text_gc, TEXT_X(col), TEXT_Y(row), buf, wlen); else #endif XDrawString(gui.dpy, gui.wid, gui.text_gc, TEXT_X(col), TEXT_Y(row), (char *)s, len); } else if (p_linespace != 0 #ifdef FEAT_XFONTSET || current_fontset != NULL #endif ) { XSetForeground(gui.dpy, gui.text_gc, prev_bg_color); XFillRectangle(gui.dpy, gui.wid, gui.text_gc, FILL_X(col), FILL_Y(row), gui.char_width * cells, gui.char_height); XSetForeground(gui.dpy, gui.text_gc, prev_fg_color); #ifdef FEAT_MBYTE if (enc_utf8) XDrawString16(gui.dpy, gui.wid, gui.text_gc, TEXT_X(col), TEXT_Y(row), buf, wlen); else #endif XDrawString(gui.dpy, gui.wid, gui.text_gc, TEXT_X(col), TEXT_Y(row), (char *)s, len); } else { /* XmbDrawImageString has bug, don't use it for fontset. */ #ifdef FEAT_MBYTE if (enc_utf8) XDrawImageString16(gui.dpy, gui.wid, gui.text_gc, TEXT_X(col), TEXT_Y(row), buf, wlen); else #endif XDrawImageString(gui.dpy, gui.wid, gui.text_gc, TEXT_X(col), TEXT_Y(row), (char *)s, len); } /* Bold trick: draw the text again with a one-pixel offset. */ if (flags & DRAW_BOLD) { #ifdef FEAT_MBYTE if (enc_utf8) XDrawString16(gui.dpy, gui.wid, gui.text_gc, TEXT_X(col) + 1, TEXT_Y(row), buf, wlen); else #endif XDrawString(gui.dpy, gui.wid, gui.text_gc, TEXT_X(col) + 1, TEXT_Y(row), (char *)s, len); } /* Undercurl: draw curl at the bottom of the character cell. */ if (flags & DRAW_UNDERC) draw_curl(row, col, cells); /* Underline: draw a line at the bottom of the character cell. */ if (flags & DRAW_UNDERL) { int y = FILL_Y(row + 1) - 1; /* When p_linespace is 0, overwrite the bottom row of pixels. * Otherwise put the line just below the character. */ if (p_linespace > 1) y -= p_linespace - 1; XDrawLine(gui.dpy, gui.wid, gui.text_gc, FILL_X(col), y, FILL_X(col + cells) - 1, y); } #ifdef FEAT_XFONTSET if (current_fontset != NULL) XSetClipMask(gui.dpy, gui.text_gc, None); #endif } /* * Return OK if the key with the termcap name "name" is supported. */ int gui_mch_haskey(name) char_u *name; { int i; for (i = 0; special_keys[i].key_sym != (KeySym)0; i++) if (name[0] == special_keys[i].vim_code0 && name[1] == special_keys[i].vim_code1) return OK; return FAIL; } /* * Return the text window-id and display. Only required for X-based GUI's */ int gui_get_x11_windis(win, dis) Window *win; Display **dis; { *win = XtWindow(vimShell); *dis = gui.dpy; return OK; } void gui_mch_beep() { XBell(gui.dpy, 0); } void gui_mch_flash(msec) int msec; { /* Do a visual beep by reversing the foreground and background colors */ XFillRectangle(gui.dpy, gui.wid, gui.invert_gc, 0, 0, FILL_X((int)Columns) + gui.border_offset, FILL_Y((int)Rows) + gui.border_offset); XSync(gui.dpy, False); ui_delay((long)msec, TRUE); /* wait for a few msec */ XFillRectangle(gui.dpy, gui.wid, gui.invert_gc, 0, 0, FILL_X((int)Columns) + gui.border_offset, FILL_Y((int)Rows) + gui.border_offset); } /* * Invert a rectangle from row r, column c, for nr rows and nc columns. */ void gui_mch_invert_rectangle(r, c, nr, nc) int r; int c; int nr; int nc; { XFillRectangle(gui.dpy, gui.wid, gui.invert_gc, FILL_X(c), FILL_Y(r), (nc) * gui.char_width, (nr) * gui.char_height); } /* * Iconify the GUI window. */ void gui_mch_iconify() { XIconifyWindow(gui.dpy, XtWindow(vimShell), DefaultScreen(gui.dpy)); } #if defined(FEAT_EVAL) || defined(PROTO) /* * Bring the Vim window to the foreground. */ void gui_mch_set_foreground() { XMapRaised(gui.dpy, XtWindow(vimShell)); } #endif /* * Draw a cursor without focus. */ void gui_mch_draw_hollow_cursor(color) guicolor_T color; { int w = 1; #ifdef FEAT_MBYTE if (mb_lefthalve(gui.row, gui.col)) w = 2; #endif gui_mch_set_fg_color(color); XDrawRectangle(gui.dpy, gui.wid, gui.text_gc, FILL_X(gui.col), FILL_Y(gui.row), w * gui.char_width - 1, gui.char_height - 1); } /* * Draw part of a cursor, "w" pixels wide, and "h" pixels high, using * color "color". */ void gui_mch_draw_part_cursor(w, h, color) int w; int h; guicolor_T color; { gui_mch_set_fg_color(color); XFillRectangle(gui.dpy, gui.wid, gui.text_gc, #ifdef FEAT_RIGHTLEFT /* vertical line should be on the right of current point */ CURSOR_BAR_RIGHT ? FILL_X(gui.col + 1) - w : #endif FILL_X(gui.col), FILL_Y(gui.row) + gui.char_height - h, w, h); } /* * Catch up with any queued X events. This may put keyboard input into the * input buffer, call resize call-backs, trigger timers etc. If there is * nothing in the X event queue (& no timers pending), then we return * immediately. */ void gui_mch_update() { XtInputMask mask, desired; #ifdef ALT_X_INPUT if (suppress_alternate_input) desired = (XtIMXEvent | XtIMTimer); else #endif desired = (XtIMAll); while ((mask = XtAppPending(app_context)) && (mask & desired) && !vim_is_input_buf_full()) XtAppProcessEvent(app_context, desired); } /* * GUI input routine called by gui_wait_for_chars(). Waits for a character * from the keyboard. * wtime == -1 Wait forever. * wtime == 0 This should never happen. * wtime > 0 Wait wtime milliseconds for a character. * Returns OK if a character was found to be available within the given time, * or FAIL otherwise. */ int gui_mch_wait_for_chars(wtime) long wtime; { int focus; /* * Make this static, in case gui_x11_timer_cb is called after leaving * this function (otherwise a random value on the stack may be changed). */ static int timed_out; XtIntervalId timer = (XtIntervalId)0; XtInputMask desired; #ifdef FEAT_SNIFF static int sniff_on = 0; static XtInputId sniff_input_id = 0; #endif timed_out = FALSE; #ifdef FEAT_SNIFF if (sniff_on && !want_sniff_request) { if (sniff_input_id) XtRemoveInput(sniff_input_id); sniff_on = 0; } else if (!sniff_on && want_sniff_request) { sniff_input_id = XtAppAddInput(app_context, fd_from_sniff, (XtPointer)XtInputReadMask, gui_x11_sniff_request_cb, 0); sniff_on = 1; } #endif if (wtime > 0) timer = XtAppAddTimeOut(app_context, (long_u)wtime, gui_x11_timer_cb, &timed_out); focus = gui.in_focus; #ifdef ALT_X_INPUT if (suppress_alternate_input) desired = (XtIMXEvent | XtIMTimer); else #endif desired = (XtIMAll); while (!timed_out) { /* Stop or start blinking when focus changes */ if (gui.in_focus != focus) { if (gui.in_focus) gui_mch_start_blink(); else gui_mch_stop_blink(); focus = gui.in_focus; } #if defined(FEAT_NETBEANS_INTG) /* Process any queued netbeans messages. */ netbeans_parse_messages(); #endif /* * Don't use gui_mch_update() because then we will spin-lock until a * char arrives, instead we use XtAppProcessEvent() to hang until an * event arrives. No need to check for input_buf_full because we are * returning as soon as it contains a single char. Note that * XtAppNextEvent() may not be used because it will not return after a * timer event has arrived -- webb */ XtAppProcessEvent(app_context, desired); if (input_available()) { if (timer != (XtIntervalId)0 && !timed_out) XtRemoveTimeOut(timer); return OK; } } return FAIL; } /* * Output routines. */ /* Flush any output to the screen */ void gui_mch_flush() { XFlush(gui.dpy); } /* * Clear a rectangular region of the screen from text pos (row1, col1) to * (row2, col2) inclusive. */ void gui_mch_clear_block(row1, col1, row2, col2) int row1; int col1; int row2; int col2; { int x; x = FILL_X(col1); /* Clear one extra pixel at the far right, for when bold characters have * spilled over to the next column. */ XFillRectangle(gui.dpy, gui.wid, gui.back_gc, x, FILL_Y(row1), (col2 - col1 + 1) * gui.char_width + (col2 == Columns - 1), (row2 - row1 + 1) * gui.char_height); } void gui_mch_clear_all() { XClearArea(gui.dpy, gui.wid, 0, 0, 0, 0, False); } /* * Delete the given number of lines from the given row, scrolling up any * text further down within the scroll region. */ void gui_mch_delete_lines(row, num_lines) int row; int num_lines; { if (gui.visibility == VisibilityFullyObscured) return; /* Can't see the window */ /* copy one extra pixel at the far right, for when bold has spilled * over */ XCopyArea(gui.dpy, gui.wid, gui.wid, gui.text_gc, FILL_X(gui.scroll_region_left), FILL_Y(row + num_lines), gui.char_width * (gui.scroll_region_right - gui.scroll_region_left + 1) + (gui.scroll_region_right == Columns - 1), gui.char_height * (gui.scroll_region_bot - row - num_lines + 1), FILL_X(gui.scroll_region_left), FILL_Y(row)); gui_clear_block(gui.scroll_region_bot - num_lines + 1, gui.scroll_region_left, gui.scroll_region_bot, gui.scroll_region_right); gui_x11_check_copy_area(); } /* * Insert the given number of lines before the given row, scrolling down any * following text within the scroll region. */ void gui_mch_insert_lines(row, num_lines) int row; int num_lines; { if (gui.visibility == VisibilityFullyObscured) return; /* Can't see the window */ /* copy one extra pixel at the far right, for when bold has spilled * over */ XCopyArea(gui.dpy, gui.wid, gui.wid, gui.text_gc, FILL_X(gui.scroll_region_left), FILL_Y(row), gui.char_width * (gui.scroll_region_right - gui.scroll_region_left + 1) + (gui.scroll_region_right == Columns - 1), gui.char_height * (gui.scroll_region_bot - row - num_lines + 1), FILL_X(gui.scroll_region_left), FILL_Y(row + num_lines)); gui_clear_block(row, gui.scroll_region_left, row + num_lines - 1, gui.scroll_region_right); gui_x11_check_copy_area(); } /* * Update the region revealed by scrolling up/down. */ static void gui_x11_check_copy_area() { XEvent event; XGraphicsExposeEvent *gevent; if (gui.visibility != VisibilityPartiallyObscured) return; XFlush(gui.dpy); /* Wait to check whether the scroll worked or not */ for (;;) { if (XCheckTypedEvent(gui.dpy, NoExpose, &event)) return; /* The scroll worked. */ if (XCheckTypedEvent(gui.dpy, GraphicsExpose, &event)) { gevent = (XGraphicsExposeEvent *)&event; gui_redraw(gevent->x, gevent->y, gevent->width, gevent->height); if (gevent->count == 0) return; /* This was the last expose event */ } XSync(gui.dpy, False); } } /* * X Selection stuff, for cutting and pasting text to other windows. */ void clip_mch_lose_selection(cbd) VimClipboard *cbd; { clip_x11_lose_selection(vimShell, cbd); } int clip_mch_own_selection(cbd) VimClipboard *cbd; { return clip_x11_own_selection(vimShell, cbd); } void clip_mch_request_selection(cbd) VimClipboard *cbd; { clip_x11_request_selection(vimShell, gui.dpy, cbd); } void clip_mch_set_selection(cbd) VimClipboard *cbd; { clip_x11_set_selection(cbd); } #if defined(FEAT_MENU) || defined(PROTO) /* * Menu stuff. */ /* * Make a menu either grey or not grey. */ void gui_mch_menu_grey(menu, grey) vimmenu_T *menu; int grey; { if (menu->id != (Widget)0) { gui_mch_menu_hidden(menu, False); if (grey #ifdef FEAT_GUI_MOTIF || !menu->sensitive #endif ) XtSetSensitive(menu->id, False); else XtSetSensitive(menu->id, True); } } /* * Make menu item hidden or not hidden */ void gui_mch_menu_hidden(menu, hidden) vimmenu_T *menu; int hidden; { if (menu->id != (Widget)0) { if (hidden) XtUnmanageChild(menu->id); else XtManageChild(menu->id); } } /* * This is called after setting all the menus to grey/hidden or not. */ void gui_mch_draw_menubar() { /* Nothing to do in X */ } void gui_x11_menu_cb(w, client_data, call_data) Widget w UNUSED; XtPointer client_data; XtPointer call_data UNUSED; { gui_menu_cb((vimmenu_T *)client_data); } #endif /* FEAT_MENU */ /* * Function called when window closed. Works like ":qa". * Should put up a requester! */ static void gui_x11_wm_protocol_handler(w, client_data, event, dum) Widget w UNUSED; XtPointer client_data UNUSED; XEvent *event; Boolean *dum UNUSED; { /* * Only deal with Client messages. */ if (event->type != ClientMessage) return; /* * The WM_SAVE_YOURSELF event arrives when the window manager wants to * exit. That can be cancelled though, thus Vim shouldn't exit here. * Just sync our swap files. */ if ((Atom)((XClientMessageEvent *)event)->data.l[0] == wm_atoms[SAVE_YOURSELF_IDX]) { out_flush(); ml_sync_all(FALSE, FALSE); /* preserve all swap files */ /* Set the window's WM_COMMAND property, to let the window manager * know we are done saving ourselves. We don't want to be restarted, * thus set argv to NULL. */ XSetCommand(gui.dpy, XtWindow(vimShell), NULL, 0); return; } if ((Atom)((XClientMessageEvent *)event)->data.l[0] != wm_atoms[DELETE_WINDOW_IDX]) return; gui_shell_closed(); } #ifdef FEAT_CLIENTSERVER /* * Function called when property changed. Check for incoming commands */ static void gui_x11_send_event_handler(w, client_data, event, dum) Widget w UNUSED; XtPointer client_data UNUSED; XEvent *event; Boolean *dum UNUSED; { XPropertyEvent *e = (XPropertyEvent *) event; if (e->type == PropertyNotify && e->window == commWindow && e->atom == commProperty && e->state == PropertyNewValue) { serverEventProc(gui.dpy, event); } } #endif /* * Cursor blink functions. * * This is a simple state machine: * BLINK_NONE not blinking at all * BLINK_OFF blinking, cursor is not shown * BLINK_ON blinking, cursor is shown */ #define BLINK_NONE 0 #define BLINK_OFF 1 #define BLINK_ON 2 static int blink_state = BLINK_NONE; static long_u blink_waittime = 700; static long_u blink_ontime = 400; static long_u blink_offtime = 250; static XtIntervalId blink_timer = (XtIntervalId)0; void gui_mch_set_blinking(waittime, on, off) long waittime, on, off; { blink_waittime = waittime; blink_ontime = on; blink_offtime = off; } /* * Stop the cursor blinking. Show the cursor if it wasn't shown. */ void gui_mch_stop_blink() { if (blink_timer != (XtIntervalId)0) { XtRemoveTimeOut(blink_timer); blink_timer = (XtIntervalId)0; } if (blink_state == BLINK_OFF) gui_update_cursor(TRUE, FALSE); blink_state = BLINK_NONE; } /* * Start the cursor blinking. If it was already blinking, this restarts the * waiting time and shows the cursor. */ void gui_mch_start_blink() { if (blink_timer != (XtIntervalId)0) XtRemoveTimeOut(blink_timer); /* Only switch blinking on if none of the times is zero */ if (blink_waittime && blink_ontime && blink_offtime && gui.in_focus) { blink_timer = XtAppAddTimeOut(app_context, blink_waittime, gui_x11_blink_cb, NULL); blink_state = BLINK_ON; gui_update_cursor(TRUE, FALSE); } } static void gui_x11_blink_cb(timed_out, interval_id) XtPointer timed_out UNUSED; XtIntervalId *interval_id UNUSED; { if (blink_state == BLINK_ON) { gui_undraw_cursor(); blink_state = BLINK_OFF; blink_timer = XtAppAddTimeOut(app_context, blink_offtime, gui_x11_blink_cb, NULL); } else { gui_update_cursor(TRUE, FALSE); blink_state = BLINK_ON; blink_timer = XtAppAddTimeOut(app_context, blink_ontime, gui_x11_blink_cb, NULL); } } /* * Return the RGB value of a pixel as a long. */ long_u gui_mch_get_rgb(pixel) guicolor_T pixel; { XColor xc; Colormap colormap; colormap = DefaultColormap(gui.dpy, XDefaultScreen(gui.dpy)); xc.pixel = pixel; XQueryColor(gui.dpy, colormap, &xc); return ((xc.red & 0xff00) << 8) + (xc.green & 0xff00) + ((unsigned)xc.blue >> 8); } /* * Add the callback functions. */ void gui_x11_callbacks(textArea, vimForm) Widget textArea; Widget vimForm; { XtAddEventHandler(textArea, VisibilityChangeMask, FALSE, gui_x11_visibility_cb, (XtPointer)0); XtAddEventHandler(textArea, ExposureMask, FALSE, gui_x11_expose_cb, (XtPointer)0); XtAddEventHandler(vimShell, StructureNotifyMask, FALSE, gui_x11_resize_window_cb, (XtPointer)0); XtAddEventHandler(vimShell, FocusChangeMask, FALSE, gui_x11_focus_change_cb, (XtPointer)0); /* * Only install these enter/leave callbacks when 'p' in 'guioptions'. * Only needed for some window managers. */ if (vim_strchr(p_go, GO_POINTER) != NULL) { XtAddEventHandler(vimShell, LeaveWindowMask, FALSE, gui_x11_leave_cb, (XtPointer)0); XtAddEventHandler(textArea, LeaveWindowMask, FALSE, gui_x11_leave_cb, (XtPointer)0); XtAddEventHandler(textArea, EnterWindowMask, FALSE, gui_x11_enter_cb, (XtPointer)0); XtAddEventHandler(vimShell, EnterWindowMask, FALSE, gui_x11_enter_cb, (XtPointer)0); } XtAddEventHandler(vimForm, KeyPressMask, FALSE, gui_x11_key_hit_cb, (XtPointer)0); XtAddEventHandler(textArea, KeyPressMask, FALSE, gui_x11_key_hit_cb, (XtPointer)0); /* get pointer moved events from scrollbar, needed for 'mousefocus' */ XtAddEventHandler(vimForm, PointerMotionMask, FALSE, gui_x11_mouse_cb, (XtPointer)1); XtAddEventHandler(textArea, ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | PointerMotionMask, FALSE, gui_x11_mouse_cb, (XtPointer)0); } /* * Get current mouse coordinates in text window. */ void gui_mch_getmouse(int *x, int *y) { int rootx, rooty, winx, winy; Window root, child; unsigned int mask; if (gui.wid && XQueryPointer(gui.dpy, gui.wid, &root, &child, &rootx, &rooty, &winx, &winy, &mask)) { *x = winx; *y = winy; } else { *x = -1; *y = -1; } } void gui_mch_setmouse(x, y) int x; int y; { if (gui.wid) XWarpPointer(gui.dpy, (Window)0, gui.wid, 0, 0, 0, 0, x, y); } #if (defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU)) || defined(PROTO) XButtonPressedEvent * gui_x11_get_last_mouse_event() { return &last_mouse_event; } #endif #if defined(FEAT_SIGN_ICONS) || defined(PROTO) /* Signs are currently always 2 chars wide. Hopefully the font is big enough * to provide room for the bitmap! */ # define SIGN_WIDTH (gui.char_width * 2) void gui_mch_drawsign(row, col, typenr) int row; int col; int typenr; { XImage *sign; if (gui.in_use && (sign = (XImage *)sign_get_image(typenr)) != NULL) { XClearArea(gui.dpy, gui.wid, TEXT_X(col), TEXT_Y(row) - sign->height, SIGN_WIDTH, gui.char_height, FALSE); XPutImage(gui.dpy, gui.wid, gui.text_gc, sign, 0, 0, TEXT_X(col) + (SIGN_WIDTH - sign->width) / 2, TEXT_Y(row) - sign->height, sign->width, sign->height); } } void * gui_mch_register_sign(signfile) char_u *signfile; { XpmAttributes attrs; XImage *sign = NULL; int status; /* * Setup the color substitution table. */ if (signfile[0] != NUL && signfile[0] != '-') { XpmColorSymbol color[5] = { {"none", NULL, 0}, {"iconColor1", NULL, 0}, {"bottomShadowColor", NULL, 0}, {"topShadowColor", NULL, 0}, {"selectColor", NULL, 0} }; attrs.valuemask = XpmColorSymbols; attrs.numsymbols = 2; attrs.colorsymbols = color; attrs.colorsymbols[0].pixel = gui.back_pixel; attrs.colorsymbols[1].pixel = gui.norm_pixel; status = XpmReadFileToImage(gui.dpy, (char *)signfile, &sign, NULL, &attrs); if (status == 0) { /* Sign width is fixed at two columns now. if (sign->width > gui.sign_width) gui.sign_width = sign->width + 8; */ } else EMSG(_(e_signdata)); } return (void *)sign; } void gui_mch_destroy_sign(sign) void *sign; { XDestroyImage((XImage*)sign); } #endif #ifdef FEAT_MOUSESHAPE /* The last set mouse pointer shape is remembered, to be used when it goes * from hidden to not hidden. */ static int last_shape = 0; #endif /* * Use the blank mouse pointer or not. */ void gui_mch_mousehide(hide) int hide; /* TRUE = use blank ptr, FALSE = use parent ptr */ { if (gui.pointer_hidden != hide) { gui.pointer_hidden = hide; if (hide) XDefineCursor(gui.dpy, gui.wid, gui.blank_pointer); else #ifdef FEAT_MOUSESHAPE mch_set_mouse_shape(last_shape); #else XUndefineCursor(gui.dpy, gui.wid); #endif } } #if defined(FEAT_MOUSESHAPE) || defined(PROTO) /* Table for shape IDs. Keep in sync with the mshape_names[] table in * misc2.c! */ static int mshape_ids[] = { XC_left_ptr, /* arrow */ 0, /* blank */ XC_xterm, /* beam */ XC_sb_v_double_arrow, /* updown */ XC_sizing, /* udsizing */ XC_sb_h_double_arrow, /* leftright */ XC_sizing, /* lrsizing */ XC_watch, /* busy */ XC_X_cursor, /* no */ XC_crosshair, /* crosshair */ XC_hand1, /* hand1 */ XC_hand2, /* hand2 */ XC_pencil, /* pencil */ XC_question_arrow, /* question */ XC_right_ptr, /* right-arrow */ XC_center_ptr, /* up-arrow */ XC_left_ptr /* last one */ }; void mch_set_mouse_shape(shape) int shape; { int id; if (!gui.in_use) return; if (shape == MSHAPE_HIDE || gui.pointer_hidden) XDefineCursor(gui.dpy, gui.wid, gui.blank_pointer); else { if (shape >= MSHAPE_NUMBERED) { id = shape - MSHAPE_NUMBERED; if (id >= XC_num_glyphs) id = XC_left_ptr; else id &= ~1; /* they are always even (why?) */ } else id = mshape_ids[shape]; XDefineCursor(gui.dpy, gui.wid, XCreateFontCursor(gui.dpy, id)); } if (shape != MSHAPE_HIDE) last_shape = shape; } #endif #if (defined(FEAT_TOOLBAR) && defined(FEAT_BEVAL)) || defined(PROTO) /* * Set the balloon-eval used for the tooltip of a toolbar menu item. * The check for a non-toolbar item was added, because there is a crash when * passing a normal menu item here. Can't explain that, but better avoid it. */ void gui_mch_menu_set_tip(menu) vimmenu_T *menu; { if (menu->id != NULL && menu->parent != NULL && menu_is_toolbar(menu->parent->name)) { /* Always destroy and create the balloon, in case the string was * changed. */ if (menu->tip != NULL) { gui_mch_destroy_beval_area(menu->tip); menu->tip = NULL; } if (menu->strings[MENU_INDEX_TIP] != NULL) menu->tip = gui_mch_create_beval_area( menu->id, menu->strings[MENU_INDEX_TIP], NULL, NULL); } } #endif
zyz2011-vim
src/gui_x11.c
C
gpl2
88,382
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Python extensions by Paul Moore. * Changes for Unix by David Leonard. * * This consists of four parts: * 1. Python interpreter main program * 2. Python output stream: writes output via [e]msg(). * 3. Implementation of the Vim module for Python * 4. Utility functions for handling the interface between Vim and Python. */ /* * Roland Puntaier 2009/sept/16: * Adaptations to support both python3.x and python2.x */ /* uncomment this if used with the debug version of python */ /* #define Py_DEBUG */ #include "vim.h" #include <limits.h> /* Python.h defines _POSIX_THREADS itself (if needed) */ #ifdef _POSIX_THREADS # undef _POSIX_THREADS #endif #if defined(_WIN32) && defined(HAVE_FCNTL_H) # undef HAVE_FCNTL_H #endif #ifdef _DEBUG # undef _DEBUG #endif #define PY_SSIZE_T_CLEAN #ifdef F_BLANK # undef F_BLANK #endif #ifdef HAVE_STDARG_H # undef HAVE_STDARG_H /* Python's config.h defines it as well. */ #endif #ifdef _POSIX_C_SOURCE /* defined in feature.h */ # undef _POSIX_C_SOURCE #endif #ifdef _XOPEN_SOURCE # undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */ #endif #include <Python.h> #if defined(MACOS) && !defined(MACOS_X_UNIX) # include "macglue.h" # include <CodeFragments.h> #endif #undef main /* Defined in python.h - aargh */ #undef HAVE_FCNTL_H /* Clash with os_win32.h */ static void init_structs(void); /* The "surrogateescape" error handler is new in Python 3.1 */ #if PY_VERSION_HEX >= 0x030100f0 # define CODEC_ERROR_HANDLER "surrogateescape" #else # define CODEC_ERROR_HANDLER NULL #endif #define PyInt Py_ssize_t #define PyString_Check(obj) PyUnicode_Check(obj) #define PyString_AsBytes(obj) PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, CODEC_ERROR_HANDLER); #define PyString_FreeBytes(obj) Py_XDECREF(bytes) #define PyString_AsString(obj) PyBytes_AsString(obj) #define PyString_Size(obj) PyBytes_GET_SIZE(bytes) #define PyString_FromString(repr) PyUnicode_FromString(repr) #if defined(DYNAMIC_PYTHON3) || defined(PROTO) # ifndef WIN3264 # include <dlfcn.h> # define FARPROC void* # define HINSTANCE void* # if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL) # define load_dll(n) dlopen((n), RTLD_LAZY) # else # define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL) # endif # define close_dll dlclose # define symbol_from_dll dlsym # else # define load_dll vimLoadLib # define close_dll FreeLibrary # define symbol_from_dll GetProcAddress # endif /* * Wrapper defines */ # undef PyArg_Parse # define PyArg_Parse py3_PyArg_Parse # undef PyArg_ParseTuple # define PyArg_ParseTuple py3_PyArg_ParseTuple # define PyMem_Free py3_PyMem_Free # define PyDict_SetItemString py3_PyDict_SetItemString # define PyErr_BadArgument py3_PyErr_BadArgument # define PyErr_Clear py3_PyErr_Clear # define PyErr_NoMemory py3_PyErr_NoMemory # define PyErr_Occurred py3_PyErr_Occurred # define PyErr_SetNone py3_PyErr_SetNone # define PyErr_SetString py3_PyErr_SetString # define PyEval_InitThreads py3_PyEval_InitThreads # define PyEval_RestoreThread py3_PyEval_RestoreThread # define PyEval_SaveThread py3_PyEval_SaveThread # define PyGILState_Ensure py3_PyGILState_Ensure # define PyGILState_Release py3_PyGILState_Release # define PyLong_AsLong py3_PyLong_AsLong # define PyLong_FromLong py3_PyLong_FromLong # define PyList_GetItem py3_PyList_GetItem # define PyList_Append py3_PyList_Append # define PyList_New py3_PyList_New # define PyList_SetItem py3_PyList_SetItem # define PyList_Size py3_PyList_Size # define PySlice_GetIndicesEx py3_PySlice_GetIndicesEx # define PyImport_ImportModule py3_PyImport_ImportModule # define PyObject_Init py3__PyObject_Init # define PyDict_New py3_PyDict_New # define PyDict_GetItemString py3_PyDict_GetItemString # define PyModule_GetDict py3_PyModule_GetDict #undef PyRun_SimpleString # define PyRun_SimpleString py3_PyRun_SimpleString # define PySys_SetObject py3_PySys_SetObject # define PySys_SetArgv py3_PySys_SetArgv # define PyType_Type (*py3_PyType_Type) # define PyType_Ready py3_PyType_Ready #undef Py_BuildValue # define Py_BuildValue py3_Py_BuildValue # define Py_SetPythonHome py3_Py_SetPythonHome # define Py_Initialize py3_Py_Initialize # define Py_Finalize py3_Py_Finalize # define Py_IsInitialized py3_Py_IsInitialized # define _Py_NoneStruct (*py3__Py_NoneStruct) # define PyModule_AddObject py3_PyModule_AddObject # define PyImport_AppendInittab py3_PyImport_AppendInittab # define _PyUnicode_AsString py3__PyUnicode_AsString # undef PyUnicode_AsEncodedString # define PyUnicode_AsEncodedString py3_PyUnicode_AsEncodedString # undef PyBytes_AsString # define PyBytes_AsString py3_PyBytes_AsString # define PyObject_GenericGetAttr py3_PyObject_GenericGetAttr # define PySlice_Type (*py3_PySlice_Type) # define PyErr_NewException py3_PyErr_NewException # ifdef Py_DEBUG # define _Py_NegativeRefcount py3__Py_NegativeRefcount # define _Py_RefTotal (*py3__Py_RefTotal) # define _Py_Dealloc py3__Py_Dealloc # define _PyObject_DebugMalloc py3__PyObject_DebugMalloc # define _PyObject_DebugFree py3__PyObject_DebugFree # else # define PyObject_Malloc py3_PyObject_Malloc # define PyObject_Free py3_PyObject_Free # endif # define PyType_GenericAlloc py3_PyType_GenericAlloc # define PyType_GenericNew py3_PyType_GenericNew # define PyModule_Create2 py3_PyModule_Create2 # undef PyUnicode_FromString # define PyUnicode_FromString py3_PyUnicode_FromString # undef PyUnicode_Decode # define PyUnicode_Decode py3_PyUnicode_Decode # ifdef Py_DEBUG # undef PyObject_NEW # define PyObject_NEW(type, typeobj) \ ( (type *) PyObject_Init( \ (PyObject *) _PyObject_DebugMalloc( _PyObject_SIZE(typeobj) ), (typeobj)) ) # endif /* * Pointers for dynamic link */ static int (*py3_PySys_SetArgv)(int, wchar_t **); static void (*py3_Py_SetPythonHome)(wchar_t *home); static void (*py3_Py_Initialize)(void); static PyObject* (*py3_PyList_New)(Py_ssize_t size); static PyGILState_STATE (*py3_PyGILState_Ensure)(void); static void (*py3_PyGILState_Release)(PyGILState_STATE); static int (*py3_PySys_SetObject)(char *, PyObject *); static PyObject* (*py3_PyList_Append)(PyObject *, PyObject *); static Py_ssize_t (*py3_PyList_Size)(PyObject *); static int (*py3_PySlice_GetIndicesEx)(PyObject *r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength); static PyObject* (*py3_PyErr_NoMemory)(void); static void (*py3_Py_Finalize)(void); static void (*py3_PyErr_SetString)(PyObject *, const char *); static int (*py3_PyRun_SimpleString)(char *); static PyObject* (*py3_PyList_GetItem)(PyObject *, Py_ssize_t); static PyObject* (*py3_PyImport_ImportModule)(const char *); static int (*py3_PyErr_BadArgument)(void); static PyTypeObject* py3_PyType_Type; static PyObject* (*py3_PyErr_Occurred)(void); static PyObject* (*py3_PyModule_GetDict)(PyObject *); static int (*py3_PyList_SetItem)(PyObject *, Py_ssize_t, PyObject *); static PyObject* (*py3_PyDict_GetItemString)(PyObject *, const char *); static PyObject* (*py3_PyLong_FromLong)(long); static PyObject* (*py3_PyDict_New)(void); static PyObject* (*py3_Py_BuildValue)(char *, ...); static int (*py3_PyType_Ready)(PyTypeObject *type); static int (*py3_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item); static PyObject* (*py3_PyUnicode_FromString)(const char *u); static PyObject* (*py3_PyUnicode_Decode)(const char *u, Py_ssize_t size, const char *encoding, const char *errors); static long (*py3_PyLong_AsLong)(PyObject *); static void (*py3_PyErr_SetNone)(PyObject *); static void (*py3_PyEval_InitThreads)(void); static void(*py3_PyEval_RestoreThread)(PyThreadState *); static PyThreadState*(*py3_PyEval_SaveThread)(void); static int (*py3_PyArg_Parse)(PyObject *, char *, ...); static int (*py3_PyArg_ParseTuple)(PyObject *, char *, ...); static int (*py3_PyMem_Free)(void *); static int (*py3_Py_IsInitialized)(void); static void (*py3_PyErr_Clear)(void); static PyObject*(*py3__PyObject_Init)(PyObject *, PyTypeObject *); static PyObject* py3__Py_NoneStruct; static int (*py3_PyModule_AddObject)(PyObject *m, const char *name, PyObject *o); static int (*py3_PyImport_AppendInittab)(const char *name, PyObject* (*initfunc)(void)); static char* (*py3__PyUnicode_AsString)(PyObject *unicode); static PyObject* (*py3_PyUnicode_AsEncodedString)(PyObject *unicode, const char* encoding, const char* errors); static char* (*py3_PyBytes_AsString)(PyObject *bytes); static PyObject* (*py3_PyObject_GenericGetAttr)(PyObject *obj, PyObject *name); static PyObject* (*py3_PyModule_Create2)(struct PyModuleDef* module, int module_api_version); static PyObject* (*py3_PyType_GenericAlloc)(PyTypeObject *type, Py_ssize_t nitems); static PyObject* (*py3_PyType_GenericNew)(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyTypeObject* py3_PySlice_Type; static PyObject* (*py3_PyErr_NewException)(char *name, PyObject *base, PyObject *dict); # ifdef Py_DEBUG static void (*py3__Py_NegativeRefcount)(const char *fname, int lineno, PyObject *op); static Py_ssize_t* py3__Py_RefTotal; static void (*py3__Py_Dealloc)(PyObject *obj); static void (*py3__PyObject_DebugFree)(void*); static void* (*py3__PyObject_DebugMalloc)(size_t); # else static void (*py3_PyObject_Free)(void*); static void* (*py3_PyObject_Malloc)(size_t); # endif static HINSTANCE hinstPy3 = 0; /* Instance of python.dll */ /* Imported exception objects */ static PyObject *p3imp_PyExc_AttributeError; static PyObject *p3imp_PyExc_IndexError; static PyObject *p3imp_PyExc_KeyboardInterrupt; static PyObject *p3imp_PyExc_TypeError; static PyObject *p3imp_PyExc_ValueError; # define PyExc_AttributeError p3imp_PyExc_AttributeError # define PyExc_IndexError p3imp_PyExc_IndexError # define PyExc_KeyboardInterrupt p3imp_PyExc_KeyboardInterrupt # define PyExc_TypeError p3imp_PyExc_TypeError # define PyExc_ValueError p3imp_PyExc_ValueError /* * Table of name to function pointer of python. */ # define PYTHON_PROC FARPROC static struct { char *name; PYTHON_PROC *ptr; } py3_funcname_table[] = { {"PySys_SetArgv", (PYTHON_PROC*)&py3_PySys_SetArgv}, {"Py_SetPythonHome", (PYTHON_PROC*)&py3_Py_SetPythonHome}, {"Py_Initialize", (PYTHON_PROC*)&py3_Py_Initialize}, {"PyArg_ParseTuple", (PYTHON_PROC*)&py3_PyArg_ParseTuple}, {"PyMem_Free", (PYTHON_PROC*)&py3_PyMem_Free}, {"PyList_New", (PYTHON_PROC*)&py3_PyList_New}, {"PyGILState_Ensure", (PYTHON_PROC*)&py3_PyGILState_Ensure}, {"PyGILState_Release", (PYTHON_PROC*)&py3_PyGILState_Release}, {"PySys_SetObject", (PYTHON_PROC*)&py3_PySys_SetObject}, {"PyList_Append", (PYTHON_PROC*)&py3_PyList_Append}, {"PyList_Size", (PYTHON_PROC*)&py3_PyList_Size}, {"PySlice_GetIndicesEx", (PYTHON_PROC*)&py3_PySlice_GetIndicesEx}, {"PyErr_NoMemory", (PYTHON_PROC*)&py3_PyErr_NoMemory}, {"Py_Finalize", (PYTHON_PROC*)&py3_Py_Finalize}, {"PyErr_SetString", (PYTHON_PROC*)&py3_PyErr_SetString}, {"PyRun_SimpleString", (PYTHON_PROC*)&py3_PyRun_SimpleString}, {"PyList_GetItem", (PYTHON_PROC*)&py3_PyList_GetItem}, {"PyImport_ImportModule", (PYTHON_PROC*)&py3_PyImport_ImportModule}, {"PyErr_BadArgument", (PYTHON_PROC*)&py3_PyErr_BadArgument}, {"PyType_Type", (PYTHON_PROC*)&py3_PyType_Type}, {"PyErr_Occurred", (PYTHON_PROC*)&py3_PyErr_Occurred}, {"PyModule_GetDict", (PYTHON_PROC*)&py3_PyModule_GetDict}, {"PyList_SetItem", (PYTHON_PROC*)&py3_PyList_SetItem}, {"PyDict_GetItemString", (PYTHON_PROC*)&py3_PyDict_GetItemString}, {"PyLong_FromLong", (PYTHON_PROC*)&py3_PyLong_FromLong}, {"PyDict_New", (PYTHON_PROC*)&py3_PyDict_New}, {"Py_BuildValue", (PYTHON_PROC*)&py3_Py_BuildValue}, {"PyType_Ready", (PYTHON_PROC*)&py3_PyType_Ready}, {"PyDict_SetItemString", (PYTHON_PROC*)&py3_PyDict_SetItemString}, {"PyLong_AsLong", (PYTHON_PROC*)&py3_PyLong_AsLong}, {"PyErr_SetNone", (PYTHON_PROC*)&py3_PyErr_SetNone}, {"PyEval_InitThreads", (PYTHON_PROC*)&py3_PyEval_InitThreads}, {"PyEval_RestoreThread", (PYTHON_PROC*)&py3_PyEval_RestoreThread}, {"PyEval_SaveThread", (PYTHON_PROC*)&py3_PyEval_SaveThread}, {"PyArg_Parse", (PYTHON_PROC*)&py3_PyArg_Parse}, {"Py_IsInitialized", (PYTHON_PROC*)&py3_Py_IsInitialized}, {"_Py_NoneStruct", (PYTHON_PROC*)&py3__Py_NoneStruct}, {"PyErr_Clear", (PYTHON_PROC*)&py3_PyErr_Clear}, {"PyObject_Init", (PYTHON_PROC*)&py3__PyObject_Init}, {"PyModule_AddObject", (PYTHON_PROC*)&py3_PyModule_AddObject}, {"PyImport_AppendInittab", (PYTHON_PROC*)&py3_PyImport_AppendInittab}, {"_PyUnicode_AsString", (PYTHON_PROC*)&py3__PyUnicode_AsString}, {"PyBytes_AsString", (PYTHON_PROC*)&py3_PyBytes_AsString}, {"PyObject_GenericGetAttr", (PYTHON_PROC*)&py3_PyObject_GenericGetAttr}, {"PyModule_Create2", (PYTHON_PROC*)&py3_PyModule_Create2}, {"PyType_GenericAlloc", (PYTHON_PROC*)&py3_PyType_GenericAlloc}, {"PyType_GenericNew", (PYTHON_PROC*)&py3_PyType_GenericNew}, {"PySlice_Type", (PYTHON_PROC*)&py3_PySlice_Type}, {"PyErr_NewException", (PYTHON_PROC*)&py3_PyErr_NewException}, # ifdef Py_DEBUG {"_Py_NegativeRefcount", (PYTHON_PROC*)&py3__Py_NegativeRefcount}, {"_Py_RefTotal", (PYTHON_PROC*)&py3__Py_RefTotal}, {"_Py_Dealloc", (PYTHON_PROC*)&py3__Py_Dealloc}, {"_PyObject_DebugFree", (PYTHON_PROC*)&py3__PyObject_DebugFree}, {"_PyObject_DebugMalloc", (PYTHON_PROC*)&py3__PyObject_DebugMalloc}, # else {"PyObject_Malloc", (PYTHON_PROC*)&py3_PyObject_Malloc}, {"PyObject_Free", (PYTHON_PROC*)&py3_PyObject_Free}, # endif {"", NULL}, }; /* * Free python.dll */ static void end_dynamic_python3(void) { if (hinstPy3 != 0) { close_dll(hinstPy3); hinstPy3 = 0; } } /* * Load library and get all pointers. * Parameter 'libname' provides name of DLL. * Return OK or FAIL. */ static int py3_runtime_link_init(char *libname, int verbose) { int i; void *ucs_from_string, *ucs_decode, *ucs_as_encoded_string; # if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON) /* Can't have Python and Python3 loaded at the same time. * It cause a crash, because RTLD_GLOBAL is needed for * standard C extension libraries of one or both python versions. */ if (python_loaded()) { if (verbose) EMSG(_("E837: This Vim cannot execute :py3 after using :python")); return FAIL; } # endif if (hinstPy3 != 0) return OK; hinstPy3 = load_dll(libname); if (!hinstPy3) { if (verbose) EMSG2(_(e_loadlib), libname); return FAIL; } for (i = 0; py3_funcname_table[i].ptr; ++i) { if ((*py3_funcname_table[i].ptr = symbol_from_dll(hinstPy3, py3_funcname_table[i].name)) == NULL) { close_dll(hinstPy3); hinstPy3 = 0; if (verbose) EMSG2(_(e_loadfunc), py3_funcname_table[i].name); return FAIL; } } /* Load unicode functions separately as only the ucs2 or the ucs4 functions * will be present in the library. */ ucs_from_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS2_FromString"); ucs_decode = symbol_from_dll(hinstPy3, "PyUnicodeUCS2_Decode"); ucs_as_encoded_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS2_AsEncodedString"); if (!ucs_from_string || !ucs_decode || !ucs_as_encoded_string) { ucs_from_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS4_FromString"); ucs_decode = symbol_from_dll(hinstPy3, "PyUnicodeUCS4_Decode"); ucs_as_encoded_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS4_AsEncodedString"); } if (ucs_from_string && ucs_decode && ucs_as_encoded_string) { py3_PyUnicode_FromString = ucs_from_string; py3_PyUnicode_Decode = ucs_decode; py3_PyUnicode_AsEncodedString = ucs_as_encoded_string; } else { close_dll(hinstPy3); hinstPy3 = 0; if (verbose) EMSG2(_(e_loadfunc), "PyUnicode_UCSX_*"); return FAIL; } return OK; } /* * If python is enabled (there is installed python on Windows system) return * TRUE, else FALSE. */ int python3_enabled(int verbose) { return py3_runtime_link_init(DYNAMIC_PYTHON3_DLL, verbose) == OK; } /* Load the standard Python exceptions - don't import the symbols from the * DLL, as this can cause errors (importing data symbols is not reliable). */ static void get_py3_exceptions __ARGS((void)); static void get_py3_exceptions() { PyObject *exmod = PyImport_ImportModule("builtins"); PyObject *exdict = PyModule_GetDict(exmod); p3imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError"); p3imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError"); p3imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt"); p3imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError"); p3imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError"); Py_XINCREF(p3imp_PyExc_AttributeError); Py_XINCREF(p3imp_PyExc_IndexError); Py_XINCREF(p3imp_PyExc_KeyboardInterrupt); Py_XINCREF(p3imp_PyExc_TypeError); Py_XINCREF(p3imp_PyExc_ValueError); Py_XDECREF(exmod); } #endif /* DYNAMIC_PYTHON3 */ static PyObject *BufferNew (buf_T *); static PyObject *WindowNew(win_T *); static PyObject *LineToString(const char *); static PyObject *BufferDir(PyObject *, PyObject *); static PyTypeObject RangeType; /* * Include the code shared with if_python.c */ #include "if_py_both.h" static void call_PyObject_Free(void *p) { #ifdef Py_DEBUG _PyObject_DebugFree(p); #else PyObject_Free(p); #endif } static PyObject * call_PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) { return PyType_GenericNew(type,args,kwds); } static PyObject * call_PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) { return PyType_GenericAlloc(type,nitems); } /****************************************************** * Internal function prototypes. */ static Py_ssize_t RangeStart; static Py_ssize_t RangeEnd; static int PythonIO_Init(void); static void PythonIO_Fini(void); PyMODINIT_FUNC Py3Init_vim(void); /****************************************************** * 1. Python interpreter main program. */ static int py3initialised = 0; static PyGILState_STATE pygilstate = PyGILState_UNLOCKED; void python3_end() { static int recurse = 0; /* If a crash occurs while doing this, don't try again. */ if (recurse != 0) return; ++recurse; #ifdef DYNAMIC_PYTHON3 if (hinstPy3) #endif if (Py_IsInitialized()) { // acquire lock before finalizing pygilstate = PyGILState_Ensure(); PythonIO_Fini(); Py_Finalize(); } #ifdef DYNAMIC_PYTHON3 end_dynamic_python3(); #endif --recurse; } #if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON)) || defined(PROTO) int python3_loaded() { return (hinstPy3 != 0); } #endif static int Python3_Init(void) { if (!py3initialised) { #ifdef DYNAMIC_PYTHON3 if (!python3_enabled(TRUE)) { EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded.")); goto fail; } #endif init_structs(); #ifdef PYTHON3_HOME Py_SetPythonHome(PYTHON3_HOME); #endif #if !defined(MACOS) || defined(MACOS_X_UNIX) Py_Initialize(); #else PyMac_Initialize(); #endif /* initialise threads, must be after Py_Initialize() */ PyEval_InitThreads(); #ifdef DYNAMIC_PYTHON3 get_py3_exceptions(); #endif if (PythonIO_Init()) goto fail; PyImport_AppendInittab("vim", Py3Init_vim); /* Remove the element from sys.path that was added because of our * argv[0] value in Py3Init_vim(). Previously we used an empty * string, but dependinding on the OS we then get an empty entry or * the current directory in sys.path. * Only after vim has been imported, the element does exist in * sys.path. */ PyRun_SimpleString("import vim; import sys; sys.path = list(filter(lambda x: not x.endswith('must>not&exist'), sys.path))"); // lock is created and acquired in PyEval_InitThreads() and thread // state is created in Py_Initialize() // there _PyGILState_NoteThreadState() also sets gilcounter to 1 // (python must have threads enabled!) // so the following does both: unlock GIL and save thread state in TLS // without deleting thread state PyGILState_Release(pygilstate); py3initialised = 1; } return 0; fail: /* We call PythonIO_Flush() here to print any Python errors. * This is OK, as it is possible to call this function even * if PythonIO_Init() has not completed successfully (it will * not do anything in this case). */ PythonIO_Flush(); return -1; } /* * External interface */ static void DoPy3Command(exarg_T *eap, const char *cmd) { #if defined(MACOS) && !defined(MACOS_X_UNIX) GrafPtr oldPort; #endif #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) char *saved_locale; #endif PyObject *cmdstr; PyObject *cmdbytes; #if defined(MACOS) && !defined(MACOS_X_UNIX) GetPort(&oldPort); /* Check if the Python library is available */ if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress) goto theend; #endif if (Python3_Init()) goto theend; RangeStart = eap->line1; RangeEnd = eap->line2; Python_Release_Vim(); /* leave vim */ #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) /* Python only works properly when the LC_NUMERIC locale is "C". */ saved_locale = setlocale(LC_NUMERIC, NULL); if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0) saved_locale = NULL; else { /* Need to make a copy, value may change when setting new locale. */ saved_locale = (char *)vim_strsave((char_u *)saved_locale); (void)setlocale(LC_NUMERIC, "C"); } #endif pygilstate = PyGILState_Ensure(); /* PyRun_SimpleString expects a UTF-8 string. Wrong encoding may cause * SyntaxError (unicode error). */ cmdstr = PyUnicode_Decode(cmd, strlen(cmd), (char *)ENC_OPT, CODEC_ERROR_HANDLER); cmdbytes = PyUnicode_AsEncodedString(cmdstr, "utf-8", CODEC_ERROR_HANDLER); Py_XDECREF(cmdstr); PyRun_SimpleString(PyBytes_AsString(cmdbytes)); Py_XDECREF(cmdbytes); PyGILState_Release(pygilstate); #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) if (saved_locale != NULL) { (void)setlocale(LC_NUMERIC, saved_locale); vim_free(saved_locale); } #endif Python_Lock_Vim(); /* enter vim */ PythonIO_Flush(); #if defined(MACOS) && !defined(MACOS_X_UNIX) SetPort(oldPort); #endif theend: return; /* keeps lint happy */ } /* * ":py3" */ void ex_py3(exarg_T *eap) { char_u *script; script = script_get(eap, eap->arg); if (!eap->skip) { if (script == NULL) DoPy3Command(eap, (char *)eap->arg); else DoPy3Command(eap, (char *)script); } vim_free(script); } #define BUFFER_SIZE 2048 /* * ":py3file" */ void ex_py3file(exarg_T *eap) { static char buffer[BUFFER_SIZE]; const char *file; char *p; int i; /* Have to do it like this. PyRun_SimpleFile requires you to pass a * stdio file pointer, but Vim and the Python DLL are compiled with * different options under Windows, meaning that stdio pointers aren't * compatible between the two. Yuk. * * construct: exec(compile(open('a_filename', 'rb').read(), 'a_filename', 'exec')) * * Using bytes so that Python can detect the source encoding as it normally * does. The doc does not say "compile" accept bytes, though. * * We need to escape any backslashes or single quotes in the file name, so that * Python won't mangle the file name. */ strcpy(buffer, "exec(compile(open('"); p = buffer + 19; /* size of "exec(compile(open('" */ for (i=0; i<2; ++i) { file = (char *)eap->arg; while (*file && p < buffer + (BUFFER_SIZE - 3)) { if (*file == '\\' || *file == '\'') *p++ = '\\'; *p++ = *file++; } /* If we didn't finish the file name, we hit a buffer overflow */ if (*file != '\0') return; if (i==0) { strcpy(p,"','rb').read(),'"); p += 16; } else { strcpy(p,"','exec'))"); p += 10; } } /* Execute the file */ DoPy3Command(eap, buffer); } /****************************************************** * 2. Python output stream: writes output via [e]msg(). */ /* Implementation functions */ static PyObject * OutputGetattro(PyObject *self, PyObject *nameobj) { char *name = ""; if (PyUnicode_Check(nameobj)) name = _PyUnicode_AsString(nameobj); if (strcmp(name, "softspace") == 0) return PyLong_FromLong(((OutputObject *)(self))->softspace); return PyObject_GenericGetAttr(self, nameobj); } static int OutputSetattro(PyObject *self, PyObject *nameobj, PyObject *val) { char *name = ""; if (PyUnicode_Check(nameobj)) name = _PyUnicode_AsString(nameobj); if (val == NULL) { PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes")); return -1; } if (strcmp(name, "softspace") == 0) { if (!PyLong_Check(val)) { PyErr_SetString(PyExc_TypeError, _("softspace must be an integer")); return -1; } ((OutputObject *)(self))->softspace = PyLong_AsLong(val); return 0; } PyErr_SetString(PyExc_AttributeError, _("invalid attribute")); return -1; } /***************/ static int PythonIO_Init(void) { PyType_Ready(&OutputType); return PythonIO_Init_io(); } static void PythonIO_Fini(void) { PySys_SetObject("stdout", NULL); PySys_SetObject("stderr", NULL); } /****************************************************** * 3. Implementation of the Vim module for Python */ /* Window type - Implementation functions * -------------------------------------- */ #define WindowType_Check(obj) ((obj)->ob_base.ob_type == &WindowType) /* Buffer type - Implementation functions * -------------------------------------- */ #define BufferType_Check(obj) ((obj)->ob_base.ob_type == &BufferType) static Py_ssize_t BufferLength(PyObject *); static PyObject *BufferItem(PyObject *, Py_ssize_t); static PyObject* BufferSubscript(PyObject *self, PyObject *idx); static Py_ssize_t BufferAsSubscript(PyObject *self, PyObject *idx, PyObject *val); /* Line range type - Implementation functions * -------------------------------------- */ #define RangeType_Check(obj) ((obj)->ob_base.ob_type == &RangeType) static PyObject* RangeSubscript(PyObject *self, PyObject *idx); static Py_ssize_t RangeAsItem(PyObject *, Py_ssize_t, PyObject *); static Py_ssize_t RangeAsSubscript(PyObject *self, PyObject *idx, PyObject *val); /* Current objects type - Implementation functions * ----------------------------------------------- */ static PySequenceMethods BufferAsSeq = { (lenfunc) BufferLength, /* sq_length, len(x) */ (binaryfunc) 0, /* sq_concat, x+y */ (ssizeargfunc) 0, /* sq_repeat, x*n */ (ssizeargfunc) BufferItem, /* sq_item, x[i] */ 0, /* was_sq_slice, x[i:j] */ 0, /* sq_ass_item, x[i]=v */ 0, /* sq_ass_slice, x[i:j]=v */ 0, /* sq_contains */ 0, /* sq_inplace_concat */ 0, /* sq_inplace_repeat */ }; PyMappingMethods BufferAsMapping = { /* mp_length */ (lenfunc)BufferLength, /* mp_subscript */ (binaryfunc)BufferSubscript, /* mp_ass_subscript */ (objobjargproc)BufferAsSubscript, }; /* Buffer object - Definitions */ static PyTypeObject BufferType; static PyObject * BufferNew(buf_T *buf) { /* We need to handle deletion of buffers underneath us. * If we add a "b_python3_ref" field to the buf_T structure, * then we can get at it in buf_freeall() in vim. We then * need to create only ONE Python object per buffer - if * we try to create a second, just INCREF the existing one * and return it. The (single) Python object referring to * the buffer is stored in "b_python3_ref". * Question: what to do on a buf_freeall(). We'll probably * have to either delete the Python object (DECREF it to * zero - a bad idea, as it leaves dangling refs!) or * set the buf_T * value to an invalid value (-1?), which * means we need checks in all access functions... Bah. */ BufferObject *self; if (buf->b_python3_ref != NULL) { self = buf->b_python3_ref; Py_INCREF(self); } else { self = PyObject_NEW(BufferObject, &BufferType); buf->b_python3_ref = self; if (self == NULL) return NULL; self->buf = buf; } return (PyObject *)(self); } static void BufferDestructor(PyObject *self) { BufferObject *this = (BufferObject *)(self); if (this->buf && this->buf != INVALID_BUFFER_VALUE) this->buf->b_python3_ref = NULL; Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * BufferGetattro(PyObject *self, PyObject*nameobj) { BufferObject *this = (BufferObject *)(self); char *name = ""; if (PyUnicode_Check(nameobj)) name = _PyUnicode_AsString(nameobj); if (CheckBuffer(this)) return NULL; if (strcmp(name, "name") == 0) return Py_BuildValue("s", this->buf->b_ffname); else if (strcmp(name, "number") == 0) return Py_BuildValue("n", this->buf->b_fnum); else return PyObject_GenericGetAttr(self, nameobj); } static PyObject * BufferDir(PyObject *self UNUSED, PyObject *args UNUSED) { return Py_BuildValue("[sssss]", "name", "number", "append", "mark", "range"); } static PyObject * BufferRepr(PyObject *self) { static char repr[100]; BufferObject *this = (BufferObject *)(self); if (this->buf == INVALID_BUFFER_VALUE) { vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self)); return PyUnicode_FromString(repr); } else { char *name = (char *)this->buf->b_fname; Py_ssize_t len; if (name == NULL) name = ""; len = strlen(name); if (len > 35) name = name + (35 - len); vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name); return PyUnicode_FromString(repr); } } /******************/ static Py_ssize_t BufferLength(PyObject *self) { if (CheckBuffer((BufferObject *)(self))) return -1; return (Py_ssize_t)(((BufferObject *)(self))->buf->b_ml.ml_line_count); } static PyObject * BufferItem(PyObject *self, Py_ssize_t n) { return RBItem((BufferObject *)(self), n, 1, (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count); } static PyObject * BufferSlice(PyObject *self, Py_ssize_t lo, Py_ssize_t hi) { return RBSlice((BufferObject *)(self), lo, hi, 1, (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count); } static PyObject * BufferSubscript(PyObject *self, PyObject* idx) { if (PyLong_Check(idx)) { long _idx = PyLong_AsLong(idx); return BufferItem(self,_idx); } else if (PySlice_Check(idx)) { Py_ssize_t start, stop, step, slicelen; if (PySlice_GetIndicesEx((PyObject *)idx, (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count+1, &start, &stop, &step, &slicelen) < 0) { return NULL; } return BufferSlice(self, start, stop); } else { PyErr_SetString(PyExc_IndexError, "Index must be int or slice"); return NULL; } } static Py_ssize_t BufferAsSubscript(PyObject *self, PyObject* idx, PyObject* val) { if (PyLong_Check(idx)) { long n = PyLong_AsLong(idx); return RBAsItem((BufferObject *)(self), n, val, 1, (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count, NULL); } else if (PySlice_Check(idx)) { Py_ssize_t start, stop, step, slicelen; if (PySlice_GetIndicesEx((PyObject *)idx, (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count+1, &start, &stop, &step, &slicelen) < 0) { return -1; } return RBAsSlice((BufferObject *)(self), start, stop, val, 1, (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count, NULL); } else { PyErr_SetString(PyExc_IndexError, "Index must be int or slice"); return -1; } } static PySequenceMethods RangeAsSeq = { (lenfunc) RangeLength, /* sq_length, len(x) */ (binaryfunc) 0, /* RangeConcat, sq_concat, x+y */ (ssizeargfunc) 0, /* RangeRepeat, sq_repeat, x*n */ (ssizeargfunc) RangeItem, /* sq_item, x[i] */ 0, /* was_sq_slice, x[i:j] */ (ssizeobjargproc) RangeAsItem, /* sq_as_item, x[i]=v */ 0, /* sq_ass_slice, x[i:j]=v */ 0, /* sq_contains */ 0, /* sq_inplace_concat */ 0, /* sq_inplace_repeat */ }; PyMappingMethods RangeAsMapping = { /* mp_length */ (lenfunc)RangeLength, /* mp_subscript */ (binaryfunc)RangeSubscript, /* mp_ass_subscript */ (objobjargproc)RangeAsSubscript, }; /* Line range object - Implementation */ static void RangeDestructor(PyObject *self) { Py_DECREF(((RangeObject *)(self))->buf); Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * RangeGetattro(PyObject *self, PyObject *nameobj) { char *name = ""; if (PyUnicode_Check(nameobj)) name = _PyUnicode_AsString(nameobj); if (strcmp(name, "start") == 0) return Py_BuildValue("n", ((RangeObject *)(self))->start - 1); else if (strcmp(name, "end") == 0) return Py_BuildValue("n", ((RangeObject *)(self))->end - 1); else return PyObject_GenericGetAttr(self, nameobj); } /****************/ static Py_ssize_t RangeAsItem(PyObject *self, Py_ssize_t n, PyObject *val) { return RBAsItem(((RangeObject *)(self))->buf, n, val, ((RangeObject *)(self))->start, ((RangeObject *)(self))->end, &((RangeObject *)(self))->end); } static Py_ssize_t RangeAsSlice(PyObject *self, Py_ssize_t lo, Py_ssize_t hi, PyObject *val) { return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val, ((RangeObject *)(self))->start, ((RangeObject *)(self))->end, &((RangeObject *)(self))->end); } static PyObject * RangeSubscript(PyObject *self, PyObject* idx) { if (PyLong_Check(idx)) { long _idx = PyLong_AsLong(idx); return RangeItem(self,_idx); } else if (PySlice_Check(idx)) { Py_ssize_t start, stop, step, slicelen; if (PySlice_GetIndicesEx((PyObject *)idx, ((RangeObject *)(self))->end-((RangeObject *)(self))->start+1, &start, &stop, &step, &slicelen) < 0) { return NULL; } return RangeSlice(self, start, stop); } else { PyErr_SetString(PyExc_IndexError, "Index must be int or slice"); return NULL; } } static Py_ssize_t RangeAsSubscript(PyObject *self, PyObject *idx, PyObject *val) { if (PyLong_Check(idx)) { long n = PyLong_AsLong(idx); return RangeAsItem(self, n, val); } else if (PySlice_Check(idx)) { Py_ssize_t start, stop, step, slicelen; if (PySlice_GetIndicesEx((PyObject *)idx, ((RangeObject *)(self))->end-((RangeObject *)(self))->start+1, &start, &stop, &step, &slicelen) < 0) { return -1; } return RangeAsSlice(self, start, stop, val); } else { PyErr_SetString(PyExc_IndexError, "Index must be int or slice"); return -1; } } /* Buffer list object - Definitions */ typedef struct { PyObject_HEAD } BufListObject; static PySequenceMethods BufListAsSeq = { (lenfunc) BufListLength, /* sq_length, len(x) */ (binaryfunc) 0, /* sq_concat, x+y */ (ssizeargfunc) 0, /* sq_repeat, x*n */ (ssizeargfunc) BufListItem, /* sq_item, x[i] */ 0, /* was_sq_slice, x[i:j] */ (ssizeobjargproc) 0, /* sq_as_item, x[i]=v */ 0, /* sq_ass_slice, x[i:j]=v */ 0, /* sq_contains */ 0, /* sq_inplace_concat */ 0, /* sq_inplace_repeat */ }; static PyTypeObject BufListType; /* Window object - Definitions */ static struct PyMethodDef WindowMethods[] = { /* name, function, calling, documentation */ { NULL, NULL, 0, NULL } }; static PyTypeObject WindowType; /* Window object - Implementation */ static PyObject * WindowNew(win_T *win) { /* We need to handle deletion of windows underneath us. * If we add a "w_python3_ref" field to the win_T structure, * then we can get at it in win_free() in vim. We then * need to create only ONE Python object per window - if * we try to create a second, just INCREF the existing one * and return it. The (single) Python object referring to * the window is stored in "w_python3_ref". * On a win_free() we set the Python object's win_T* field * to an invalid value. We trap all uses of a window * object, and reject them if the win_T* field is invalid. */ WindowObject *self; if (win->w_python3_ref) { self = win->w_python3_ref; Py_INCREF(self); } else { self = PyObject_NEW(WindowObject, &WindowType); if (self == NULL) return NULL; self->win = win; win->w_python3_ref = self; } return (PyObject *)(self); } static void WindowDestructor(PyObject *self) { WindowObject *this = (WindowObject *)(self); if (this->win && this->win != INVALID_WINDOW_VALUE) this->win->w_python3_ref = NULL; Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * WindowGetattro(PyObject *self, PyObject *nameobj) { WindowObject *this = (WindowObject *)(self); char *name = ""; if (PyUnicode_Check(nameobj)) name = _PyUnicode_AsString(nameobj); if (CheckWindow(this)) return NULL; if (strcmp(name, "buffer") == 0) return (PyObject *)BufferNew(this->win->w_buffer); else if (strcmp(name, "cursor") == 0) { pos_T *pos = &this->win->w_cursor; return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col)); } else if (strcmp(name, "height") == 0) return Py_BuildValue("l", (long)(this->win->w_height)); #ifdef FEAT_VERTSPLIT else if (strcmp(name, "width") == 0) return Py_BuildValue("l", (long)(W_WIDTH(this->win))); #endif else if (strcmp(name,"__members__") == 0) return Py_BuildValue("[sss]", "buffer", "cursor", "height"); else return PyObject_GenericGetAttr(self, nameobj); } static int WindowSetattro(PyObject *self, PyObject *nameobj, PyObject *val) { char *name = ""; if (PyUnicode_Check(nameobj)) name = _PyUnicode_AsString(nameobj); return WindowSetattr(self, name, val); } /* Window list object - Definitions */ typedef struct { PyObject_HEAD } WinListObject; static PySequenceMethods WinListAsSeq = { (lenfunc) WinListLength, /* sq_length, len(x) */ (binaryfunc) 0, /* sq_concat, x+y */ (ssizeargfunc) 0, /* sq_repeat, x*n */ (ssizeargfunc) WinListItem, /* sq_item, x[i] */ 0, /* sq_slice, x[i:j] */ (ssizeobjargproc)0, /* sq_as_item, x[i]=v */ 0, /* sq_ass_slice, x[i:j]=v */ 0, /* sq_contains */ 0, /* sq_inplace_concat */ 0, /* sq_inplace_repeat */ }; static PyTypeObject WinListType; /* Current items object - Definitions */ typedef struct { PyObject_HEAD } CurrentObject; static PyTypeObject CurrentType; /* Current items object - Implementation */ static PyObject * CurrentGetattro(PyObject *self UNUSED, PyObject *nameobj) { char *name = ""; if (PyUnicode_Check(nameobj)) name = _PyUnicode_AsString(nameobj); if (strcmp(name, "buffer") == 0) return (PyObject *)BufferNew(curbuf); else if (strcmp(name, "window") == 0) return (PyObject *)WindowNew(curwin); else if (strcmp(name, "line") == 0) return GetBufferLine(curbuf, (Py_ssize_t)curwin->w_cursor.lnum); else if (strcmp(name, "range") == 0) return RangeNew(curbuf, RangeStart, RangeEnd); else if (strcmp(name,"__members__") == 0) return Py_BuildValue("[ssss]", "buffer", "window", "line", "range"); else { PyErr_SetString(PyExc_AttributeError, name); return NULL; } } static int CurrentSetattro(PyObject *self UNUSED, PyObject *nameobj, PyObject *value) { char *name = ""; if (PyUnicode_Check(nameobj)) name = _PyUnicode_AsString(nameobj); if (strcmp(name, "line") == 0) { if (SetBufferLine(curbuf, (Py_ssize_t)curwin->w_cursor.lnum, value, NULL) == FAIL) return -1; return 0; } else { PyErr_SetString(PyExc_AttributeError, name); return -1; } } /* External interface */ void python3_buffer_free(buf_T *buf) { if (buf->b_python3_ref != NULL) { BufferObject *bp = buf->b_python3_ref; bp->buf = INVALID_BUFFER_VALUE; buf->b_python3_ref = NULL; } } #if defined(FEAT_WINDOWS) || defined(PROTO) void python3_window_free(win_T *win) { if (win->w_python3_ref != NULL) { WindowObject *wp = win->w_python3_ref; wp->win = INVALID_WINDOW_VALUE; win->w_python3_ref = NULL; } } #endif static BufListObject TheBufferList = { PyObject_HEAD_INIT(&BufListType) }; static WinListObject TheWindowList = { PyObject_HEAD_INIT(&WinListType) }; static CurrentObject TheCurrent = { PyObject_HEAD_INIT(&CurrentType) }; PyDoc_STRVAR(vim_module_doc,"vim python interface\n"); static struct PyModuleDef vimmodule; #ifndef PROTO PyMODINIT_FUNC Py3Init_vim(void) { PyObject *mod; /* The special value is removed from sys.path in Python3_Init(). */ static wchar_t *(argv[2]) = {L"/must>not&exist/foo", NULL}; PyType_Ready(&BufferType); PyType_Ready(&RangeType); PyType_Ready(&WindowType); PyType_Ready(&BufListType); PyType_Ready(&WinListType); PyType_Ready(&CurrentType); /* Set sys.argv[] to avoid a crash in warn(). */ PySys_SetArgv(1, argv); mod = PyModule_Create(&vimmodule); if (mod == NULL) return NULL; VimError = PyErr_NewException("vim.error", NULL, NULL); Py_INCREF(VimError); PyModule_AddObject(mod, "error", VimError); Py_INCREF((PyObject *)(void *)&TheBufferList); PyModule_AddObject(mod, "buffers", (PyObject *)(void *)&TheBufferList); Py_INCREF((PyObject *)(void *)&TheCurrent); PyModule_AddObject(mod, "current", (PyObject *)(void *)&TheCurrent); Py_INCREF((PyObject *)(void *)&TheWindowList); PyModule_AddObject(mod, "windows", (PyObject *)(void *)&TheWindowList); if (PyErr_Occurred()) return NULL; return mod; } #endif /************************************************************************* * 4. Utility functions for handling the interface between Vim and Python. */ /* Convert a Vim line into a Python string. * All internal newlines are replaced by null characters. * * On errors, the Python exception data is set, and NULL is returned. */ static PyObject * LineToString(const char *str) { PyObject *result; Py_ssize_t len = strlen(str); char *tmp,*p; tmp = (char *)alloc((unsigned)(len+1)); p = tmp; if (p == NULL) { PyErr_NoMemory(); return NULL; } while (*str) { if (*str == '\n') *p = '\0'; else *p = *str; ++p; ++str; } *p = '\0'; result = PyUnicode_Decode(tmp, len, (char *)ENC_OPT, CODEC_ERROR_HANDLER); vim_free(tmp); return result; } static void init_structs(void) { vim_memset(&OutputType, 0, sizeof(OutputType)); OutputType.tp_name = "vim.message"; OutputType.tp_basicsize = sizeof(OutputObject); OutputType.tp_getattro = OutputGetattro; OutputType.tp_setattro = OutputSetattro; OutputType.tp_flags = Py_TPFLAGS_DEFAULT; OutputType.tp_doc = "vim message object"; OutputType.tp_methods = OutputMethods; OutputType.tp_alloc = call_PyType_GenericAlloc; OutputType.tp_new = call_PyType_GenericNew; OutputType.tp_free = call_PyObject_Free; vim_memset(&BufferType, 0, sizeof(BufferType)); BufferType.tp_name = "vim.buffer"; BufferType.tp_basicsize = sizeof(BufferType); BufferType.tp_dealloc = BufferDestructor; BufferType.tp_repr = BufferRepr; BufferType.tp_as_sequence = &BufferAsSeq; BufferType.tp_as_mapping = &BufferAsMapping; BufferType.tp_getattro = BufferGetattro; BufferType.tp_flags = Py_TPFLAGS_DEFAULT; BufferType.tp_doc = "vim buffer object"; BufferType.tp_methods = BufferMethods; BufferType.tp_alloc = call_PyType_GenericAlloc; BufferType.tp_new = call_PyType_GenericNew; BufferType.tp_free = call_PyObject_Free; vim_memset(&WindowType, 0, sizeof(WindowType)); WindowType.tp_name = "vim.window"; WindowType.tp_basicsize = sizeof(WindowObject); WindowType.tp_dealloc = WindowDestructor; WindowType.tp_repr = WindowRepr; WindowType.tp_getattro = WindowGetattro; WindowType.tp_setattro = WindowSetattro; WindowType.tp_flags = Py_TPFLAGS_DEFAULT; WindowType.tp_doc = "vim Window object"; WindowType.tp_methods = WindowMethods; WindowType.tp_alloc = call_PyType_GenericAlloc; WindowType.tp_new = call_PyType_GenericNew; WindowType.tp_free = call_PyObject_Free; vim_memset(&BufListType, 0, sizeof(BufListType)); BufListType.tp_name = "vim.bufferlist"; BufListType.tp_basicsize = sizeof(BufListObject); BufListType.tp_as_sequence = &BufListAsSeq; BufListType.tp_flags = Py_TPFLAGS_DEFAULT; BufferType.tp_doc = "vim buffer list"; vim_memset(&WinListType, 0, sizeof(WinListType)); WinListType.tp_name = "vim.windowlist"; WinListType.tp_basicsize = sizeof(WinListType); WinListType.tp_as_sequence = &WinListAsSeq; WinListType.tp_flags = Py_TPFLAGS_DEFAULT; WinListType.tp_doc = "vim window list"; vim_memset(&RangeType, 0, sizeof(RangeType)); RangeType.tp_name = "vim.range"; RangeType.tp_basicsize = sizeof(RangeObject); RangeType.tp_dealloc = RangeDestructor; RangeType.tp_repr = RangeRepr; RangeType.tp_as_sequence = &RangeAsSeq; RangeType.tp_as_mapping = &RangeAsMapping; RangeType.tp_getattro = RangeGetattro; RangeType.tp_flags = Py_TPFLAGS_DEFAULT; RangeType.tp_doc = "vim Range object"; RangeType.tp_methods = RangeMethods; RangeType.tp_alloc = call_PyType_GenericAlloc; RangeType.tp_new = call_PyType_GenericNew; RangeType.tp_free = call_PyObject_Free; vim_memset(&CurrentType, 0, sizeof(CurrentType)); CurrentType.tp_name = "vim.currentdata"; CurrentType.tp_basicsize = sizeof(CurrentObject); CurrentType.tp_getattro = CurrentGetattro; CurrentType.tp_setattro = CurrentSetattro; CurrentType.tp_flags = Py_TPFLAGS_DEFAULT; CurrentType.tp_doc = "vim current object"; vim_memset(&vimmodule, 0, sizeof(vimmodule)); vimmodule.m_name = "vim"; vimmodule.m_doc = vim_module_doc; vimmodule.m_size = -1; vimmodule.m_methods = VimMethods; }
zyz2011-vim
src/if_python3.c
C
gpl2
46,865
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * if_perl.xs: Main code for Perl interface support. * Mostly written by Sven Verdoolaege. */ #define _memory_h /* avoid memset redeclaration */ #define IN_PERL_FILE /* don't include if_perl.pro from proto.h */ #include "vim.h" /* * Work around clashes between Perl and Vim namespace. proto.h doesn't * include if_perl.pro and perlsfio.pro when IN_PERL_FILE is defined, because * we need the CV typedef. proto.h can't be moved to after including * if_perl.h, because we get all sorts of name clashes then. */ #ifndef PROTO #ifndef __MINGW32__ # include "proto/if_perl.pro" # include "proto/if_perlsfio.pro" #endif #endif /* Perl compatibility stuff. This should ensure compatibility with older * versions of Perl. */ #ifndef PERL_VERSION # include <patchlevel.h> # define PERL_REVISION 5 # define PERL_VERSION PATCHLEVEL # define PERL_SUBVERSION SUBVERSION #endif /* * Quoting Jan Dubois of Active State: * ActivePerl build 822 still identifies itself as 5.8.8 but already * contains many of the changes from the upcoming Perl 5.8.9 release. * * The changes include addition of two symbols (Perl_sv_2iv_flags, * Perl_newXS_flags) not present in earlier releases. * * Jan Dubois suggested the following guarding scheme. * * Active State defined ACTIVEPERL_VERSION as a string in versions before * 5.8.8; and so the comparison to 822 below needs to be guarded. */ #if (PERL_REVISION == 5) && (PERL_VERSION == 8) && (PERL_SUBVERSION >= 8) # if (ACTIVEPERL_VERSION >= 822) || (PERL_SUBVERSION >= 9) # define PERL589_OR_LATER # endif #endif #if (PERL_REVISION == 5) && (PERL_VERSION >= 9) # define PERL589_OR_LATER #endif #if (PERL_REVISION == 5) && ((PERL_VERSION > 10) || \ (PERL_VERSION == 10) && (PERL_SUBVERSION >= 1)) # define PERL5101_OR_LATER #endif #ifndef pTHX # define pTHX void # define pTHX_ #endif #ifndef EXTERN_C # define EXTERN_C #endif /* Compatibility hacks over */ static PerlInterpreter *perl_interp = NULL; static void xs_init __ARGS((pTHX)); static void VIM_init __ARGS((void)); EXTERN_C void boot_DynaLoader __ARGS((pTHX_ CV*)); /* * For dynamic linked perl. */ #if defined(DYNAMIC_PERL) || defined(PROTO) #ifndef DYNAMIC_PERL /* just generating prototypes */ #ifdef WIN3264 typedef int HANDLE; #endif typedef int XSINIT_t; typedef int XSUBADDR_t; typedef int perl_key; #endif #ifndef WIN3264 #include <dlfcn.h> #define HANDLE void* #define PERL_PROC void* #define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL) #define symbol_from_dll dlsym #define close_dll dlclose #else #define PERL_PROC FARPROC #define load_dll vimLoadLib #define symbol_from_dll GetProcAddress #define close_dll FreeLibrary #endif /* * Wrapper defines */ # define perl_alloc dll_perl_alloc # define perl_construct dll_perl_construct # define perl_parse dll_perl_parse # define perl_run dll_perl_run # define perl_destruct dll_perl_destruct # define perl_free dll_perl_free # define Perl_get_context dll_Perl_get_context # define Perl_croak dll_Perl_croak # ifdef PERL5101_OR_LATER # define Perl_croak_xs_usage dll_Perl_croak_xs_usage # endif # ifndef PROTO # define Perl_croak_nocontext dll_Perl_croak_nocontext # define Perl_call_argv dll_Perl_call_argv # define Perl_call_pv dll_Perl_call_pv # define Perl_eval_sv dll_Perl_eval_sv # define Perl_get_sv dll_Perl_get_sv # define Perl_eval_pv dll_Perl_eval_pv # define Perl_call_method dll_Perl_call_method # endif # define Perl_dowantarray dll_Perl_dowantarray # define Perl_free_tmps dll_Perl_free_tmps # define Perl_gv_stashpv dll_Perl_gv_stashpv # define Perl_markstack_grow dll_Perl_markstack_grow # define Perl_mg_find dll_Perl_mg_find # define Perl_newXS dll_Perl_newXS # define Perl_newSV dll_Perl_newSV # define Perl_newSViv dll_Perl_newSViv # define Perl_newSVpv dll_Perl_newSVpv # define Perl_pop_scope dll_Perl_pop_scope # define Perl_push_scope dll_Perl_push_scope # define Perl_save_int dll_Perl_save_int # define Perl_stack_grow dll_Perl_stack_grow # define Perl_set_context dll_Perl_set_context # if (PERL_REVISION == 5) && (PERL_VERSION >= 14) # define Perl_sv_2bool_flags dll_Perl_sv_2bool_flags # define Perl_xs_apiversion_bootcheck dll_Perl_xs_apiversion_bootcheck # else # define Perl_sv_2bool dll_Perl_sv_2bool # endif # define Perl_sv_2iv dll_Perl_sv_2iv # define Perl_sv_2mortal dll_Perl_sv_2mortal # if (PERL_REVISION == 5) && (PERL_VERSION >= 8) # define Perl_sv_2pv_flags dll_Perl_sv_2pv_flags # define Perl_sv_2pv_nolen dll_Perl_sv_2pv_nolen # else # define Perl_sv_2pv dll_Perl_sv_2pv # endif # define Perl_sv_bless dll_Perl_sv_bless # if (PERL_REVISION == 5) && (PERL_VERSION >= 8) # define Perl_sv_catpvn_flags dll_Perl_sv_catpvn_flags # else # define Perl_sv_catpvn dll_Perl_sv_catpvn # endif #ifdef PERL589_OR_LATER # define Perl_sv_2iv_flags dll_Perl_sv_2iv_flags # define Perl_newXS_flags dll_Perl_newXS_flags #endif # define Perl_sv_free dll_Perl_sv_free # if (PERL_REVISION == 5) && (PERL_VERSION >= 10) # define Perl_sv_free2 dll_Perl_sv_free2 # endif # define Perl_sv_isa dll_Perl_sv_isa # define Perl_sv_magic dll_Perl_sv_magic # define Perl_sv_setiv dll_Perl_sv_setiv # define Perl_sv_setpv dll_Perl_sv_setpv # define Perl_sv_setpvn dll_Perl_sv_setpvn # if (PERL_REVISION == 5) && (PERL_VERSION >= 8) # define Perl_sv_setsv_flags dll_Perl_sv_setsv_flags # else # define Perl_sv_setsv dll_Perl_sv_setsv # endif # define Perl_sv_upgrade dll_Perl_sv_upgrade # define Perl_Tstack_sp_ptr dll_Perl_Tstack_sp_ptr # define Perl_Top_ptr dll_Perl_Top_ptr # define Perl_Tstack_base_ptr dll_Perl_Tstack_base_ptr # define Perl_Tstack_max_ptr dll_Perl_Tstack_max_ptr # define Perl_Ttmps_ix_ptr dll_Perl_Ttmps_ix_ptr # define Perl_Ttmps_floor_ptr dll_Perl_Ttmps_floor_ptr # define Perl_Tmarkstack_ptr_ptr dll_Perl_Tmarkstack_ptr_ptr # define Perl_Tmarkstack_max_ptr dll_Perl_Tmarkstack_max_ptr # define Perl_TSv_ptr dll_Perl_TSv_ptr # define Perl_TXpv_ptr dll_Perl_TXpv_ptr # define Perl_Tna_ptr dll_Perl_Tna_ptr # define Perl_Idefgv_ptr dll_Perl_Idefgv_ptr # define Perl_Ierrgv_ptr dll_Perl_Ierrgv_ptr # define Perl_Isv_yes_ptr dll_Perl_Isv_yes_ptr # define boot_DynaLoader dll_boot_DynaLoader # define Perl_Gthr_key_ptr dll_Perl_Gthr_key_ptr # define Perl_sys_init dll_Perl_sys_init # define Perl_sys_term dll_Perl_sys_term # define Perl_ISv_ptr dll_Perl_ISv_ptr # define Perl_Istack_max_ptr dll_Perl_Istack_max_ptr # define Perl_Istack_base_ptr dll_Perl_Istack_base_ptr # define Perl_Itmps_ix_ptr dll_Perl_Itmps_ix_ptr # define Perl_Itmps_floor_ptr dll_Perl_Itmps_floor_ptr # define Perl_IXpv_ptr dll_Perl_IXpv_ptr # define Perl_Ina_ptr dll_Perl_Ina_ptr # define Perl_Imarkstack_ptr_ptr dll_Perl_Imarkstack_ptr_ptr # define Perl_Imarkstack_max_ptr dll_Perl_Imarkstack_max_ptr # define Perl_Istack_sp_ptr dll_Perl_Istack_sp_ptr # define Perl_Iop_ptr dll_Perl_Iop_ptr # define Perl_call_list dll_Perl_call_list # define Perl_Iscopestack_ix_ptr dll_Perl_Iscopestack_ix_ptr # define Perl_Iunitcheckav_ptr dll_Perl_Iunitcheckav_ptr /* * Declare HANDLE for perl.dll and function pointers. */ static HANDLE hPerlLib = NULL; static PerlInterpreter* (*perl_alloc)(); static void (*perl_construct)(PerlInterpreter*); static void (*perl_destruct)(PerlInterpreter*); static void (*perl_free)(PerlInterpreter*); static int (*perl_run)(PerlInterpreter*); static int (*perl_parse)(PerlInterpreter*, XSINIT_t, int, char**, char**); static void* (*Perl_get_context)(void); static void (*Perl_croak)(pTHX_ const char*, ...); #ifdef PERL5101_OR_LATER static void (*Perl_croak_xs_usage)(pTHX_ const CV *const, const char *const params); #endif static void (*Perl_croak_nocontext)(const char*, ...); static I32 (*Perl_dowantarray)(pTHX); static void (*Perl_free_tmps)(pTHX); static HV* (*Perl_gv_stashpv)(pTHX_ const char*, I32); static void (*Perl_markstack_grow)(pTHX); static MAGIC* (*Perl_mg_find)(pTHX_ SV*, int); static CV* (*Perl_newXS)(pTHX_ char*, XSUBADDR_t, char*); static SV* (*Perl_newSV)(pTHX_ STRLEN); static SV* (*Perl_newSViv)(pTHX_ IV); static SV* (*Perl_newSVpv)(pTHX_ const char*, STRLEN); static I32 (*Perl_call_argv)(pTHX_ const char*, I32, char**); static I32 (*Perl_call_pv)(pTHX_ const char*, I32); static I32 (*Perl_eval_sv)(pTHX_ SV*, I32); static SV* (*Perl_get_sv)(pTHX_ const char*, I32); static SV* (*Perl_eval_pv)(pTHX_ const char*, I32); static SV* (*Perl_call_method)(pTHX_ const char*, I32); static void (*Perl_pop_scope)(pTHX); static void (*Perl_push_scope)(pTHX); static void (*Perl_save_int)(pTHX_ int*); static SV** (*Perl_stack_grow)(pTHX_ SV**, SV**p, int); static SV** (*Perl_set_context)(void*); #if (PERL_REVISION == 5) && (PERL_VERSION >= 14) static bool (*Perl_sv_2bool_flags)(pTHX_ SV*, I32); static void (*Perl_xs_apiversion_bootcheck)(pTHX_ SV *module, const char *api_p, STRLEN api_len); #else static bool (*Perl_sv_2bool)(pTHX_ SV*); #endif static IV (*Perl_sv_2iv)(pTHX_ SV*); static SV* (*Perl_sv_2mortal)(pTHX_ SV*); #if (PERL_REVISION == 5) && (PERL_VERSION >= 8) static char* (*Perl_sv_2pv_flags)(pTHX_ SV*, STRLEN*, I32); static char* (*Perl_sv_2pv_nolen)(pTHX_ SV*); #else static char* (*Perl_sv_2pv)(pTHX_ SV*, STRLEN*); #endif static SV* (*Perl_sv_bless)(pTHX_ SV*, HV*); #if (PERL_REVISION == 5) && (PERL_VERSION >= 8) static void (*Perl_sv_catpvn_flags)(pTHX_ SV* , const char*, STRLEN, I32); #else static void (*Perl_sv_catpvn)(pTHX_ SV*, const char*, STRLEN); #endif #ifdef PERL589_OR_LATER static IV (*Perl_sv_2iv_flags)(pTHX_ SV* sv, I32 flags); static CV * (*Perl_newXS_flags)(pTHX_ const char *name, XSUBADDR_t subaddr, const char *const filename, const char *const proto, U32 flags); #endif static void (*Perl_sv_free)(pTHX_ SV*); static int (*Perl_sv_isa)(pTHX_ SV*, const char*); static void (*Perl_sv_magic)(pTHX_ SV*, SV*, int, const char*, I32); static void (*Perl_sv_setiv)(pTHX_ SV*, IV); static void (*Perl_sv_setpv)(pTHX_ SV*, const char*); static void (*Perl_sv_setpvn)(pTHX_ SV*, const char*, STRLEN); #if (PERL_REVISION == 5) && (PERL_VERSION >= 8) static void (*Perl_sv_setsv_flags)(pTHX_ SV*, SV*, I32); #else static void (*Perl_sv_setsv)(pTHX_ SV*, SV*); #endif static bool (*Perl_sv_upgrade)(pTHX_ SV*, U32); #if (PERL_REVISION == 5) && (PERL_VERSION < 10) static SV*** (*Perl_Tstack_sp_ptr)(register PerlInterpreter*); static OP** (*Perl_Top_ptr)(register PerlInterpreter*); static SV*** (*Perl_Tstack_base_ptr)(register PerlInterpreter*); static SV*** (*Perl_Tstack_max_ptr)(register PerlInterpreter*); static I32* (*Perl_Ttmps_ix_ptr)(register PerlInterpreter*); static I32* (*Perl_Ttmps_floor_ptr)(register PerlInterpreter*); static I32** (*Perl_Tmarkstack_ptr_ptr)(register PerlInterpreter*); static I32** (*Perl_Tmarkstack_max_ptr)(register PerlInterpreter*); static SV** (*Perl_TSv_ptr)(register PerlInterpreter*); static XPV** (*Perl_TXpv_ptr)(register PerlInterpreter*); static STRLEN* (*Perl_Tna_ptr)(register PerlInterpreter*); #else static void (*Perl_sv_free2)(pTHX_ SV*); static void (*Perl_sys_init)(int* argc, char*** argv); static void (*Perl_sys_term)(void); static SV** (*Perl_ISv_ptr)(register PerlInterpreter*); static SV*** (*Perl_Istack_max_ptr)(register PerlInterpreter*); static SV*** (*Perl_Istack_base_ptr)(register PerlInterpreter*); static XPV** (*Perl_IXpv_ptr)(register PerlInterpreter*); static I32* (*Perl_Itmps_ix_ptr)(register PerlInterpreter*); static I32* (*Perl_Itmps_floor_ptr)(register PerlInterpreter*); static STRLEN* (*Perl_Ina_ptr)(register PerlInterpreter*); static I32** (*Perl_Imarkstack_ptr_ptr)(register PerlInterpreter*); static I32** (*Perl_Imarkstack_max_ptr)(register PerlInterpreter*); static SV*** (*Perl_Istack_sp_ptr)(register PerlInterpreter*); static OP** (*Perl_Iop_ptr)(register PerlInterpreter*); static void (*Perl_call_list)(pTHX_ I32, AV*); static I32* (*Perl_Iscopestack_ix_ptr)(register PerlInterpreter*); static AV** (*Perl_Iunitcheckav_ptr)(register PerlInterpreter*); #endif static GV** (*Perl_Idefgv_ptr)(register PerlInterpreter*); static GV** (*Perl_Ierrgv_ptr)(register PerlInterpreter*); static SV* (*Perl_Isv_yes_ptr)(register PerlInterpreter*); static void (*boot_DynaLoader)_((pTHX_ CV*)); static perl_key* (*Perl_Gthr_key_ptr)_((pTHX)); /* * Table of name to function pointer of perl. */ static struct { char* name; PERL_PROC* ptr; } perl_funcname_table[] = { {"perl_alloc", (PERL_PROC*)&perl_alloc}, {"perl_construct", (PERL_PROC*)&perl_construct}, {"perl_destruct", (PERL_PROC*)&perl_destruct}, {"perl_free", (PERL_PROC*)&perl_free}, {"perl_run", (PERL_PROC*)&perl_run}, {"perl_parse", (PERL_PROC*)&perl_parse}, {"Perl_get_context", (PERL_PROC*)&Perl_get_context}, {"Perl_croak", (PERL_PROC*)&Perl_croak}, #ifdef PERL5101_OR_LATER {"Perl_croak_xs_usage", (PERL_PROC*)&Perl_croak_xs_usage}, #endif {"Perl_croak_nocontext", (PERL_PROC*)&Perl_croak_nocontext}, {"Perl_dowantarray", (PERL_PROC*)&Perl_dowantarray}, {"Perl_free_tmps", (PERL_PROC*)&Perl_free_tmps}, {"Perl_gv_stashpv", (PERL_PROC*)&Perl_gv_stashpv}, {"Perl_markstack_grow", (PERL_PROC*)&Perl_markstack_grow}, {"Perl_mg_find", (PERL_PROC*)&Perl_mg_find}, {"Perl_newXS", (PERL_PROC*)&Perl_newXS}, {"Perl_newSV", (PERL_PROC*)&Perl_newSV}, {"Perl_newSViv", (PERL_PROC*)&Perl_newSViv}, {"Perl_newSVpv", (PERL_PROC*)&Perl_newSVpv}, {"Perl_call_argv", (PERL_PROC*)&Perl_call_argv}, {"Perl_call_pv", (PERL_PROC*)&Perl_call_pv}, {"Perl_eval_sv", (PERL_PROC*)&Perl_eval_sv}, {"Perl_get_sv", (PERL_PROC*)&Perl_get_sv}, {"Perl_eval_pv", (PERL_PROC*)&Perl_eval_pv}, {"Perl_call_method", (PERL_PROC*)&Perl_call_method}, {"Perl_pop_scope", (PERL_PROC*)&Perl_pop_scope}, {"Perl_push_scope", (PERL_PROC*)&Perl_push_scope}, {"Perl_save_int", (PERL_PROC*)&Perl_save_int}, {"Perl_stack_grow", (PERL_PROC*)&Perl_stack_grow}, {"Perl_set_context", (PERL_PROC*)&Perl_set_context}, #if (PERL_REVISION == 5) && (PERL_VERSION >= 14) {"Perl_sv_2bool_flags", (PERL_PROC*)&Perl_sv_2bool_flags}, {"Perl_xs_apiversion_bootcheck",(PERL_PROC*)&Perl_xs_apiversion_bootcheck}, #else {"Perl_sv_2bool", (PERL_PROC*)&Perl_sv_2bool}, #endif {"Perl_sv_2iv", (PERL_PROC*)&Perl_sv_2iv}, {"Perl_sv_2mortal", (PERL_PROC*)&Perl_sv_2mortal}, #if (PERL_REVISION == 5) && (PERL_VERSION >= 8) {"Perl_sv_2pv_flags", (PERL_PROC*)&Perl_sv_2pv_flags}, {"Perl_sv_2pv_nolen", (PERL_PROC*)&Perl_sv_2pv_nolen}, #else {"Perl_sv_2pv", (PERL_PROC*)&Perl_sv_2pv}, #endif #ifdef PERL589_OR_LATER {"Perl_sv_2iv_flags", (PERL_PROC*)&Perl_sv_2iv_flags}, {"Perl_newXS_flags", (PERL_PROC*)&Perl_newXS_flags}, #endif {"Perl_sv_bless", (PERL_PROC*)&Perl_sv_bless}, #if (PERL_REVISION == 5) && (PERL_VERSION >= 8) {"Perl_sv_catpvn_flags", (PERL_PROC*)&Perl_sv_catpvn_flags}, #else {"Perl_sv_catpvn", (PERL_PROC*)&Perl_sv_catpvn}, #endif {"Perl_sv_free", (PERL_PROC*)&Perl_sv_free}, {"Perl_sv_isa", (PERL_PROC*)&Perl_sv_isa}, {"Perl_sv_magic", (PERL_PROC*)&Perl_sv_magic}, {"Perl_sv_setiv", (PERL_PROC*)&Perl_sv_setiv}, {"Perl_sv_setpv", (PERL_PROC*)&Perl_sv_setpv}, {"Perl_sv_setpvn", (PERL_PROC*)&Perl_sv_setpvn}, #if (PERL_REVISION == 5) && (PERL_VERSION >= 8) {"Perl_sv_setsv_flags", (PERL_PROC*)&Perl_sv_setsv_flags}, #else {"Perl_sv_setsv", (PERL_PROC*)&Perl_sv_setsv}, #endif {"Perl_sv_upgrade", (PERL_PROC*)&Perl_sv_upgrade}, #if (PERL_REVISION == 5) && (PERL_VERSION < 10) {"Perl_Tstack_sp_ptr", (PERL_PROC*)&Perl_Tstack_sp_ptr}, {"Perl_Top_ptr", (PERL_PROC*)&Perl_Top_ptr}, {"Perl_Tstack_base_ptr", (PERL_PROC*)&Perl_Tstack_base_ptr}, {"Perl_Tstack_max_ptr", (PERL_PROC*)&Perl_Tstack_max_ptr}, {"Perl_Ttmps_ix_ptr", (PERL_PROC*)&Perl_Ttmps_ix_ptr}, {"Perl_Ttmps_floor_ptr", (PERL_PROC*)&Perl_Ttmps_floor_ptr}, {"Perl_Tmarkstack_ptr_ptr", (PERL_PROC*)&Perl_Tmarkstack_ptr_ptr}, {"Perl_Tmarkstack_max_ptr", (PERL_PROC*)&Perl_Tmarkstack_max_ptr}, {"Perl_TSv_ptr", (PERL_PROC*)&Perl_TSv_ptr}, {"Perl_TXpv_ptr", (PERL_PROC*)&Perl_TXpv_ptr}, {"Perl_Tna_ptr", (PERL_PROC*)&Perl_Tna_ptr}, #else {"Perl_sv_free2", (PERL_PROC*)&Perl_sv_free2}, {"Perl_sys_init", (PERL_PROC*)&Perl_sys_init}, {"Perl_sys_term", (PERL_PROC*)&Perl_sys_term}, {"Perl_call_list", (PERL_PROC*)&Perl_call_list}, # if (PERL_REVISION == 5) && (PERL_VERSION >= 14) # else {"Perl_ISv_ptr", (PERL_PROC*)&Perl_ISv_ptr}, {"Perl_Istack_max_ptr", (PERL_PROC*)&Perl_Istack_max_ptr}, {"Perl_Istack_base_ptr", (PERL_PROC*)&Perl_Istack_base_ptr}, {"Perl_IXpv_ptr", (PERL_PROC*)&Perl_IXpv_ptr}, {"Perl_Itmps_ix_ptr", (PERL_PROC*)&Perl_Itmps_ix_ptr}, {"Perl_Itmps_floor_ptr", (PERL_PROC*)&Perl_Itmps_floor_ptr}, {"Perl_Ina_ptr", (PERL_PROC*)&Perl_Ina_ptr}, {"Perl_Imarkstack_ptr_ptr", (PERL_PROC*)&Perl_Imarkstack_ptr_ptr}, {"Perl_Imarkstack_max_ptr", (PERL_PROC*)&Perl_Imarkstack_max_ptr}, {"Perl_Istack_sp_ptr", (PERL_PROC*)&Perl_Istack_sp_ptr}, {"Perl_Iop_ptr", (PERL_PROC*)&Perl_Iop_ptr}, {"Perl_Iscopestack_ix_ptr", (PERL_PROC*)&Perl_Iscopestack_ix_ptr}, {"Perl_Iunitcheckav_ptr", (PERL_PROC*)&Perl_Iunitcheckav_ptr}, # endif #endif #if (PERL_REVISION == 5) && (PERL_VERSION >= 14) #else {"Perl_Idefgv_ptr", (PERL_PROC*)&Perl_Idefgv_ptr}, {"Perl_Ierrgv_ptr", (PERL_PROC*)&Perl_Ierrgv_ptr}, {"Perl_Isv_yes_ptr", (PERL_PROC*)&Perl_Isv_yes_ptr}, {"Perl_Gthr_key_ptr", (PERL_PROC*)&Perl_Gthr_key_ptr}, #endif {"boot_DynaLoader", (PERL_PROC*)&boot_DynaLoader}, {"", NULL}, }; /* * Make all runtime-links of perl. * * 1. Get module handle using LoadLibraryEx. * 2. Get pointer to perl function by GetProcAddress. * 3. Repeat 2, until get all functions will be used. * * Parameter 'libname' provides name of DLL. * Return OK or FAIL. */ static int perl_runtime_link_init(char *libname, int verbose) { int i; if (hPerlLib != NULL) return OK; if ((hPerlLib = load_dll(libname)) == NULL) { if (verbose) EMSG2(_("E370: Could not load library %s"), libname); return FAIL; } for (i = 0; perl_funcname_table[i].ptr; ++i) { if (!(*perl_funcname_table[i].ptr = symbol_from_dll(hPerlLib, perl_funcname_table[i].name))) { close_dll(hPerlLib); hPerlLib = NULL; if (verbose) EMSG2(_(e_loadfunc), perl_funcname_table[i].name); return FAIL; } } return OK; } /* * If runtime-link-perl(DLL) was loaded successfully, return TRUE. * There were no DLL loaded, return FALSE. */ int perl_enabled(verbose) int verbose; { return perl_runtime_link_init(DYNAMIC_PERL_DLL, verbose) == OK; } #endif /* DYNAMIC_PERL */ /* * perl_init(): initialize perl interpreter * We have to call perl_parse to initialize some structures, * there's nothing to actually parse. */ static void perl_init() { char *bootargs[] = { "VI", NULL }; int argc = 3; static char *argv[] = { "", "-e", "" }; #if (PERL_REVISION == 5) && (PERL_VERSION >= 10) Perl_sys_init(&argc, (char***)&argv); #endif perl_interp = perl_alloc(); perl_construct(perl_interp); perl_parse(perl_interp, xs_init, argc, argv, 0); perl_call_argv("VIM::bootstrap", (long)G_DISCARD, bootargs); VIM_init(); #ifdef USE_SFIO sfdisc(PerlIO_stdout(), sfdcnewvim()); sfdisc(PerlIO_stderr(), sfdcnewvim()); sfsetbuf(PerlIO_stdout(), NULL, 0); sfsetbuf(PerlIO_stderr(), NULL, 0); #endif } /* * perl_end(): clean up after ourselves */ void perl_end() { if (perl_interp) { perl_run(perl_interp); perl_destruct(perl_interp); perl_free(perl_interp); perl_interp = NULL; #if (PERL_REVISION == 5) && (PERL_VERSION >= 10) Perl_sys_term(); #endif } #ifdef DYNAMIC_PERL if (hPerlLib) { close_dll(hPerlLib); hPerlLib = NULL; } #endif } /* * msg_split(): send a message to the message handling routines * split at '\n' first though. */ void msg_split(s, attr) char_u *s; int attr; /* highlighting attributes */ { char *next; char *token = (char *)s; while ((next = strchr(token, '\n')) && !got_int) { *next++ = '\0'; /* replace \n with \0 */ msg_attr((char_u *)token, attr); token = next; } if (*token && !got_int) msg_attr((char_u *)token, attr); } #ifndef FEAT_EVAL /* * This stub is needed because an "#ifdef FEAT_EVAL" around Eval() doesn't * work properly. */ char_u * eval_to_string(arg, nextcmd, dolist) char_u *arg; char_u **nextcmd; int dolist; { return NULL; } #endif /* * Create a new reference to an SV pointing to the SCR structure * The b_perl_private/w_perl_private part of the SCR structure points to the * SV, so there can only be one such SV for a particular SCR structure. When * the last reference has gone (DESTROY is called), * b_perl_private/w_perl_private is reset; When the screen goes away before * all references are gone, the value of the SV is reset; * any subsequent use of any of those reference will produce * a warning. (see typemap) */ static SV * newWINrv(rv, ptr) SV *rv; win_T *ptr; { sv_upgrade(rv, SVt_RV); if (ptr->w_perl_private == NULL) { ptr->w_perl_private = newSV(0); sv_setiv(ptr->w_perl_private, PTR2IV(ptr)); } else SvREFCNT_inc(ptr->w_perl_private); SvRV(rv) = ptr->w_perl_private; SvROK_on(rv); return sv_bless(rv, gv_stashpv("VIWIN", TRUE)); } static SV * newBUFrv(rv, ptr) SV *rv; buf_T *ptr; { sv_upgrade(rv, SVt_RV); if (ptr->b_perl_private == NULL) { ptr->b_perl_private = newSV(0); sv_setiv(ptr->b_perl_private, PTR2IV(ptr)); } else SvREFCNT_inc(ptr->b_perl_private); SvRV(rv) = ptr->b_perl_private; SvROK_on(rv); return sv_bless(rv, gv_stashpv("VIBUF", TRUE)); } /* * perl_win_free * Remove all refences to the window to be destroyed */ void perl_win_free(wp) win_T *wp; { if (wp->w_perl_private) sv_setiv((SV *)wp->w_perl_private, 0); return; } void perl_buf_free(bp) buf_T *bp; { if (bp->b_perl_private) sv_setiv((SV *)bp->b_perl_private, 0); return; } #ifndef PROTO # if (PERL_REVISION == 5) && (PERL_VERSION >= 8) I32 cur_val(pTHX_ IV iv, SV *sv); # else I32 cur_val(IV iv, SV *sv); #endif /* * Handler for the magic variables $main::curwin and $main::curbuf. * The handler is put into the magic vtbl for these variables. * (This is effectively a C-level equivalent of a tied variable). * There is no "set" function as the variables are read-only. */ # if (PERL_REVISION == 5) && (PERL_VERSION >= 8) I32 cur_val(pTHX_ IV iv, SV *sv) # else I32 cur_val(IV iv, SV *sv) # endif { SV *rv; if (iv == 0) rv = newWINrv(newSV(0), curwin); else rv = newBUFrv(newSV(0), curbuf); sv_setsv(sv, rv); return 0; } #endif /* !PROTO */ struct ufuncs cw_funcs = { cur_val, 0, 0 }; struct ufuncs cb_funcs = { cur_val, 0, 1 }; /* * VIM_init(): Vim-specific initialisation. * Make the magical main::curwin and main::curbuf variables */ static void VIM_init() { static char cw[] = "main::curwin"; static char cb[] = "main::curbuf"; SV *sv; sv = perl_get_sv(cw, TRUE); sv_magic(sv, NULL, 'U', (char *)&cw_funcs, sizeof(cw_funcs)); SvREADONLY_on(sv); sv = perl_get_sv(cb, TRUE); sv_magic(sv, NULL, 'U', (char *)&cb_funcs, sizeof(cb_funcs)); SvREADONLY_on(sv); /* * Setup the Safe compartment. * It shouldn't be a fatal error if the Safe module is missing. * XXX: Only shares the 'Msg' routine (which has to be called * like 'Msg(...)'). */ (void)perl_eval_pv( "if ( eval( 'require Safe' ) ) { $VIM::safe = Safe->new(); $VIM::safe->share_from( 'VIM', ['Msg'] ); }", G_DISCARD | G_VOID ); } #ifdef DYNAMIC_PERL static char *e_noperl = N_("Sorry, this command is disabled: the Perl library could not be loaded."); #endif /* * ":perl" */ void ex_perl(eap) exarg_T *eap; { char *err; char *script; STRLEN length; SV *sv; #ifdef HAVE_SANDBOX SV *safe; #endif script = (char *)script_get(eap, eap->arg); if (eap->skip) { vim_free(script); return; } if (perl_interp == NULL) { #ifdef DYNAMIC_PERL if (!perl_enabled(TRUE)) { EMSG(_(e_noperl)); vim_free(script); return; } #endif perl_init(); } { dSP; ENTER; SAVETMPS; if (script == NULL) sv = newSVpv((char *)eap->arg, 0); else { sv = newSVpv(script, 0); vim_free(script); } #ifdef HAVE_SANDBOX if (sandbox) { safe = perl_get_sv("VIM::safe", FALSE); # ifndef MAKE_TEST /* avoid a warning for unreachable code */ if (safe == NULL || !SvTRUE(safe)) EMSG(_("E299: Perl evaluation forbidden in sandbox without the Safe module")); else # endif { PUSHMARK(SP); XPUSHs(safe); XPUSHs(sv); PUTBACK; perl_call_method("reval", G_DISCARD); } } else #endif perl_eval_sv(sv, G_DISCARD | G_NOARGS); SvREFCNT_dec(sv); err = SvPV(GvSV(PL_errgv), length); FREETMPS; LEAVE; if (!length) return; msg_split((char_u *)err, highlight_attr[HLF_E]); return; } } static int replace_line(line, end) linenr_T *line, *end; { char *str; if (SvOK(GvSV(PL_defgv))) { str = SvPV(GvSV(PL_defgv), PL_na); ml_replace(*line, (char_u *)str, 1); changed_bytes(*line, 0); } else { ml_delete(*line, FALSE); deleted_lines_mark(*line, 1L); --(*end); --(*line); } return OK; } /* * ":perldo". */ void ex_perldo(eap) exarg_T *eap; { STRLEN length; SV *sv; char *str; linenr_T i; if (bufempty()) return; if (perl_interp == NULL) { #ifdef DYNAMIC_PERL if (!perl_enabled(TRUE)) { EMSG(_(e_noperl)); return; } #endif perl_init(); } { dSP; length = strlen((char *)eap->arg); sv = newSV(length + sizeof("sub VIM::perldo {") - 1 + 1); sv_setpvn(sv, "sub VIM::perldo {", sizeof("sub VIM::perldo {") - 1); sv_catpvn(sv, (char *)eap->arg, length); sv_catpvn(sv, "}", 1); perl_eval_sv(sv, G_DISCARD | G_NOARGS); SvREFCNT_dec(sv); str = SvPV(GvSV(PL_errgv), length); if (length) goto err; if (u_save(eap->line1 - 1, eap->line2 + 1) != OK) return; ENTER; SAVETMPS; for (i = eap->line1; i <= eap->line2; i++) { sv_setpv(GvSV(PL_defgv), (char *)ml_get(i)); PUSHMARK(sp); perl_call_pv("VIM::perldo", G_SCALAR | G_EVAL); str = SvPV(GvSV(PL_errgv), length); if (length) break; SPAGAIN; if (SvTRUEx(POPs)) { if (replace_line(&i, &eap->line2) != OK) { PUTBACK; break; } } PUTBACK; } FREETMPS; LEAVE; check_cursor(); update_screen(NOT_VALID); if (!length) return; err: msg_split((char_u *)str, highlight_attr[HLF_E]); return; } } #ifndef FEAT_WINDOWS int win_valid(win_T *w) { return TRUE; } int win_count() { return 1; } win_T *win_find_nr(int n) { return curwin; } #endif XS(boot_VIM); static void xs_init(pTHX) { char *file = __FILE__; /* DynaLoader is a special case */ newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file); newXS("VIM::bootstrap", boot_VIM, file); } typedef win_T * VIWIN; typedef buf_T * VIBUF; MODULE = VIM PACKAGE = VIM void Msg(text, hl=NULL) char *text; char *hl; PREINIT: int attr; int id; PPCODE: if (text != NULL) { attr = 0; if (hl != NULL) { id = syn_name2id((char_u *)hl); if (id != 0) attr = syn_id2attr(id); } msg_split((char_u *)text, attr); } void SetOption(line) char *line; PPCODE: if (line != NULL) do_set((char_u *)line, 0); update_screen(NOT_VALID); void DoCommand(line) char *line; PPCODE: if (line != NULL) do_cmdline_cmd((char_u *)line); void Eval(str) char *str; PREINIT: char_u *value; PPCODE: value = eval_to_string((char_u *)str, (char_u **)0, TRUE); if (value == NULL) { XPUSHs(sv_2mortal(newSViv(0))); XPUSHs(sv_2mortal(newSVpv("", 0))); } else { XPUSHs(sv_2mortal(newSViv(1))); XPUSHs(sv_2mortal(newSVpv((char *)value, 0))); vim_free(value); } void Buffers(...) PREINIT: buf_T *vimbuf; int i, b; PPCODE: if (items == 0) { if (GIMME == G_SCALAR) { i = 0; for (vimbuf = firstbuf; vimbuf; vimbuf = vimbuf->b_next) ++i; XPUSHs(sv_2mortal(newSViv(i))); } else { for (vimbuf = firstbuf; vimbuf; vimbuf = vimbuf->b_next) XPUSHs(newBUFrv(newSV(0), vimbuf)); } } else { for (i = 0; i < items; i++) { SV *sv = ST(i); if (SvIOK(sv)) b = SvIV(ST(i)); else { char_u *pat; STRLEN len; pat = (char_u *)SvPV(sv, len); ++emsg_off; b = buflist_findpat(pat, pat+len, FALSE, FALSE); --emsg_off; } if (b >= 0) { vimbuf = buflist_findnr(b); if (vimbuf) XPUSHs(newBUFrv(newSV(0), vimbuf)); } } } void Windows(...) PREINIT: win_T *vimwin; int i, w; PPCODE: if (items == 0) { if (GIMME == G_SCALAR) XPUSHs(sv_2mortal(newSViv(win_count()))); else { for (vimwin = firstwin; vimwin != NULL; vimwin = W_NEXT(vimwin)) XPUSHs(newWINrv(newSV(0), vimwin)); } } else { for (i = 0; i < items; i++) { w = SvIV(ST(i)); vimwin = win_find_nr(w); if (vimwin) XPUSHs(newWINrv(newSV(0), vimwin)); } } MODULE = VIM PACKAGE = VIWIN void DESTROY(win) VIWIN win CODE: if (win_valid(win)) win->w_perl_private = 0; SV * Buffer(win) VIWIN win CODE: if (!win_valid(win)) win = curwin; RETVAL = newBUFrv(newSV(0), win->w_buffer); OUTPUT: RETVAL void SetHeight(win, height) VIWIN win int height; PREINIT: win_T *savewin; PPCODE: if (!win_valid(win)) win = curwin; savewin = curwin; curwin = win; win_setheight(height); curwin = savewin; void Cursor(win, ...) VIWIN win PPCODE: if (items == 1) { EXTEND(sp, 2); if (!win_valid(win)) win = curwin; PUSHs(sv_2mortal(newSViv(win->w_cursor.lnum))); PUSHs(sv_2mortal(newSViv(win->w_cursor.col))); } else if (items == 3) { int lnum, col; if (!win_valid(win)) win = curwin; lnum = SvIV(ST(1)); col = SvIV(ST(2)); win->w_cursor.lnum = lnum; win->w_cursor.col = col; check_cursor(); /* put cursor on an existing line */ update_screen(NOT_VALID); } MODULE = VIM PACKAGE = VIBUF void DESTROY(vimbuf) VIBUF vimbuf; CODE: if (buf_valid(vimbuf)) vimbuf->b_perl_private = 0; void Name(vimbuf) VIBUF vimbuf; PPCODE: if (!buf_valid(vimbuf)) vimbuf = curbuf; /* No file name returns an empty string */ if (vimbuf->b_fname == NULL) XPUSHs(sv_2mortal(newSVpv("", 0))); else XPUSHs(sv_2mortal(newSVpv((char *)vimbuf->b_fname, 0))); void Number(vimbuf) VIBUF vimbuf; PPCODE: if (!buf_valid(vimbuf)) vimbuf = curbuf; XPUSHs(sv_2mortal(newSViv(vimbuf->b_fnum))); void Count(vimbuf) VIBUF vimbuf; PPCODE: if (!buf_valid(vimbuf)) vimbuf = curbuf; XPUSHs(sv_2mortal(newSViv(vimbuf->b_ml.ml_line_count))); void Get(vimbuf, ...) VIBUF vimbuf; PREINIT: char_u *line; int i; long lnum; PPCODE: if (buf_valid(vimbuf)) { for (i = 1; i < items; i++) { lnum = SvIV(ST(i)); if (lnum > 0 && lnum <= vimbuf->b_ml.ml_line_count) { line = ml_get_buf(vimbuf, lnum, FALSE); XPUSHs(sv_2mortal(newSVpv((char *)line, 0))); } } } void Set(vimbuf, ...) VIBUF vimbuf; PREINIT: int i; long lnum; char *line; PPCODE: if (buf_valid(vimbuf)) { if (items < 3) croak("Usage: VIBUF::Set(vimbuf, lnum, @lines)"); lnum = SvIV(ST(1)); for(i = 2; i < items; i++, lnum++) { line = SvPV(ST(i),PL_na); if (lnum > 0 && lnum <= vimbuf->b_ml.ml_line_count && line != NULL) { aco_save_T aco; /* set curwin/curbuf for "vimbuf" and save some things */ aucmd_prepbuf(&aco, vimbuf); if (u_savesub(lnum) == OK) { ml_replace(lnum, (char_u *)line, TRUE); changed_bytes(lnum, 0); } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); /* Careful: autocommands may have made "vimbuf" invalid! */ } } } void Delete(vimbuf, ...) VIBUF vimbuf; PREINIT: long i, lnum = 0, count = 0; PPCODE: if (buf_valid(vimbuf)) { if (items == 2) { lnum = SvIV(ST(1)); count = 1; } else if (items == 3) { lnum = SvIV(ST(1)); count = 1 + SvIV(ST(2)) - lnum; if (count == 0) count = 1; if (count < 0) { lnum -= count; count = -count; } } if (items >= 2) { for (i = 0; i < count; i++) { if (lnum > 0 && lnum <= vimbuf->b_ml.ml_line_count) { aco_save_T aco; /* set curwin/curbuf for "vimbuf" and save some things */ aucmd_prepbuf(&aco, vimbuf); if (u_savedel(lnum, 1) == OK) { ml_delete(lnum, 0); check_cursor(); deleted_lines_mark(lnum, 1L); } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); /* Careful: autocommands may have made "vimbuf" invalid! */ update_curbuf(VALID); } } } } void Append(vimbuf, ...) VIBUF vimbuf; PREINIT: int i; long lnum; char *line; PPCODE: if (buf_valid(vimbuf)) { if (items < 3) croak("Usage: VIBUF::Append(vimbuf, lnum, @lines)"); lnum = SvIV(ST(1)); for (i = 2; i < items; i++, lnum++) { line = SvPV(ST(i),PL_na); if (lnum >= 0 && lnum <= vimbuf->b_ml.ml_line_count && line != NULL) { aco_save_T aco; /* set curwin/curbuf for "vimbuf" and save some things */ aucmd_prepbuf(&aco, vimbuf); if (u_inssub(lnum + 1) == OK) { ml_append(lnum, (char_u *)line, (colnr_T)0, FALSE); appended_lines_mark(lnum, 1L); } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); /* Careful: autocommands may have made "vimbuf" invalid! */ update_curbuf(VALID); } } }
zyz2011-vim
src/if_perl.xs
XS
gpl2
34,305
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* for debugging */ /* #define CHECK(c, s) if (c) EMSG(s) */ #define CHECK(c, s) /* * memline.c: Contains the functions for appending, deleting and changing the * text lines. The memfile functions are used to store the information in * blocks of memory, backed up by a file. The structure of the information is * a tree. The root of the tree is a pointer block. The leaves of the tree * are data blocks. In between may be several layers of pointer blocks, * forming branches. * * Three types of blocks are used: * - Block nr 0 contains information for recovery * - Pointer blocks contain list of pointers to other blocks. * - Data blocks contain the actual text. * * Block nr 0 contains the block0 structure (see below). * * Block nr 1 is the first pointer block. It is the root of the tree. * Other pointer blocks are branches. * * If a line is too big to fit in a single page, the block containing that * line is made big enough to hold the line. It may span several pages. * Otherwise all blocks are one page. * * A data block that was filled when starting to edit a file and was not * changed since then, can have a negative block number. This means that it * has not yet been assigned a place in the file. When recovering, the lines * in this data block can be read from the original file. When the block is * changed (lines appended/deleted/changed) or when it is flushed it gets a * positive number. Use mf_trans_del() to get the new number, before calling * mf_get(). */ #include "vim.h" #ifndef UNIX /* it's in os_unix.h for Unix */ # include <time.h> #endif #if defined(SASC) || defined(__amigaos4__) # include <proto/dos.h> /* for Open() and Close() */ #endif typedef struct block0 ZERO_BL; /* contents of the first block */ typedef struct pointer_block PTR_BL; /* contents of a pointer block */ typedef struct data_block DATA_BL; /* contents of a data block */ typedef struct pointer_entry PTR_EN; /* block/line-count pair */ #define DATA_ID (('d' << 8) + 'a') /* data block id */ #define PTR_ID (('p' << 8) + 't') /* pointer block id */ #define BLOCK0_ID0 'b' /* block 0 id 0 */ #define BLOCK0_ID1 '0' /* block 0 id 1 */ #define BLOCK0_ID1_C0 'c' /* block 0 id 1 'cm' 0 */ #define BLOCK0_ID1_C1 'C' /* block 0 id 1 'cm' 1 */ /* * pointer to a block, used in a pointer block */ struct pointer_entry { blocknr_T pe_bnum; /* block number */ linenr_T pe_line_count; /* number of lines in this branch */ linenr_T pe_old_lnum; /* lnum for this block (for recovery) */ int pe_page_count; /* number of pages in block pe_bnum */ }; /* * A pointer block contains a list of branches in the tree. */ struct pointer_block { short_u pb_id; /* ID for pointer block: PTR_ID */ short_u pb_count; /* number of pointers in this block */ short_u pb_count_max; /* maximum value for pb_count */ PTR_EN pb_pointer[1]; /* list of pointers to blocks (actually longer) * followed by empty space until end of page */ }; /* * A data block is a leaf in the tree. * * The text of the lines is at the end of the block. The text of the first line * in the block is put at the end, the text of the second line in front of it, * etc. Thus the order of the lines is the opposite of the line number. */ struct data_block { short_u db_id; /* ID for data block: DATA_ID */ unsigned db_free; /* free space available */ unsigned db_txt_start; /* byte where text starts */ unsigned db_txt_end; /* byte just after data block */ linenr_T db_line_count; /* number of lines in this block */ unsigned db_index[1]; /* index for start of line (actually bigger) * followed by empty space upto db_txt_start * followed by the text in the lines until * end of page */ }; /* * The low bits of db_index hold the actual index. The topmost bit is * used for the global command to be able to mark a line. * This method is not clean, but otherwise there would be at least one extra * byte used for each line. * The mark has to be in this place to keep it with the correct line when other * lines are inserted or deleted. */ #define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1)) #define DB_INDEX_MASK (~DB_MARKED) #define INDEX_SIZE (sizeof(unsigned)) /* size of one db_index entry */ #define HEADER_SIZE (sizeof(DATA_BL) - INDEX_SIZE) /* size of data block header */ #define B0_FNAME_SIZE_ORG 900 /* what it was in older versions */ #define B0_FNAME_SIZE_NOCRYPT 898 /* 2 bytes used for other things */ #define B0_FNAME_SIZE_CRYPT 890 /* 10 bytes used for other things */ #define B0_UNAME_SIZE 40 #define B0_HNAME_SIZE 40 /* * Restrict the numbers to 32 bits, otherwise most compilers will complain. * This won't detect a 64 bit machine that only swaps a byte in the top 32 * bits, but that is crazy anyway. */ #define B0_MAGIC_LONG 0x30313233L #define B0_MAGIC_INT 0x20212223L #define B0_MAGIC_SHORT 0x10111213L #define B0_MAGIC_CHAR 0x55 /* * Block zero holds all info about the swap file. * * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing * swap files unusable! * * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!! * * This block is built up of single bytes, to make it portable across * different machines. b0_magic_* is used to check the byte order and size of * variables, because the rest of the swap file is not portable. */ struct block0 { char_u b0_id[2]; /* id for block 0: BLOCK0_ID0 and BLOCK0_ID1, * BLOCK0_ID1_C0, BLOCK0_ID1_C1 */ char_u b0_version[10]; /* Vim version string */ char_u b0_page_size[4];/* number of bytes per page */ char_u b0_mtime[4]; /* last modification time of file */ char_u b0_ino[4]; /* inode of b0_fname */ char_u b0_pid[4]; /* process id of creator (or 0) */ char_u b0_uname[B0_UNAME_SIZE]; /* name of user (uid if no name) */ char_u b0_hname[B0_HNAME_SIZE]; /* host name (if it has a name) */ char_u b0_fname[B0_FNAME_SIZE_ORG]; /* name of file being edited */ long b0_magic_long; /* check for byte order of long */ int b0_magic_int; /* check for byte order of int */ short b0_magic_short; /* check for byte order of short */ char_u b0_magic_char; /* check for last char */ }; /* * Note: b0_dirty and b0_flags are put at the end of the file name. For very * long file names in older versions of Vim they are invalid. * The 'fileencoding' comes before b0_flags, with a NUL in front. But only * when there is room, for very long file names it's omitted. */ #define B0_DIRTY 0x55 #define b0_dirty b0_fname[B0_FNAME_SIZE_ORG - 1] /* * The b0_flags field is new in Vim 7.0. */ #define b0_flags b0_fname[B0_FNAME_SIZE_ORG - 2] /* * Crypt seed goes here, 8 bytes. New in Vim 7.3. * Without encryption these bytes may be used for 'fenc'. */ #define b0_seed b0_fname[B0_FNAME_SIZE_ORG - 2 - MF_SEED_LEN] /* The lowest two bits contain the fileformat. Zero means it's not set * (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or * EOL_MAC + 1. */ #define B0_FF_MASK 3 /* Swap file is in directory of edited file. Used to find the file from * different mount points. */ #define B0_SAME_DIR 4 /* The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it. * When empty there is only the NUL. */ #define B0_HAS_FENC 8 #define STACK_INCR 5 /* nr of entries added to ml_stack at a time */ /* * The line number where the first mark may be is remembered. * If it is 0 there are no marks at all. * (always used for the current buffer only, no buffer change possible while * executing a global command). */ static linenr_T lowest_marked = 0; /* * arguments for ml_find_line() */ #define ML_DELETE 0x11 /* delete line */ #define ML_INSERT 0x12 /* insert line */ #define ML_FIND 0x13 /* just find the line */ #define ML_FLUSH 0x02 /* flush locked block */ #define ML_SIMPLE(x) (x & 0x10) /* DEL, INS or FIND */ /* argument for ml_upd_block0() */ typedef enum { UB_FNAME = 0 /* update timestamp and filename */ , UB_SAME_DIR /* update the B0_SAME_DIR flag */ , UB_CRYPT /* update crypt key */ } upd_block0_T; #ifdef FEAT_CRYPT static void ml_set_b0_crypt __ARGS((buf_T *buf, ZERO_BL *b0p)); #endif static int ml_check_b0_id __ARGS((ZERO_BL *b0p)); static void ml_upd_block0 __ARGS((buf_T *buf, upd_block0_T what)); static void set_b0_fname __ARGS((ZERO_BL *, buf_T *buf)); static void set_b0_dir_flag __ARGS((ZERO_BL *b0p, buf_T *buf)); #ifdef FEAT_MBYTE static void add_b0_fenc __ARGS((ZERO_BL *b0p, buf_T *buf)); #endif static time_t swapfile_info __ARGS((char_u *)); static int recov_file_names __ARGS((char_u **, char_u *, int prepend_dot)); static int ml_append_int __ARGS((buf_T *, linenr_T, char_u *, colnr_T, int, int)); static int ml_delete_int __ARGS((buf_T *, linenr_T, int)); static char_u *findswapname __ARGS((buf_T *, char_u **, char_u *)); static void ml_flush_line __ARGS((buf_T *)); static bhdr_T *ml_new_data __ARGS((memfile_T *, int, int)); static bhdr_T *ml_new_ptr __ARGS((memfile_T *)); static bhdr_T *ml_find_line __ARGS((buf_T *, linenr_T, int)); static int ml_add_stack __ARGS((buf_T *)); static void ml_lineadd __ARGS((buf_T *, int)); static int b0_magic_wrong __ARGS((ZERO_BL *)); #ifdef CHECK_INODE static int fnamecmp_ino __ARGS((char_u *, char_u *, long)); #endif static void long_to_char __ARGS((long, char_u *)); static long char_to_long __ARGS((char_u *)); #if defined(UNIX) || defined(WIN3264) static char_u *make_percent_swname __ARGS((char_u *dir, char_u *name)); #endif #ifdef FEAT_CRYPT static void ml_crypt_prepare __ARGS((memfile_T *mfp, off_t offset, int reading)); #endif #ifdef FEAT_BYTEOFF static void ml_updatechunk __ARGS((buf_T *buf, long line, long len, int updtype)); #endif /* * Open a new memline for "buf". * * Return FAIL for failure, OK otherwise. */ int ml_open(buf) buf_T *buf; { memfile_T *mfp; bhdr_T *hp = NULL; ZERO_BL *b0p; PTR_BL *pp; DATA_BL *dp; /* * init fields in memline struct */ buf->b_ml.ml_stack_size = 0; /* no stack yet */ buf->b_ml.ml_stack = NULL; /* no stack yet */ buf->b_ml.ml_stack_top = 0; /* nothing in the stack */ buf->b_ml.ml_locked = NULL; /* no cached block */ buf->b_ml.ml_line_lnum = 0; /* no cached line */ #ifdef FEAT_BYTEOFF buf->b_ml.ml_chunksize = NULL; #endif /* * When 'updatecount' is non-zero swap file may be opened later. */ if (p_uc && buf->b_p_swf) buf->b_may_swap = TRUE; else buf->b_may_swap = FALSE; /* * Open the memfile. No swap file is created yet. */ mfp = mf_open(NULL, 0); if (mfp == NULL) goto error; buf->b_ml.ml_mfp = mfp; #ifdef FEAT_CRYPT mfp->mf_buffer = buf; #endif buf->b_ml.ml_flags = ML_EMPTY; buf->b_ml.ml_line_count = 1; #ifdef FEAT_LINEBREAK curwin->w_nrwidth_line_count = 0; #endif #if defined(MSDOS) && !defined(DJGPP) /* for 16 bit MS-DOS create a swapfile now, because we run out of * memory very quickly */ if (p_uc != 0) ml_open_file(buf); #endif /* * fill block0 struct and write page 0 */ if ((hp = mf_new(mfp, FALSE, 1)) == NULL) goto error; if (hp->bh_bnum != 0) { EMSG(_("E298: Didn't get block nr 0?")); goto error; } b0p = (ZERO_BL *)(hp->bh_data); b0p->b0_id[0] = BLOCK0_ID0; b0p->b0_id[1] = BLOCK0_ID1; b0p->b0_magic_long = (long)B0_MAGIC_LONG; b0p->b0_magic_int = (int)B0_MAGIC_INT; b0p->b0_magic_short = (short)B0_MAGIC_SHORT; b0p->b0_magic_char = B0_MAGIC_CHAR; STRNCPY(b0p->b0_version, "VIM ", 4); STRNCPY(b0p->b0_version + 4, Version, 6); long_to_char((long)mfp->mf_page_size, b0p->b0_page_size); #ifdef FEAT_SPELL if (!buf->b_spell) #endif { b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0; b0p->b0_flags = get_fileformat(buf) + 1; set_b0_fname(b0p, buf); (void)get_user_name(b0p->b0_uname, B0_UNAME_SIZE); b0p->b0_uname[B0_UNAME_SIZE - 1] = NUL; mch_get_host_name(b0p->b0_hname, B0_HNAME_SIZE); b0p->b0_hname[B0_HNAME_SIZE - 1] = NUL; long_to_char(mch_get_pid(), b0p->b0_pid); #ifdef FEAT_CRYPT if (*buf->b_p_key != NUL) ml_set_b0_crypt(buf, b0p); #endif } /* * Always sync block number 0 to disk, so we can check the file name in * the swap file in findswapname(). Don't do this for a help files or * a spell buffer though. * Only works when there's a swapfile, otherwise it's done when the file * is created. */ mf_put(mfp, hp, TRUE, FALSE); if (!buf->b_help && !B_SPELL(buf)) (void)mf_sync(mfp, 0); /* * Fill in root pointer block and write page 1. */ if ((hp = ml_new_ptr(mfp)) == NULL) goto error; if (hp->bh_bnum != 1) { EMSG(_("E298: Didn't get block nr 1?")); goto error; } pp = (PTR_BL *)(hp->bh_data); pp->pb_count = 1; pp->pb_pointer[0].pe_bnum = 2; pp->pb_pointer[0].pe_page_count = 1; pp->pb_pointer[0].pe_old_lnum = 1; pp->pb_pointer[0].pe_line_count = 1; /* line count after insertion */ mf_put(mfp, hp, TRUE, FALSE); /* * Allocate first data block and create an empty line 1. */ if ((hp = ml_new_data(mfp, FALSE, 1)) == NULL) goto error; if (hp->bh_bnum != 2) { EMSG(_("E298: Didn't get block nr 2?")); goto error; } dp = (DATA_BL *)(hp->bh_data); dp->db_index[0] = --dp->db_txt_start; /* at end of block */ dp->db_free -= 1 + INDEX_SIZE; dp->db_line_count = 1; *((char_u *)dp + dp->db_txt_start) = NUL; /* empty line */ return OK; error: if (mfp != NULL) { if (hp) mf_put(mfp, hp, FALSE, FALSE); mf_close(mfp, TRUE); /* will also free(mfp->mf_fname) */ } buf->b_ml.ml_mfp = NULL; return FAIL; } #if defined(FEAT_CRYPT) || defined(PROTO) /* * Prepare encryption for "buf" with block 0 "b0p". */ static void ml_set_b0_crypt(buf, b0p) buf_T *buf; ZERO_BL *b0p; { if (*buf->b_p_key == NUL) b0p->b0_id[1] = BLOCK0_ID1; else { if (get_crypt_method(buf) == 0) b0p->b0_id[1] = BLOCK0_ID1_C0; else { b0p->b0_id[1] = BLOCK0_ID1_C1; /* Generate a seed and store it in block 0 and in the memfile. */ sha2_seed(&b0p->b0_seed, MF_SEED_LEN, NULL, 0); mch_memmove(buf->b_ml.ml_mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN); } } } /* * Called after the crypt key or 'cryptmethod' was changed for "buf". * Will apply this to the swapfile. * "old_key" is the previous key. It is equal to buf->b_p_key when * 'cryptmethod' is changed. * "old_cm" is the previous 'cryptmethod'. It is equal to the current * 'cryptmethod' when 'key' is changed. */ void ml_set_crypt_key(buf, old_key, old_cm) buf_T *buf; char_u *old_key; int old_cm; { memfile_T *mfp = buf->b_ml.ml_mfp; bhdr_T *hp; int page_count; int idx; long error; infoptr_T *ip; PTR_BL *pp; DATA_BL *dp; blocknr_T bnum; int top; if (mfp == NULL) return; /* no memfile yet, nothing to do */ /* Set the key, method and seed to be used for reading, these must be the * old values. */ mfp->mf_old_key = old_key; mfp->mf_old_cm = old_cm; if (old_cm > 0) mch_memmove(mfp->mf_old_seed, mfp->mf_seed, MF_SEED_LEN); /* Update block 0 with the crypt flag and may set a new seed. */ ml_upd_block0(buf, UB_CRYPT); if (mfp->mf_infile_count > 2) { /* * Need to read back all data blocks from disk, decrypt them with the * old key/method and mark them to be written. The algorithm is * similar to what happens in ml_recover(), but we skip negative block * numbers. */ ml_flush_line(buf); /* flush buffered line */ (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */ hp = NULL; bnum = 1; /* start with block 1 */ page_count = 1; /* which is 1 page */ idx = 0; /* start with first index in block 1 */ error = 0; buf->b_ml.ml_stack_top = 0; vim_free(buf->b_ml.ml_stack); buf->b_ml.ml_stack = NULL; buf->b_ml.ml_stack_size = 0; /* no stack yet */ for ( ; !got_int; line_breakcheck()) { if (hp != NULL) mf_put(mfp, hp, FALSE, FALSE); /* release previous block */ /* get the block (pointer or data) */ if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL) { if (bnum == 1) break; ++error; } else { pp = (PTR_BL *)(hp->bh_data); if (pp->pb_id == PTR_ID) /* it is a pointer block */ { if (pp->pb_count == 0) { /* empty block? */ ++error; } else if (idx < (int)pp->pb_count) /* go a block deeper */ { if (pp->pb_pointer[idx].pe_bnum < 0) { /* Skip data block with negative block number. */ ++idx; /* get same block again for next index */ continue; } /* going one block deeper in the tree, new entry in * stack */ if ((top = ml_add_stack(buf)) < 0) { ++error; break; /* out of memory */ } ip = &(buf->b_ml.ml_stack[top]); ip->ip_bnum = bnum; ip->ip_index = idx; bnum = pp->pb_pointer[idx].pe_bnum; page_count = pp->pb_pointer[idx].pe_page_count; continue; } } else /* not a pointer block */ { dp = (DATA_BL *)(hp->bh_data); if (dp->db_id != DATA_ID) /* block id wrong */ ++error; else { /* It is a data block, need to write it back to disk. */ mf_put(mfp, hp, TRUE, FALSE); hp = NULL; } } } if (buf->b_ml.ml_stack_top == 0) /* finished */ break; /* go one block up in the tree */ ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]); bnum = ip->ip_bnum; idx = ip->ip_index + 1; /* go to next index */ page_count = 1; } if (error > 0) EMSG(_("E843: Error while updating swap file crypt")); } mfp->mf_old_key = NULL; } #endif /* * ml_setname() is called when the file name of "buf" has been changed. * It may rename the swap file. */ void ml_setname(buf) buf_T *buf; { int success = FALSE; memfile_T *mfp; char_u *fname; char_u *dirp; #if defined(MSDOS) || defined(MSWIN) char_u *p; #endif mfp = buf->b_ml.ml_mfp; if (mfp->mf_fd < 0) /* there is no swap file yet */ { /* * When 'updatecount' is 0 and 'noswapfile' there is no swap file. * For help files we will make a swap file now. */ if (p_uc != 0) ml_open_file(buf); /* create a swap file */ return; } /* * Try all directories in the 'directory' option. */ dirp = p_dir; for (;;) { if (*dirp == NUL) /* tried all directories, fail */ break; fname = findswapname(buf, &dirp, mfp->mf_fname); /* alloc's fname */ if (dirp == NULL) /* out of memory */ break; if (fname == NULL) /* no file name found for this dir */ continue; #if defined(MSDOS) || defined(MSWIN) /* * Set full pathname for swap file now, because a ":!cd dir" may * change directory without us knowing it. */ p = FullName_save(fname, FALSE); vim_free(fname); fname = p; if (fname == NULL) continue; #endif /* if the file name is the same we don't have to do anything */ if (fnamecmp(fname, mfp->mf_fname) == 0) { vim_free(fname); success = TRUE; break; } /* need to close the swap file before renaming */ if (mfp->mf_fd >= 0) { close(mfp->mf_fd); mfp->mf_fd = -1; } /* try to rename the swap file */ if (vim_rename(mfp->mf_fname, fname) == 0) { success = TRUE; vim_free(mfp->mf_fname); mfp->mf_fname = fname; vim_free(mfp->mf_ffname); #if defined(MSDOS) || defined(MSWIN) mfp->mf_ffname = NULL; /* mf_fname is full pathname already */ #else mf_set_ffname(mfp); #endif ml_upd_block0(buf, UB_SAME_DIR); break; } vim_free(fname); /* this fname didn't work, try another */ } if (mfp->mf_fd == -1) /* need to (re)open the swap file */ { mfp->mf_fd = mch_open((char *)mfp->mf_fname, O_RDWR | O_EXTRA, 0); if (mfp->mf_fd < 0) { /* could not (re)open the swap file, what can we do???? */ EMSG(_("E301: Oops, lost the swap file!!!")); return; } #ifdef HAVE_FD_CLOEXEC { int fdflags = fcntl(mfp->mf_fd, F_GETFD); if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0) fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC); } #endif } if (!success) EMSG(_("E302: Could not rename swap file")); } /* * Open a file for the memfile for all buffers that are not readonly or have * been modified. * Used when 'updatecount' changes from zero to non-zero. */ void ml_open_files() { buf_T *buf; for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (!buf->b_p_ro || buf->b_changed) ml_open_file(buf); } /* * Open a swap file for an existing memfile, if there is no swap file yet. * If we are unable to find a file name, mf_fname will be NULL * and the memfile will be in memory only (no recovery possible). */ void ml_open_file(buf) buf_T *buf; { memfile_T *mfp; char_u *fname; char_u *dirp; mfp = buf->b_ml.ml_mfp; if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf) return; /* nothing to do */ #ifdef FEAT_SPELL /* For a spell buffer use a temp file name. */ if (buf->b_spell) { fname = vim_tempname('s'); if (fname != NULL) (void)mf_open_file(mfp, fname); /* consumes fname! */ buf->b_may_swap = FALSE; return; } #endif /* * Try all directories in 'directory' option. */ dirp = p_dir; for (;;) { if (*dirp == NUL) break; /* There is a small chance that between choosing the swap file name * and creating it, another Vim creates the file. In that case the * creation will fail and we will use another directory. */ fname = findswapname(buf, &dirp, NULL); /* allocates fname */ if (dirp == NULL) break; /* out of memory */ if (fname == NULL) continue; if (mf_open_file(mfp, fname) == OK) /* consumes fname! */ { #if defined(MSDOS) || defined(MSWIN) /* * set full pathname for swap file now, because a ":!cd dir" may * change directory without us knowing it. */ mf_fullname(mfp); #endif ml_upd_block0(buf, UB_SAME_DIR); /* Flush block zero, so others can read it */ if (mf_sync(mfp, MFS_ZERO) == OK) { /* Mark all blocks that should be in the swapfile as dirty. * Needed for when the 'swapfile' option was reset, so that * the swap file was deleted, and then on again. */ mf_set_dirty(mfp); break; } /* Writing block 0 failed: close the file and try another dir */ mf_close_file(buf, FALSE); } } if (mfp->mf_fname == NULL) /* Failed! */ { need_wait_return = TRUE; /* call wait_return later */ ++no_wait_return; (void)EMSG2(_("E303: Unable to open swap file for \"%s\", recovery impossible"), buf_spname(buf) != NULL ? (char_u *)buf_spname(buf) : buf->b_fname); --no_wait_return; } /* don't try to open a swap file again */ buf->b_may_swap = FALSE; } /* * If still need to create a swap file, and starting to edit a not-readonly * file, or reading into an existing buffer, create a swap file now. */ void check_need_swap(newfile) int newfile; /* reading file into new buffer */ { if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile)) ml_open_file(curbuf); } /* * Close memline for buffer 'buf'. * If 'del_file' is TRUE, delete the swap file */ void ml_close(buf, del_file) buf_T *buf; int del_file; { if (buf->b_ml.ml_mfp == NULL) /* not open */ return; mf_close(buf->b_ml.ml_mfp, del_file); /* close the .swp file */ if (buf->b_ml.ml_line_lnum != 0 && (buf->b_ml.ml_flags & ML_LINE_DIRTY)) vim_free(buf->b_ml.ml_line_ptr); vim_free(buf->b_ml.ml_stack); #ifdef FEAT_BYTEOFF vim_free(buf->b_ml.ml_chunksize); buf->b_ml.ml_chunksize = NULL; #endif buf->b_ml.ml_mfp = NULL; /* Reset the "recovered" flag, give the ATTENTION prompt the next time * this buffer is loaded. */ buf->b_flags &= ~BF_RECOVERED; } /* * Close all existing memlines and memfiles. * Only used when exiting. * When 'del_file' is TRUE, delete the memfiles. * But don't delete files that were ":preserve"d when we are POSIX compatible. */ void ml_close_all(del_file) int del_file; { buf_T *buf; for (buf = firstbuf; buf != NULL; buf = buf->b_next) ml_close(buf, del_file && ((buf->b_flags & BF_PRESERVED) == 0 || vim_strchr(p_cpo, CPO_PRESERVE) == NULL)); #ifdef TEMPDIRNAMES vim_deltempdir(); /* delete created temp directory */ #endif } /* * Close all memfiles for not modified buffers. * Only use just before exiting! */ void ml_close_notmod() { buf_T *buf; for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (!bufIsChanged(buf)) ml_close(buf, TRUE); /* close all not-modified buffers */ } /* * Update the timestamp in the .swp file. * Used when the file has been written. */ void ml_timestamp(buf) buf_T *buf; { ml_upd_block0(buf, UB_FNAME); } /* * Return FAIL when the ID of "b0p" is wrong. */ static int ml_check_b0_id(b0p) ZERO_BL *b0p; { if (b0p->b0_id[0] != BLOCK0_ID0 || (b0p->b0_id[1] != BLOCK0_ID1 && b0p->b0_id[1] != BLOCK0_ID1_C0 && b0p->b0_id[1] != BLOCK0_ID1_C1) ) return FAIL; return OK; } /* * Update the timestamp or the B0_SAME_DIR flag of the .swp file. */ static void ml_upd_block0(buf, what) buf_T *buf; upd_block0_T what; { memfile_T *mfp; bhdr_T *hp; ZERO_BL *b0p; mfp = buf->b_ml.ml_mfp; if (mfp == NULL || (hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL) return; b0p = (ZERO_BL *)(hp->bh_data); if (ml_check_b0_id(b0p) == FAIL) EMSG(_("E304: ml_upd_block0(): Didn't get block 0??")); else { if (what == UB_FNAME) set_b0_fname(b0p, buf); #ifdef FEAT_CRYPT else if (what == UB_CRYPT) ml_set_b0_crypt(buf, b0p); #endif else /* what == UB_SAME_DIR */ set_b0_dir_flag(b0p, buf); } mf_put(mfp, hp, TRUE, FALSE); } /* * Write file name and timestamp into block 0 of a swap file. * Also set buf->b_mtime. * Don't use NameBuff[]!!! */ static void set_b0_fname(b0p, buf) ZERO_BL *b0p; buf_T *buf; { struct stat st; if (buf->b_ffname == NULL) b0p->b0_fname[0] = NUL; else { #if defined(MSDOS) || defined(MSWIN) || defined(AMIGA) /* Systems that cannot translate "~user" back into a path: copy the * file name unmodified. Do use slashes instead of backslashes for * portability. */ vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1); # ifdef BACKSLASH_IN_FILENAME forward_slash(b0p->b0_fname); # endif #else size_t flen, ulen; char_u uname[B0_UNAME_SIZE]; /* * For a file under the home directory of the current user, we try to * replace the home directory path with "~user". This helps when * editing the same file on different machines over a network. * First replace home dir path with "~/" with home_replace(). * Then insert the user name to get "~user/". */ home_replace(NULL, buf->b_ffname, b0p->b0_fname, B0_FNAME_SIZE_CRYPT, TRUE); if (b0p->b0_fname[0] == '~') { flen = STRLEN(b0p->b0_fname); /* If there is no user name or it is too long, don't use "~/" */ if (get_user_name(uname, B0_UNAME_SIZE) == FAIL || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE_CRYPT - 1) vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1); else { mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen); mch_memmove(b0p->b0_fname + 1, uname, ulen); } } #endif if (mch_stat((char *)buf->b_ffname, &st) >= 0) { long_to_char((long)st.st_mtime, b0p->b0_mtime); #ifdef CHECK_INODE long_to_char((long)st.st_ino, b0p->b0_ino); #endif buf_store_time(buf, &st, buf->b_ffname); buf->b_mtime_read = buf->b_mtime; } else { long_to_char(0L, b0p->b0_mtime); #ifdef CHECK_INODE long_to_char(0L, b0p->b0_ino); #endif buf->b_mtime = 0; buf->b_mtime_read = 0; buf->b_orig_size = 0; buf->b_orig_mode = 0; } } #ifdef FEAT_MBYTE /* Also add the 'fileencoding' if there is room. */ add_b0_fenc(b0p, curbuf); #endif } /* * Update the B0_SAME_DIR flag of the swap file. It's set if the file and the * swapfile for "buf" are in the same directory. * This is fail safe: if we are not sure the directories are equal the flag is * not set. */ static void set_b0_dir_flag(b0p, buf) ZERO_BL *b0p; buf_T *buf; { if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname)) b0p->b0_flags |= B0_SAME_DIR; else b0p->b0_flags &= ~B0_SAME_DIR; } #ifdef FEAT_MBYTE /* * When there is room, add the 'fileencoding' to block zero. */ static void add_b0_fenc(b0p, buf) ZERO_BL *b0p; buf_T *buf; { int n; int size = B0_FNAME_SIZE_NOCRYPT; # ifdef FEAT_CRYPT /* Without encryption use the same offset as in Vim 7.2 to be compatible. * With encryption it's OK to move elsewhere, the swap file is not * compatible anyway. */ if (*buf->b_p_key != NUL) size = B0_FNAME_SIZE_CRYPT; # endif n = (int)STRLEN(buf->b_p_fenc); if ((int)STRLEN(b0p->b0_fname) + n + 1 > size) b0p->b0_flags &= ~B0_HAS_FENC; else { mch_memmove((char *)b0p->b0_fname + size - n, (char *)buf->b_p_fenc, (size_t)n); *(b0p->b0_fname + size - n - 1) = NUL; b0p->b0_flags |= B0_HAS_FENC; } } #endif /* * Try to recover curbuf from the .swp file. */ void ml_recover() { buf_T *buf = NULL; memfile_T *mfp = NULL; char_u *fname; char_u *fname_used = NULL; bhdr_T *hp = NULL; ZERO_BL *b0p; int b0_ff; char_u *b0_fenc = NULL; #ifdef FEAT_CRYPT int b0_cm = -1; #endif PTR_BL *pp; DATA_BL *dp; infoptr_T *ip; blocknr_T bnum; int page_count; struct stat org_stat, swp_stat; int len; int directly; linenr_T lnum; char_u *p; int i; long error; int cannot_open; linenr_T line_count; int has_error; int idx; int top; int txt_start; off_t size; int called_from_main; int serious_error = TRUE; long mtime; int attr; int orig_file_status = NOTDONE; recoverymode = TRUE; called_from_main = (curbuf->b_ml.ml_mfp == NULL); attr = hl_attr(HLF_E); /* * If the file name ends in ".s[uvw][a-z]" we assume this is the swap file. * Otherwise a search is done to find the swap file(s). */ fname = curbuf->b_fname; if (fname == NULL) /* When there is no file name */ fname = (char_u *)""; len = (int)STRLEN(fname); if (len >= 4 && #if defined(VMS) STRNICMP(fname + len - 4, "_s" , 2) #else STRNICMP(fname + len - 4, ".s" , 2) #endif == 0 && vim_strchr((char_u *)"UVWuvw", fname[len - 2]) != NULL && ASCII_ISALPHA(fname[len - 1])) { directly = TRUE; fname_used = vim_strsave(fname); /* make a copy for mf_open() */ } else { directly = FALSE; /* count the number of matching swap files */ len = recover_names(fname, FALSE, 0, NULL); if (len == 0) /* no swap files found */ { EMSG2(_("E305: No swap file found for %s"), fname); goto theend; } if (len == 1) /* one swap file found, use it */ i = 1; else /* several swap files found, choose */ { /* list the names of the swap files */ (void)recover_names(fname, TRUE, 0, NULL); msg_putchar('\n'); MSG_PUTS(_("Enter number of swap file to use (0 to quit): ")); i = get_number(FALSE, NULL); if (i < 1 || i > len) goto theend; } /* get the swap file name that will be used */ (void)recover_names(fname, FALSE, i, &fname_used); } if (fname_used == NULL) goto theend; /* out of memory */ /* When called from main() still need to initialize storage structure */ if (called_from_main && ml_open(curbuf) == FAIL) getout(1); /* * Allocate a buffer structure for the swap file that is used for recovery. * Only the memline and crypt information in it are really used. */ buf = (buf_T *)alloc((unsigned)sizeof(buf_T)); if (buf == NULL) goto theend; /* * init fields in memline struct */ buf->b_ml.ml_stack_size = 0; /* no stack yet */ buf->b_ml.ml_stack = NULL; /* no stack yet */ buf->b_ml.ml_stack_top = 0; /* nothing in the stack */ buf->b_ml.ml_line_lnum = 0; /* no cached line */ buf->b_ml.ml_locked = NULL; /* no locked block */ buf->b_ml.ml_flags = 0; #ifdef FEAT_CRYPT buf->b_p_key = empty_option; buf->b_p_cm = empty_option; #endif /* * open the memfile from the old swap file */ p = vim_strsave(fname_used); /* save "fname_used" for the message: mf_open() will consume "fname_used"! */ mfp = mf_open(fname_used, O_RDONLY); fname_used = p; if (mfp == NULL || mfp->mf_fd < 0) { if (fname_used != NULL) EMSG2(_("E306: Cannot open %s"), fname_used); goto theend; } buf->b_ml.ml_mfp = mfp; #ifdef FEAT_CRYPT mfp->mf_buffer = buf; #endif /* * The page size set in mf_open() might be different from the page size * used in the swap file, we must get it from block 0. But to read block * 0 we need a page size. Use the minimal size for block 0 here, it will * be set to the real value below. */ mfp->mf_page_size = MIN_SWAP_PAGE_SIZE; /* * try to read block 0 */ if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL) { msg_start(); MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST); msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST); MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."), attr | MSG_HIST); msg_end(); goto theend; } b0p = (ZERO_BL *)(hp->bh_data); if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0) { msg_start(); msg_outtrans_attr(mfp->mf_fname, MSG_HIST); MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"), MSG_HIST); MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST); msg_end(); goto theend; } if (ml_check_b0_id(b0p) == FAIL) { EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname); goto theend; } if (b0_magic_wrong(b0p)) { msg_start(); msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST); #if defined(MSDOS) || defined(MSWIN) if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0) MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"), attr | MSG_HIST); else #endif MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"), attr | MSG_HIST); MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST); /* avoid going past the end of a corrupted hostname */ b0p->b0_fname[0] = NUL; MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST); MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST); msg_end(); goto theend; } #ifdef FEAT_CRYPT if (b0p->b0_id[1] == BLOCK0_ID1_C0) b0_cm = 0; else if (b0p->b0_id[1] == BLOCK0_ID1_C1) { b0_cm = 1; mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN); } set_crypt_method(buf, b0_cm); #else if (b0p->b0_id[1] != BLOCK0_ID1) { EMSG2(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname); goto theend; } #endif /* * If we guessed the wrong page size, we have to recalculate the * highest block number in the file. */ if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size)) { unsigned previous_page_size = mfp->mf_page_size; mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size)); if (mfp->mf_page_size < previous_page_size) { msg_start(); msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST); MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"), attr | MSG_HIST); msg_end(); goto theend; } if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0) mfp->mf_blocknr_max = 0; /* no file or empty file */ else mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size); mfp->mf_infile_count = mfp->mf_blocknr_max; /* need to reallocate the memory used to store the data */ p = alloc(mfp->mf_page_size); if (p == NULL) goto theend; mch_memmove(p, hp->bh_data, previous_page_size); vim_free(hp->bh_data); hp->bh_data = p; b0p = (ZERO_BL *)(hp->bh_data); } /* * If .swp file name given directly, use name from swap file for buffer. */ if (directly) { expand_env(b0p->b0_fname, NameBuff, MAXPATHL); if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL) goto theend; } home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE); smsg((char_u *)_("Using swap file \"%s\""), NameBuff); if (buf_spname(curbuf) != NULL) STRCPY(NameBuff, buf_spname(curbuf)); else home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE); smsg((char_u *)_("Original file \"%s\""), NameBuff); msg_putchar('\n'); /* * check date of swap file and original file */ mtime = char_to_long(b0p->b0_mtime); if (curbuf->b_ffname != NULL && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1 && org_stat.st_mtime > swp_stat.st_mtime) || org_stat.st_mtime != mtime)) { EMSG(_("E308: Warning: Original file may have been changed")); } out_flush(); /* Get the 'fileformat' and 'fileencoding' from block zero. */ b0_ff = (b0p->b0_flags & B0_FF_MASK); if (b0p->b0_flags & B0_HAS_FENC) { int fnsize = B0_FNAME_SIZE_NOCRYPT; #ifdef FEAT_CRYPT /* Use the same size as in add_b0_fenc(). */ if (b0p->b0_id[1] != BLOCK0_ID1) fnsize = B0_FNAME_SIZE_CRYPT; #endif for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p) ; b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + fnsize - p)); } mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */ hp = NULL; /* * Now that we are sure that the file is going to be recovered, clear the * contents of the current buffer. */ while (!(curbuf->b_ml.ml_flags & ML_EMPTY)) ml_delete((linenr_T)1, FALSE); /* * Try reading the original file to obtain the values of 'fileformat', * 'fileencoding', etc. Ignore errors. The text itself is not used. * When the file is encrypted the user is asked to enter the key. */ if (curbuf->b_ffname != NULL) orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW); #ifdef FEAT_CRYPT if (b0_cm >= 0) { /* Need to ask the user for the crypt key. If this fails we continue * without a key, will probably get garbage text. */ if (*curbuf->b_p_key != NUL) { smsg((char_u *)_("Swap file is encrypted: \"%s\""), fname_used); MSG_PUTS(_("\nIf you entered a new crypt key but did not write the text file,")); MSG_PUTS(_("\nenter the new crypt key.")); MSG_PUTS(_("\nIf you wrote the text file after changing the crypt key press enter")); MSG_PUTS(_("\nto use the same key for text file and swap file")); } else smsg((char_u *)_(need_key_msg), fname_used); buf->b_p_key = get_crypt_key(FALSE, FALSE); if (buf->b_p_key == NULL) buf->b_p_key = curbuf->b_p_key; else if (*buf->b_p_key == NUL) { vim_free(buf->b_p_key); buf->b_p_key = curbuf->b_p_key; } if (buf->b_p_key == NULL) buf->b_p_key = empty_option; } #endif /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */ if (b0_ff != 0) set_fileformat(b0_ff - 1, OPT_LOCAL); if (b0_fenc != NULL) { set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL); vim_free(b0_fenc); } unchanged(curbuf, TRUE); bnum = 1; /* start with block 1 */ page_count = 1; /* which is 1 page */ lnum = 0; /* append after line 0 in curbuf */ line_count = 0; idx = 0; /* start with first index in block 1 */ error = 0; buf->b_ml.ml_stack_top = 0; buf->b_ml.ml_stack = NULL; buf->b_ml.ml_stack_size = 0; /* no stack yet */ if (curbuf->b_ffname == NULL) cannot_open = TRUE; else cannot_open = FALSE; serious_error = FALSE; for ( ; !got_int; line_breakcheck()) { if (hp != NULL) mf_put(mfp, hp, FALSE, FALSE); /* release previous block */ /* * get block */ if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL) { if (bnum == 1) { EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname); goto theend; } ++error; ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"), (colnr_T)0, TRUE); } else /* there is a block */ { pp = (PTR_BL *)(hp->bh_data); if (pp->pb_id == PTR_ID) /* it is a pointer block */ { /* check line count when using pointer block first time */ if (idx == 0 && line_count != 0) { for (i = 0; i < (int)pp->pb_count; ++i) line_count -= pp->pb_pointer[i].pe_line_count; if (line_count != 0) { ++error; ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"), (colnr_T)0, TRUE); } } if (pp->pb_count == 0) { ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"), (colnr_T)0, TRUE); ++error; } else if (idx < (int)pp->pb_count) /* go a block deeper */ { if (pp->pb_pointer[idx].pe_bnum < 0) { /* * Data block with negative block number. * Try to read lines from the original file. * This is slow, but it works. */ if (!cannot_open) { line_count = pp->pb_pointer[idx].pe_line_count; if (readfile(curbuf->b_ffname, NULL, lnum, pp->pb_pointer[idx].pe_old_lnum - 1, line_count, NULL, 0) == FAIL) cannot_open = TRUE; else lnum += line_count; } if (cannot_open) { ++error; ml_append(lnum++, (char_u *)_("???LINES MISSING"), (colnr_T)0, TRUE); } ++idx; /* get same block again for next index */ continue; } /* * going one block deeper in the tree */ if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */ { ++error; break; /* out of memory */ } ip = &(buf->b_ml.ml_stack[top]); ip->ip_bnum = bnum; ip->ip_index = idx; bnum = pp->pb_pointer[idx].pe_bnum; line_count = pp->pb_pointer[idx].pe_line_count; page_count = pp->pb_pointer[idx].pe_page_count; idx = 0; continue; } } else /* not a pointer block */ { dp = (DATA_BL *)(hp->bh_data); if (dp->db_id != DATA_ID) /* block id wrong */ { if (bnum == 1) { EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"), mfp->mf_fname); goto theend; } ++error; ml_append(lnum++, (char_u *)_("???BLOCK MISSING"), (colnr_T)0, TRUE); } else { /* * it is a data block * Append all the lines in this block */ has_error = FALSE; /* * check length of block * if wrong, use length in pointer block */ if (page_count * mfp->mf_page_size != dp->db_txt_end) { ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"), (colnr_T)0, TRUE); ++error; has_error = TRUE; dp->db_txt_end = page_count * mfp->mf_page_size; } /* make sure there is a NUL at the end of the block */ *((char_u *)dp + dp->db_txt_end - 1) = NUL; /* * check number of lines in block * if wrong, use count in data block */ if (line_count != dp->db_line_count) { ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"), (colnr_T)0, TRUE); ++error; has_error = TRUE; } for (i = 0; i < dp->db_line_count; ++i) { txt_start = (dp->db_index[i] & DB_INDEX_MASK); if (txt_start <= (int)HEADER_SIZE || txt_start >= (int)dp->db_txt_end) { p = (char_u *)"???"; ++error; } else p = (char_u *)dp + txt_start; ml_append(lnum++, p, (colnr_T)0, TRUE); } if (has_error) ml_append(lnum++, (char_u *)_("???END"), (colnr_T)0, TRUE); } } } if (buf->b_ml.ml_stack_top == 0) /* finished */ break; /* * go one block up in the tree */ ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]); bnum = ip->ip_bnum; idx = ip->ip_index + 1; /* go to next index */ page_count = 1; } /* * Compare the buffer contents with the original file. When they differ * set the 'modified' flag. * Lines 1 - lnum are the new contents. * Lines lnum + 1 to ml_line_count are the original contents. * Line ml_line_count + 1 in the dummy empty line. */ if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1) { /* Recovering an empty file results in two lines and the first line is * empty. Don't set the modified flag then. */ if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL)) { changed_int(); ++curbuf->b_changedtick; } } else { for (idx = 1; idx <= lnum; ++idx) { /* Need to copy one line, fetching the other one may flush it. */ p = vim_strsave(ml_get(idx)); i = STRCMP(p, ml_get(idx + lnum)); vim_free(p); if (i != 0) { changed_int(); ++curbuf->b_changedtick; break; } } } /* * Delete the lines from the original file and the dummy line from the * empty buffer. These will now be after the last line in the buffer. */ while (curbuf->b_ml.ml_line_count > lnum && !(curbuf->b_ml.ml_flags & ML_EMPTY)) ml_delete(curbuf->b_ml.ml_line_count, FALSE); curbuf->b_flags |= BF_RECOVERED; recoverymode = FALSE; if (got_int) EMSG(_("E311: Recovery Interrupted")); else if (error) { ++no_wait_return; MSG(">>>>>>>>>>>>>"); EMSG(_("E312: Errors detected while recovering; look for lines starting with ???")); --no_wait_return; MSG(_("See \":help E312\" for more information.")); MSG(">>>>>>>>>>>>>"); } else { if (curbuf->b_changed) { MSG(_("Recovery completed. You should check if everything is OK.")); MSG_PUTS(_("\n(You might want to write out this file under another name\n")); MSG_PUTS(_("and run diff with the original file to check for changes)")); } else MSG(_("Recovery completed. Buffer contents equals file contents.")); MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n")); cmdline_row = msg_row; } #ifdef FEAT_CRYPT if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0) { MSG_PUTS(_("Using crypt key from swap file for the text file.\n")); set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL); } #endif redraw_curbuf_later(NOT_VALID); theend: vim_free(fname_used); recoverymode = FALSE; if (mfp != NULL) { if (hp != NULL) mf_put(mfp, hp, FALSE, FALSE); mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */ } if (buf != NULL) { #ifdef FEAT_CRYPT if (buf->b_p_key != curbuf->b_p_key) free_string_option(buf->b_p_key); free_string_option(buf->b_p_cm); #endif vim_free(buf->b_ml.ml_stack); vim_free(buf); } if (serious_error && called_from_main) ml_close(curbuf, TRUE); #ifdef FEAT_AUTOCMD else { apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf); apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf); } #endif return; } /* * Find the names of swap files in current directory and the directory given * with the 'directory' option. * * Used to: * - list the swap files for "vim -r" * - count the number of swap files when recovering * - list the swap files when recovering * - find the name of the n'th swap file when recovering */ int recover_names(fname, list, nr, fname_out) char_u *fname; /* base for swap file name */ int list; /* when TRUE, list the swap file names */ int nr; /* when non-zero, return nr'th swap file name */ char_u **fname_out; /* result when "nr" > 0 */ { int num_names; char_u *(names[6]); char_u *tail; char_u *p; int num_files; int file_count = 0; char_u **files; int i; char_u *dirp; char_u *dir_name; char_u *fname_res = NULL; #ifdef HAVE_READLINK char_u fname_buf[MAXPATHL]; #endif if (fname != NULL) { #ifdef HAVE_READLINK /* Expand symlink in the file name, because the swap file is created * with the actual file instead of with the symlink. */ if (resolve_symlink(fname, fname_buf) == OK) fname_res = fname_buf; else #endif fname_res = fname; } if (list) { /* use msg() to start the scrolling properly */ msg((char_u *)_("Swap files found:")); msg_putchar('\n'); } /* * Do the loop for every directory in 'directory'. * First allocate some memory to put the directory name in. */ dir_name = alloc((unsigned)STRLEN(p_dir) + 1); dirp = p_dir; while (dir_name != NULL && *dirp) { /* * Isolate a directory name from *dirp and put it in dir_name (we know * it is large enough, so use 31000 for length). * Advance dirp to next directory name. */ (void)copy_option_part(&dirp, dir_name, 31000, ","); if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */ { if (fname == NULL) { #ifdef VMS names[0] = vim_strsave((char_u *)"*_sw%"); #else names[0] = vim_strsave((char_u *)"*.sw?"); #endif #if defined(UNIX) || defined(WIN3264) /* For Unix names starting with a dot are special. MS-Windows * supports this too, on some file systems. */ names[1] = vim_strsave((char_u *)".*.sw?"); names[2] = vim_strsave((char_u *)".sw?"); num_names = 3; #else # ifdef VMS names[1] = vim_strsave((char_u *)".*_sw%"); num_names = 2; # else num_names = 1; # endif #endif } else num_names = recov_file_names(names, fname_res, TRUE); } else /* check directory dir_name */ { if (fname == NULL) { #ifdef VMS names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE); #else names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE); #endif #if defined(UNIX) || defined(WIN3264) /* For Unix names starting with a dot are special. MS-Windows * supports this too, on some file systems. */ names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE); names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE); num_names = 3; #else # ifdef VMS names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE); num_names = 2; # else num_names = 1; # endif #endif } else { #if defined(UNIX) || defined(WIN3264) p = dir_name + STRLEN(dir_name); if (after_pathsep(dir_name, p) && p[-1] == p[-2]) { /* Ends with '//', Use Full path for swap name */ tail = make_percent_swname(dir_name, fname_res); } else #endif { tail = gettail(fname_res); tail = concat_fnames(dir_name, tail, TRUE); } if (tail == NULL) num_names = 0; else { num_names = recov_file_names(names, tail, FALSE); vim_free(tail); } } } /* check for out-of-memory */ for (i = 0; i < num_names; ++i) { if (names[i] == NULL) { for (i = 0; i < num_names; ++i) vim_free(names[i]); num_names = 0; } } if (num_names == 0) num_files = 0; else if (expand_wildcards(num_names, names, &num_files, &files, EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL) num_files = 0; /* * When no swap file found, wildcard expansion might have failed (e.g. * not able to execute the shell). * Try finding a swap file by simply adding ".swp" to the file name. */ if (*dirp == NUL && file_count + num_files == 0 && fname != NULL) { struct stat st; char_u *swapname; swapname = modname(fname_res, #if defined(VMS) (char_u *)"_swp", FALSE #else (char_u *)".swp", TRUE #endif ); if (swapname != NULL) { if (mch_stat((char *)swapname, &st) != -1) /* It exists! */ { files = (char_u **)alloc((unsigned)sizeof(char_u *)); if (files != NULL) { files[0] = swapname; swapname = NULL; num_files = 1; } } vim_free(swapname); } } /* * remove swapfile name of the current buffer, it must be ignored */ if (curbuf->b_ml.ml_mfp != NULL && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL) { for (i = 0; i < num_files; ++i) if (fullpathcmp(p, files[i], TRUE) & FPC_SAME) { /* Remove the name from files[i]. Move further entries * down. When the array becomes empty free it here, since * FreeWild() won't be called below. */ vim_free(files[i]); if (--num_files == 0) vim_free(files); else for ( ; i < num_files; ++i) files[i] = files[i + 1]; } } if (nr > 0) { file_count += num_files; if (nr <= file_count) { *fname_out = vim_strsave( files[nr - 1 + num_files - file_count]); dirp = (char_u *)""; /* stop searching */ } } else if (list) { if (dir_name[0] == '.' && dir_name[1] == NUL) { if (fname == NULL) MSG_PUTS(_(" In current directory:\n")); else MSG_PUTS(_(" Using specified name:\n")); } else { MSG_PUTS(_(" In directory ")); msg_home_replace(dir_name); MSG_PUTS(":\n"); } if (num_files) { for (i = 0; i < num_files; ++i) { /* print the swap file name */ msg_outnum((long)++file_count); MSG_PUTS(". "); msg_puts(gettail(files[i])); msg_putchar('\n'); (void)swapfile_info(files[i]); } } else MSG_PUTS(_(" -- none --\n")); out_flush(); } else file_count += num_files; for (i = 0; i < num_names; ++i) vim_free(names[i]); if (num_files > 0) FreeWild(num_files, files); } vim_free(dir_name); return file_count; } #if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */ /* * Append the full path to name with path separators made into percent * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"") */ static char_u * make_percent_swname(dir, name) char_u *dir; char_u *name; { char_u *d, *s, *f; f = fix_fname(name != NULL ? name : (char_u *) ""); d = NULL; if (f != NULL) { s = alloc((unsigned)(STRLEN(f) + 1)); if (s != NULL) { STRCPY(s, f); for (d = s; *d != NUL; mb_ptr_adv(d)) if (vim_ispathsep(*d)) *d = '%'; d = concat_fnames(dir, s, TRUE); vim_free(s); } vim_free(f); } return d; } #endif #if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)) static int process_still_running; #endif /* * Give information about an existing swap file. * Returns timestamp (0 when unknown). */ static time_t swapfile_info(fname) char_u *fname; { struct stat st; int fd; struct block0 b0; time_t x = (time_t)0; char *p; #ifdef UNIX char_u uname[B0_UNAME_SIZE]; #endif /* print the swap file date */ if (mch_stat((char *)fname, &st) != -1) { #ifdef UNIX /* print name of owner of the file */ if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK) { MSG_PUTS(_(" owned by: ")); msg_outtrans(uname); MSG_PUTS(_(" dated: ")); } else #endif MSG_PUTS(_(" dated: ")); x = st.st_mtime; /* Manx C can't do &st.st_mtime */ p = ctime(&x); /* includes '\n' */ if (p == NULL) MSG_PUTS("(invalid)\n"); else MSG_PUTS(p); } /* * print the original file name */ fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0); if (fd >= 0) { if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0)) { if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0) { MSG_PUTS(_(" [from Vim version 3.0]")); } else if (ml_check_b0_id(&b0) == FAIL) { MSG_PUTS(_(" [does not look like a Vim swap file]")); } else { MSG_PUTS(_(" file name: ")); if (b0.b0_fname[0] == NUL) MSG_PUTS(_("[No Name]")); else msg_outtrans(b0.b0_fname); MSG_PUTS(_("\n modified: ")); MSG_PUTS(b0.b0_dirty ? _("YES") : _("no")); if (*(b0.b0_uname) != NUL) { MSG_PUTS(_("\n user name: ")); msg_outtrans(b0.b0_uname); } if (*(b0.b0_hname) != NUL) { if (*(b0.b0_uname) != NUL) MSG_PUTS(_(" host name: ")); else MSG_PUTS(_("\n host name: ")); msg_outtrans(b0.b0_hname); } if (char_to_long(b0.b0_pid) != 0L) { MSG_PUTS(_("\n process ID: ")); msg_outnum(char_to_long(b0.b0_pid)); #if defined(UNIX) || defined(__EMX__) /* EMX kill() not working correctly, it seems */ if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0) { MSG_PUTS(_(" (still running)")); # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) process_still_running = TRUE; # endif } #endif } if (b0_magic_wrong(&b0)) { #if defined(MSDOS) || defined(MSWIN) if (STRNCMP(b0.b0_hname, "PC ", 3) == 0) MSG_PUTS(_("\n [not usable with this version of Vim]")); else #endif MSG_PUTS(_("\n [not usable on this computer]")); } } } else MSG_PUTS(_(" [cannot be read]")); close(fd); } else MSG_PUTS(_(" [cannot be opened]")); msg_putchar('\n'); return x; } static int recov_file_names(names, path, prepend_dot) char_u **names; char_u *path; int prepend_dot; { int num_names; #ifdef SHORT_FNAME /* * (MS-DOS) always short names */ names[0] = modname(path, (char_u *)".sw?", FALSE); num_names = 1; #else /* !SHORT_FNAME */ /* * (Win32 and Win64) never short names, but do prepend a dot. * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both. * Only use the short name if it is different. */ char_u *p; int i; # ifndef WIN3264 int shortname = curbuf->b_shortname; curbuf->b_shortname = FALSE; # endif num_names = 0; /* * May also add the file name with a dot prepended, for swap file in same * dir as original file. */ if (prepend_dot) { names[num_names] = modname(path, (char_u *)".sw?", TRUE); if (names[num_names] == NULL) goto end; ++num_names; } /* * Form the normal swap file name pattern by appending ".sw?". */ #ifdef VMS names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE); #else names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE); #endif if (names[num_names] == NULL) goto end; if (num_names >= 1) /* check if we have the same name twice */ { p = names[num_names - 1]; i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]); if (i > 0) p += i; /* file name has been expanded to full path */ if (STRCMP(p, names[num_names]) != 0) ++num_names; else vim_free(names[num_names]); } else ++num_names; # ifndef WIN3264 /* * Also try with 'shortname' set, in case the file is on a DOS filesystem. */ curbuf->b_shortname = TRUE; #ifdef VMS names[num_names] = modname(path, (char_u *)"_sw%", FALSE); #else names[num_names] = modname(path, (char_u *)".sw?", FALSE); #endif if (names[num_names] == NULL) goto end; /* * Remove the one from 'shortname', if it's the same as with 'noshortname'. */ p = names[num_names]; i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]); if (i > 0) p += i; /* file name has been expanded to full path */ if (STRCMP(names[num_names - 1], p) == 0) vim_free(names[num_names]); else ++num_names; # endif end: # ifndef WIN3264 curbuf->b_shortname = shortname; # endif #endif /* !SHORT_FNAME */ return num_names; } /* * sync all memlines * * If 'check_file' is TRUE, check if original file exists and was not changed. * If 'check_char' is TRUE, stop syncing when character becomes available, but * always sync at least one block. */ void ml_sync_all(check_file, check_char) int check_file; int check_char; { buf_T *buf; struct stat st; for (buf = firstbuf; buf != NULL; buf = buf->b_next) { if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL) continue; /* no file */ ml_flush_line(buf); /* flush buffered line */ /* flush locked block */ (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp) && buf->b_ffname != NULL) { /* * If the original file does not exist anymore or has been changed * call ml_preserve() to get rid of all negative numbered blocks. */ if (mch_stat((char *)buf->b_ffname, &st) == -1 || st.st_mtime != buf->b_mtime_read || st.st_size != buf->b_orig_size) { ml_preserve(buf, FALSE); did_check_timestamps = FALSE; need_check_timestamps = TRUE; /* give message later */ } } if (buf->b_ml.ml_mfp->mf_dirty) { (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0) | (bufIsChanged(buf) ? MFS_FLUSH : 0)); if (check_char && ui_char_avail()) /* character available now */ break; } } } /* * sync one buffer, including negative blocks * * after this all the blocks are in the swap file * * Used for the :preserve command and when the original file has been * changed or deleted. * * when message is TRUE the success of preserving is reported */ void ml_preserve(buf, message) buf_T *buf; int message; { bhdr_T *hp; linenr_T lnum; memfile_T *mfp = buf->b_ml.ml_mfp; int status; int got_int_save = got_int; if (mfp == NULL || mfp->mf_fname == NULL) { if (message) EMSG(_("E313: Cannot preserve, there is no swap file")); return; } /* We only want to stop when interrupted here, not when interrupted * before. */ got_int = FALSE; ml_flush_line(buf); /* flush buffered line */ (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */ status = mf_sync(mfp, MFS_ALL | MFS_FLUSH); /* stack is invalid after mf_sync(.., MFS_ALL) */ buf->b_ml.ml_stack_top = 0; /* * Some of the data blocks may have been changed from negative to * positive block number. In that case the pointer blocks need to be * updated. * * We don't know in which pointer block the references are, so we visit * all data blocks until there are no more translations to be done (or * we hit the end of the file, which can only happen in case a write fails, * e.g. when file system if full). * ml_find_line() does the work by translating the negative block numbers * when getting the first line of each data block. */ if (mf_need_trans(mfp) && !got_int) { lnum = 1; while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count) { hp = ml_find_line(buf, lnum, ML_FIND); if (hp == NULL) { status = FAIL; goto theend; } CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum"); lnum = buf->b_ml.ml_locked_high + 1; } (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */ /* sync the updated pointer blocks */ if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL) status = FAIL; buf->b_ml.ml_stack_top = 0; /* stack is invalid now */ } theend: got_int |= got_int_save; if (message) { if (status == OK) MSG(_("File preserved")); else EMSG(_("E314: Preserve failed")); } } /* * NOTE: The pointer returned by the ml_get_*() functions only remains valid * until the next call! * line1 = ml_get(1); * line2 = ml_get(2); // line1 is now invalid! * Make a copy of the line if necessary. */ /* * Return a pointer to a (read-only copy of a) line. * * On failure an error message is given and IObuff is returned (to avoid * having to check for error everywhere). */ char_u * ml_get(lnum) linenr_T lnum; { return ml_get_buf(curbuf, lnum, FALSE); } /* * Return pointer to position "pos". */ char_u * ml_get_pos(pos) pos_T *pos; { return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col); } /* * Return pointer to cursor line. */ char_u * ml_get_curline() { return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE); } /* * Return pointer to cursor position. */ char_u * ml_get_cursor() { return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) + curwin->w_cursor.col); } /* * Return a pointer to a line in a specific buffer * * "will_change": if TRUE mark the buffer dirty (chars in the line will be * changed) */ char_u * ml_get_buf(buf, lnum, will_change) buf_T *buf; linenr_T lnum; int will_change; /* line will be changed */ { bhdr_T *hp; DATA_BL *dp; char_u *ptr; static int recursive = 0; if (lnum > buf->b_ml.ml_line_count) /* invalid line number */ { if (recursive == 0) { /* Avoid giving this message for a recursive call, may happen when * the GUI redraws part of the text. */ ++recursive; EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum); --recursive; } errorret: STRCPY(IObuff, "???"); return IObuff; } if (lnum <= 0) /* pretend line 0 is line 1 */ lnum = 1; if (buf->b_ml.ml_mfp == NULL) /* there are no lines */ return (char_u *)""; /* * See if it is the same line as requested last time. * Otherwise may need to flush last used line. * Don't use the last used line when 'swapfile' is reset, need to load all * blocks. */ if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release) { ml_flush_line(buf); /* * Find the data block containing the line. * This also fills the stack with the blocks from the root to the data * block and releases any locked block. */ if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL) { if (recursive == 0) { /* Avoid giving this message for a recursive call, may happen * when the GUI redraws part of the text. */ ++recursive; EMSGN(_("E316: ml_get: cannot find line %ld"), lnum); --recursive; } goto errorret; } dp = (DATA_BL *)(hp->bh_data); ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK); buf->b_ml.ml_line_ptr = ptr; buf->b_ml.ml_line_lnum = lnum; buf->b_ml.ml_flags &= ~ML_LINE_DIRTY; } if (will_change) buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS); return buf->b_ml.ml_line_ptr; } /* * Check if a line that was just obtained by a call to ml_get * is in allocated memory. */ int ml_line_alloced() { return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY); } /* * Append a line after lnum (may be 0 to insert a line in front of the file). * "line" does not need to be allocated, but can't be another line in a * buffer, unlocking may make it invalid. * * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum * will be set for recovery * Check: The caller of this function should probably also call * appended_lines(). * * return FAIL for failure, OK otherwise */ int ml_append(lnum, line, len, newfile) linenr_T lnum; /* append after this line (can be 0) */ char_u *line; /* text of the new line */ colnr_T len; /* length of new line, including NUL, or 0 */ int newfile; /* flag, see above */ { /* When starting up, we might still need to create the memfile */ if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL) return FAIL; if (curbuf->b_ml.ml_line_lnum != 0) ml_flush_line(curbuf); return ml_append_int(curbuf, lnum, line, len, newfile, FALSE); } #if defined(FEAT_SPELL) || defined(PROTO) /* * Like ml_append() but for an arbitrary buffer. The buffer must already have * a memline. */ int ml_append_buf(buf, lnum, line, len, newfile) buf_T *buf; linenr_T lnum; /* append after this line (can be 0) */ char_u *line; /* text of the new line */ colnr_T len; /* length of new line, including NUL, or 0 */ int newfile; /* flag, see above */ { if (buf->b_ml.ml_mfp == NULL) return FAIL; if (buf->b_ml.ml_line_lnum != 0) ml_flush_line(buf); return ml_append_int(buf, lnum, line, len, newfile, FALSE); } #endif static int ml_append_int(buf, lnum, line, len, newfile, mark) buf_T *buf; linenr_T lnum; /* append after this line (can be 0) */ char_u *line; /* text of the new line */ colnr_T len; /* length of line, including NUL, or 0 */ int newfile; /* flag, see above */ int mark; /* mark the new line */ { int i; int line_count; /* number of indexes in current block */ int offset; int from, to; int space_needed; /* space needed for new line */ int page_size; int page_count; int db_idx; /* index for lnum in data block */ bhdr_T *hp; memfile_T *mfp; DATA_BL *dp; PTR_BL *pp; infoptr_T *ip; /* lnum out of range */ if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL) return FAIL; if (lowest_marked && lowest_marked > lnum) lowest_marked = lnum + 1; if (len == 0) len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */ space_needed = len + INDEX_SIZE; /* space needed for text + index */ mfp = buf->b_ml.ml_mfp; page_size = mfp->mf_page_size; /* * find the data block containing the previous line * This also fills the stack with the blocks from the root to the data block * This also releases any locked block. */ if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum, ML_INSERT)) == NULL) return FAIL; buf->b_ml.ml_flags &= ~ML_EMPTY; if (lnum == 0) /* got line one instead, correct db_idx */ db_idx = -1; /* careful, it is negative! */ else db_idx = lnum - buf->b_ml.ml_locked_low; /* get line count before the insertion */ line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low; dp = (DATA_BL *)(hp->bh_data); /* * If * - there is not enough room in the current block * - appending to the last line in the block * - not appending to the last line in the file * insert in front of the next block. */ if ((int)dp->db_free < space_needed && db_idx == line_count - 1 && lnum < buf->b_ml.ml_line_count) { /* * Now that the line is not going to be inserted in the block that we * expected, the line count has to be adjusted in the pointer blocks * by using ml_locked_lineadd. */ --(buf->b_ml.ml_locked_lineadd); --(buf->b_ml.ml_locked_high); if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL) return FAIL; db_idx = -1; /* careful, it is negative! */ /* get line count before the insertion */ line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low; CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1"); dp = (DATA_BL *)(hp->bh_data); } ++buf->b_ml.ml_line_count; if ((int)dp->db_free >= space_needed) /* enough room in data block */ { /* * Insert new line in existing data block, or in data block allocated above. */ dp->db_txt_start -= len; dp->db_free -= space_needed; ++(dp->db_line_count); /* * move the text of the lines that follow to the front * adjust the indexes of the lines that follow */ if (line_count > db_idx + 1) /* if there are following lines */ { /* * Offset is the start of the previous line. * This will become the character just after the new line. */ if (db_idx < 0) offset = dp->db_txt_end; else offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK); mch_memmove((char *)dp + dp->db_txt_start, (char *)dp + dp->db_txt_start + len, (size_t)(offset - (dp->db_txt_start + len))); for (i = line_count - 1; i > db_idx; --i) dp->db_index[i + 1] = dp->db_index[i] - len; dp->db_index[db_idx + 1] = offset - len; } else /* add line at the end */ dp->db_index[db_idx + 1] = dp->db_txt_start; /* * copy the text into the block */ mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len); if (mark) dp->db_index[db_idx + 1] |= DB_MARKED; /* * Mark the block dirty. */ buf->b_ml.ml_flags |= ML_LOCKED_DIRTY; if (!newfile) buf->b_ml.ml_flags |= ML_LOCKED_POS; } else /* not enough space in data block */ { /* * If there is not enough room we have to create a new data block and copy some * lines into it. * Then we have to insert an entry in the pointer block. * If this pointer block also is full, we go up another block, and so on, up * to the root if necessary. * The line counts in the pointer blocks have already been adjusted by * ml_find_line(). */ long line_count_left, line_count_right; int page_count_left, page_count_right; bhdr_T *hp_left; bhdr_T *hp_right; bhdr_T *hp_new; int lines_moved; int data_moved = 0; /* init to shut up gcc */ int total_moved = 0; /* init to shut up gcc */ DATA_BL *dp_right, *dp_left; int stack_idx; int in_left; int lineadd; blocknr_T bnum_left, bnum_right; linenr_T lnum_left, lnum_right; int pb_idx; PTR_BL *pp_new; /* * We are going to allocate a new data block. Depending on the * situation it will be put to the left or right of the existing * block. If possible we put the new line in the left block and move * the lines after it to the right block. Otherwise the new line is * also put in the right block. This method is more efficient when * inserting a lot of lines at one place. */ if (db_idx < 0) /* left block is new, right block is existing */ { lines_moved = 0; in_left = TRUE; /* space_needed does not change */ } else /* left block is existing, right block is new */ { lines_moved = line_count - db_idx - 1; if (lines_moved == 0) in_left = FALSE; /* put new line in right block */ /* space_needed does not change */ else { data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) - dp->db_txt_start; total_moved = data_moved + lines_moved * INDEX_SIZE; if ((int)dp->db_free + total_moved >= space_needed) { in_left = TRUE; /* put new line in left block */ space_needed = total_moved; } else { in_left = FALSE; /* put new line in right block */ space_needed += total_moved; } } } page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size; if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL) { /* correct line counts in pointer blocks */ --(buf->b_ml.ml_locked_lineadd); --(buf->b_ml.ml_locked_high); return FAIL; } if (db_idx < 0) /* left block is new */ { hp_left = hp_new; hp_right = hp; line_count_left = 0; line_count_right = line_count; } else /* right block is new */ { hp_left = hp; hp_right = hp_new; line_count_left = line_count; line_count_right = 0; } dp_right = (DATA_BL *)(hp_right->bh_data); dp_left = (DATA_BL *)(hp_left->bh_data); bnum_left = hp_left->bh_bnum; bnum_right = hp_right->bh_bnum; page_count_left = hp_left->bh_page_count; page_count_right = hp_right->bh_page_count; /* * May move the new line into the right/new block. */ if (!in_left) { dp_right->db_txt_start -= len; dp_right->db_free -= len + INDEX_SIZE; dp_right->db_index[0] = dp_right->db_txt_start; if (mark) dp_right->db_index[0] |= DB_MARKED; mch_memmove((char *)dp_right + dp_right->db_txt_start, line, (size_t)len); ++line_count_right; } /* * may move lines from the left/old block to the right/new one. */ if (lines_moved) { /* */ dp_right->db_txt_start -= data_moved; dp_right->db_free -= total_moved; mch_memmove((char *)dp_right + dp_right->db_txt_start, (char *)dp_left + dp_left->db_txt_start, (size_t)data_moved); offset = dp_right->db_txt_start - dp_left->db_txt_start; dp_left->db_txt_start += data_moved; dp_left->db_free += total_moved; /* * update indexes in the new block */ for (to = line_count_right, from = db_idx + 1; from < line_count_left; ++from, ++to) dp_right->db_index[to] = dp->db_index[from] + offset; line_count_right += lines_moved; line_count_left -= lines_moved; } /* * May move the new line into the left (old or new) block. */ if (in_left) { dp_left->db_txt_start -= len; dp_left->db_free -= len + INDEX_SIZE; dp_left->db_index[line_count_left] = dp_left->db_txt_start; if (mark) dp_left->db_index[line_count_left] |= DB_MARKED; mch_memmove((char *)dp_left + dp_left->db_txt_start, line, (size_t)len); ++line_count_left; } if (db_idx < 0) /* left block is new */ { lnum_left = lnum + 1; lnum_right = 0; } else /* right block is new */ { lnum_left = 0; if (in_left) lnum_right = lnum + 2; else lnum_right = lnum + 1; } dp_left->db_line_count = line_count_left; dp_right->db_line_count = line_count_right; /* * release the two data blocks * The new one (hp_new) already has a correct blocknumber. * The old one (hp, in ml_locked) gets a positive blocknumber if * we changed it and we are not editing a new file. */ if (lines_moved || in_left) buf->b_ml.ml_flags |= ML_LOCKED_DIRTY; if (!newfile && db_idx >= 0 && in_left) buf->b_ml.ml_flags |= ML_LOCKED_POS; mf_put(mfp, hp_new, TRUE, FALSE); /* * flush the old data block * set ml_locked_lineadd to 0, because the updating of the * pointer blocks is done below */ lineadd = buf->b_ml.ml_locked_lineadd; buf->b_ml.ml_locked_lineadd = 0; ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */ /* * update pointer blocks for the new data block */ for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; --stack_idx) { ip = &(buf->b_ml.ml_stack[stack_idx]); pb_idx = ip->ip_index; if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL) return FAIL; pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */ if (pp->pb_id != PTR_ID) { EMSG(_("E317: pointer block id wrong 3")); mf_put(mfp, hp, FALSE, FALSE); return FAIL; } /* * TODO: If the pointer block is full and we are adding at the end * try to insert in front of the next block */ /* block not full, add one entry */ if (pp->pb_count < pp->pb_count_max) { if (pb_idx + 1 < (int)pp->pb_count) mch_memmove(&pp->pb_pointer[pb_idx + 2], &pp->pb_pointer[pb_idx + 1], (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN)); ++pp->pb_count; pp->pb_pointer[pb_idx].pe_line_count = line_count_left; pp->pb_pointer[pb_idx].pe_bnum = bnum_left; pp->pb_pointer[pb_idx].pe_page_count = page_count_left; pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right; pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right; pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right; if (lnum_left != 0) pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left; if (lnum_right != 0) pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right; mf_put(mfp, hp, TRUE, FALSE); buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */ if (lineadd) { --(buf->b_ml.ml_stack_top); /* fix line count for rest of blocks in the stack */ ml_lineadd(buf, lineadd); /* fix stack itself */ buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high += lineadd; ++(buf->b_ml.ml_stack_top); } /* * We are finished, break the loop here. */ break; } else /* pointer block full */ { /* * split the pointer block * allocate a new pointer block * move some of the pointer into the new block * prepare for updating the parent block */ for (;;) /* do this twice when splitting block 1 */ { hp_new = ml_new_ptr(mfp); if (hp_new == NULL) /* TODO: try to fix tree */ return FAIL; pp_new = (PTR_BL *)(hp_new->bh_data); if (hp->bh_bnum != 1) break; /* * if block 1 becomes full the tree is given an extra level * The pointers from block 1 are moved into the new block. * block 1 is updated to point to the new block * then continue to split the new block */ mch_memmove(pp_new, pp, (size_t)page_size); pp->pb_count = 1; pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum; pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count; pp->pb_pointer[0].pe_old_lnum = 1; pp->pb_pointer[0].pe_page_count = 1; mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */ hp = hp_new; /* new block is to be split */ pp = pp_new; CHECK(stack_idx != 0, _("stack_idx should be 0")); ip->ip_index = 0; ++stack_idx; /* do block 1 again later */ } /* * move the pointers after the current one to the new block * If there are none, the new entry will be in the new block. */ total_moved = pp->pb_count - pb_idx - 1; if (total_moved) { mch_memmove(&pp_new->pb_pointer[0], &pp->pb_pointer[pb_idx + 1], (size_t)(total_moved) * sizeof(PTR_EN)); pp_new->pb_count = total_moved; pp->pb_count -= total_moved - 1; pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right; pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right; pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right; if (lnum_right) pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right; } else { pp_new->pb_count = 1; pp_new->pb_pointer[0].pe_bnum = bnum_right; pp_new->pb_pointer[0].pe_line_count = line_count_right; pp_new->pb_pointer[0].pe_page_count = page_count_right; pp_new->pb_pointer[0].pe_old_lnum = lnum_right; } pp->pb_pointer[pb_idx].pe_bnum = bnum_left; pp->pb_pointer[pb_idx].pe_line_count = line_count_left; pp->pb_pointer[pb_idx].pe_page_count = page_count_left; if (lnum_left) pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left; lnum_left = 0; lnum_right = 0; /* * recompute line counts */ line_count_right = 0; for (i = 0; i < (int)pp_new->pb_count; ++i) line_count_right += pp_new->pb_pointer[i].pe_line_count; line_count_left = 0; for (i = 0; i < (int)pp->pb_count; ++i) line_count_left += pp->pb_pointer[i].pe_line_count; bnum_left = hp->bh_bnum; bnum_right = hp_new->bh_bnum; page_count_left = 1; page_count_right = 1; mf_put(mfp, hp, TRUE, FALSE); mf_put(mfp, hp_new, TRUE, FALSE); } } /* * Safety check: fallen out of for loop? */ if (stack_idx < 0) { EMSG(_("E318: Updated too many blocks?")); buf->b_ml.ml_stack_top = 0; /* invalidate stack */ } } #ifdef FEAT_BYTEOFF /* The line was inserted below 'lnum' */ ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE); #endif #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { if (STRLEN(line) > 0) netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line)); netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line), (char_u *)"\n", 1); } #endif return OK; } /* * Replace line lnum, with buffering, in current buffer. * * If "copy" is TRUE, make a copy of the line, otherwise the line has been * copied to allocated memory already. * * Check: The caller of this function should probably also call * changed_lines(), unless update_screen(NOT_VALID) is used. * * return FAIL for failure, OK otherwise */ int ml_replace(lnum, line, copy) linenr_T lnum; char_u *line; int copy; { if (line == NULL) /* just checking... */ return FAIL; /* When starting up, we might still need to create the memfile */ if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL) return FAIL; if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */ return FAIL; #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum))); netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line)); } #endif if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */ ml_flush_line(curbuf); /* flush it */ else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */ vim_free(curbuf->b_ml.ml_line_ptr); /* free it */ curbuf->b_ml.ml_line_ptr = line; curbuf->b_ml.ml_line_lnum = lnum; curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY; return OK; } /* * Delete line 'lnum' in the current buffer. * * Check: The caller of this function should probably also call * deleted_lines() after this. * * return FAIL for failure, OK otherwise */ int ml_delete(lnum, message) linenr_T lnum; int message; { ml_flush_line(curbuf); return ml_delete_int(curbuf, lnum, message); } static int ml_delete_int(buf, lnum, message) buf_T *buf; linenr_T lnum; int message; { bhdr_T *hp; memfile_T *mfp; DATA_BL *dp; PTR_BL *pp; infoptr_T *ip; int count; /* number of entries in block */ int idx; int stack_idx; int text_start; int line_start; long line_size; int i; if (lnum < 1 || lnum > buf->b_ml.ml_line_count) return FAIL; if (lowest_marked && lowest_marked > lnum) lowest_marked--; /* * If the file becomes empty the last line is replaced by an empty line. */ if (buf->b_ml.ml_line_count == 1) /* file becomes empty */ { if (message #ifdef FEAT_NETBEANS_INTG && !netbeansSuppressNoLines #endif ) set_keep_msg((char_u *)_(no_lines_msg), 0); /* FEAT_BYTEOFF already handled in there, dont worry 'bout it below */ i = ml_replace((linenr_T)1, (char_u *)"", TRUE); buf->b_ml.ml_flags |= ML_EMPTY; return i; } /* * find the data block containing the line * This also fills the stack with the blocks from the root to the data block * This also releases any locked block. */ mfp = buf->b_ml.ml_mfp; if (mfp == NULL) return FAIL; if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL) return FAIL; dp = (DATA_BL *)(hp->bh_data); /* compute line count before the delete */ count = (long)(buf->b_ml.ml_locked_high) - (long)(buf->b_ml.ml_locked_low) + 2; idx = lnum - buf->b_ml.ml_locked_low; --buf->b_ml.ml_line_count; line_start = ((dp->db_index[idx]) & DB_INDEX_MASK); if (idx == 0) /* first line in block, text at the end */ line_size = dp->db_txt_end - line_start; else line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start; #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) netbeans_removed(buf, lnum, 0, (long)line_size); #endif /* * special case: If there is only one line in the data block it becomes empty. * Then we have to remove the entry, pointing to this data block, from the * pointer block. If this pointer block also becomes empty, we go up another * block, and so on, up to the root if necessary. * The line counts in the pointer blocks have already been adjusted by * ml_find_line(). */ if (count == 1) { mf_free(mfp, hp); /* free the data block */ buf->b_ml.ml_locked = NULL; for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; --stack_idx) { buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */ ip = &(buf->b_ml.ml_stack[stack_idx]); idx = ip->ip_index; if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL) return FAIL; pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */ if (pp->pb_id != PTR_ID) { EMSG(_("E317: pointer block id wrong 4")); mf_put(mfp, hp, FALSE, FALSE); return FAIL; } count = --(pp->pb_count); if (count == 0) /* the pointer block becomes empty! */ mf_free(mfp, hp); else { if (count != idx) /* move entries after the deleted one */ mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1], (size_t)(count - idx) * sizeof(PTR_EN)); mf_put(mfp, hp, TRUE, FALSE); buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */ /* fix line count for rest of blocks in the stack */ if (buf->b_ml.ml_locked_lineadd != 0) { ml_lineadd(buf, buf->b_ml.ml_locked_lineadd); buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high += buf->b_ml.ml_locked_lineadd; } ++(buf->b_ml.ml_stack_top); break; } } CHECK(stack_idx < 0, _("deleted block 1?")); } else { /* * delete the text by moving the next lines forwards */ text_start = dp->db_txt_start; mch_memmove((char *)dp + text_start + line_size, (char *)dp + text_start, (size_t)(line_start - text_start)); /* * delete the index by moving the next indexes backwards * Adjust the indexes for the text movement. */ for (i = idx; i < count - 1; ++i) dp->db_index[i] = dp->db_index[i + 1] + line_size; dp->db_free += line_size + INDEX_SIZE; dp->db_txt_start += line_size; --(dp->db_line_count); /* * mark the block dirty and make sure it is in the file (for recovery) */ buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS); } #ifdef FEAT_BYTEOFF ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE); #endif return OK; } /* * set the B_MARKED flag for line 'lnum' */ void ml_setmarked(lnum) linenr_T lnum; { bhdr_T *hp; DATA_BL *dp; /* invalid line number */ if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count || curbuf->b_ml.ml_mfp == NULL) return; /* give error message? */ if (lowest_marked == 0 || lowest_marked > lnum) lowest_marked = lnum; /* * find the data block containing the line * This also fills the stack with the blocks from the root to the data block * This also releases any locked block. */ if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) return; /* give error message? */ dp = (DATA_BL *)(hp->bh_data); dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED; curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY; } /* * find the first line with its B_MARKED flag set */ linenr_T ml_firstmarked() { bhdr_T *hp; DATA_BL *dp; linenr_T lnum; int i; if (curbuf->b_ml.ml_mfp == NULL) return (linenr_T) 0; /* * The search starts with lowest_marked line. This is the last line where * a mark was found, adjusted by inserting/deleting lines. */ for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; ) { /* * Find the data block containing the line. * This also fills the stack with the blocks from the root to the data * block This also releases any locked block. */ if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) return (linenr_T)0; /* give error message? */ dp = (DATA_BL *)(hp->bh_data); for (i = lnum - curbuf->b_ml.ml_locked_low; lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum) if ((dp->db_index[i]) & DB_MARKED) { (dp->db_index[i]) &= DB_INDEX_MASK; curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY; lowest_marked = lnum + 1; return lnum; } } return (linenr_T) 0; } /* * clear all DB_MARKED flags */ void ml_clearmarked() { bhdr_T *hp; DATA_BL *dp; linenr_T lnum; int i; if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */ return; /* * The search starts with line lowest_marked. */ for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; ) { /* * Find the data block containing the line. * This also fills the stack with the blocks from the root to the data * block and releases any locked block. */ if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) return; /* give error message? */ dp = (DATA_BL *)(hp->bh_data); for (i = lnum - curbuf->b_ml.ml_locked_low; lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum) if ((dp->db_index[i]) & DB_MARKED) { (dp->db_index[i]) &= DB_INDEX_MASK; curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY; } } lowest_marked = 0; return; } /* * flush ml_line if necessary */ static void ml_flush_line(buf) buf_T *buf; { bhdr_T *hp; DATA_BL *dp; linenr_T lnum; char_u *new_line; char_u *old_line; colnr_T new_len; int old_len; int extra; int idx; int start; int count; int i; static int entered = FALSE; if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL) return; /* nothing to do */ if (buf->b_ml.ml_flags & ML_LINE_DIRTY) { /* This code doesn't work recursively, but Netbeans may call back here * when obtaining the cursor position. */ if (entered) return; entered = TRUE; lnum = buf->b_ml.ml_line_lnum; new_line = buf->b_ml.ml_line_ptr; hp = ml_find_line(buf, lnum, ML_FIND); if (hp == NULL) EMSGN(_("E320: Cannot find line %ld"), lnum); else { dp = (DATA_BL *)(hp->bh_data); idx = lnum - buf->b_ml.ml_locked_low; start = ((dp->db_index[idx]) & DB_INDEX_MASK); old_line = (char_u *)dp + start; if (idx == 0) /* line is last in block */ old_len = dp->db_txt_end - start; else /* text of previous line follows */ old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start; new_len = (colnr_T)STRLEN(new_line) + 1; extra = new_len - old_len; /* negative if lines gets smaller */ /* * if new line fits in data block, replace directly */ if ((int)dp->db_free >= extra) { /* if the length changes and there are following lines */ count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1; if (extra != 0 && idx < count - 1) { /* move text of following lines */ mch_memmove((char *)dp + dp->db_txt_start - extra, (char *)dp + dp->db_txt_start, (size_t)(start - dp->db_txt_start)); /* adjust pointers of this and following lines */ for (i = idx + 1; i < count; ++i) dp->db_index[i] -= extra; } dp->db_index[idx] -= extra; /* adjust free space */ dp->db_free -= extra; dp->db_txt_start -= extra; /* copy new line into the data block */ mch_memmove(old_line - extra, new_line, (size_t)new_len); buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS); #ifdef FEAT_BYTEOFF /* The else case is already covered by the insert and delete */ ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE); #endif } else { /* * Cannot do it in one data block: Delete and append. * Append first, because ml_delete_int() cannot delete the * last line in a buffer, which causes trouble for a buffer * that has only one line. * Don't forget to copy the mark! */ /* How about handling errors??? */ (void)ml_append_int(buf, lnum, new_line, new_len, FALSE, (dp->db_index[idx] & DB_MARKED)); (void)ml_delete_int(buf, lnum, FALSE); } } vim_free(new_line); entered = FALSE; } buf->b_ml.ml_line_lnum = 0; } /* * create a new, empty, data block */ static bhdr_T * ml_new_data(mfp, negative, page_count) memfile_T *mfp; int negative; int page_count; { bhdr_T *hp; DATA_BL *dp; if ((hp = mf_new(mfp, negative, page_count)) == NULL) return NULL; dp = (DATA_BL *)(hp->bh_data); dp->db_id = DATA_ID; dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size; dp->db_free = dp->db_txt_start - HEADER_SIZE; dp->db_line_count = 0; return hp; } /* * create a new, empty, pointer block */ static bhdr_T * ml_new_ptr(mfp) memfile_T *mfp; { bhdr_T *hp; PTR_BL *pp; if ((hp = mf_new(mfp, FALSE, 1)) == NULL) return NULL; pp = (PTR_BL *)(hp->bh_data); pp->pb_id = PTR_ID; pp->pb_count = 0; pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL)) / sizeof(PTR_EN) + 1); return hp; } /* * lookup line 'lnum' in a memline * * action: if ML_DELETE or ML_INSERT the line count is updated while searching * if ML_FLUSH only flush a locked block * if ML_FIND just find the line * * If the block was found it is locked and put in ml_locked. * The stack is updated to lead to the locked block. The ip_high field in * the stack is updated to reflect the last line in the block AFTER the * insert or delete, also if the pointer block has not been updated yet. But * if ml_locked != NULL ml_locked_lineadd must be added to ip_high. * * return: NULL for failure, pointer to block header otherwise */ static bhdr_T * ml_find_line(buf, lnum, action) buf_T *buf; linenr_T lnum; int action; { DATA_BL *dp; PTR_BL *pp; infoptr_T *ip; bhdr_T *hp; memfile_T *mfp; linenr_T t; blocknr_T bnum, bnum2; int dirty; linenr_T low, high; int top; int page_count; int idx; mfp = buf->b_ml.ml_mfp; /* * If there is a locked block check if the wanted line is in it. * If not, flush and release the locked block. * Don't do this for ML_INSERT_SAME, because the stack need to be updated. * Don't do this for ML_FLUSH, because we want to flush the locked block. * Don't do this when 'swapfile' is reset, we want to load all the blocks. */ if (buf->b_ml.ml_locked) { if (ML_SIMPLE(action) && buf->b_ml.ml_locked_low <= lnum && buf->b_ml.ml_locked_high >= lnum && !mf_dont_release) { /* remember to update pointer blocks and stack later */ if (action == ML_INSERT) { ++(buf->b_ml.ml_locked_lineadd); ++(buf->b_ml.ml_locked_high); } else if (action == ML_DELETE) { --(buf->b_ml.ml_locked_lineadd); --(buf->b_ml.ml_locked_high); } return (buf->b_ml.ml_locked); } mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY, buf->b_ml.ml_flags & ML_LOCKED_POS); buf->b_ml.ml_locked = NULL; /* * If lines have been added or deleted in the locked block, need to * update the line count in pointer blocks. */ if (buf->b_ml.ml_locked_lineadd != 0) ml_lineadd(buf, buf->b_ml.ml_locked_lineadd); } if (action == ML_FLUSH) /* nothing else to do */ return NULL; bnum = 1; /* start at the root of the tree */ page_count = 1; low = 1; high = buf->b_ml.ml_line_count; if (action == ML_FIND) /* first try stack entries */ { for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top) { ip = &(buf->b_ml.ml_stack[top]); if (ip->ip_low <= lnum && ip->ip_high >= lnum) { bnum = ip->ip_bnum; low = ip->ip_low; high = ip->ip_high; buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */ break; } } if (top < 0) buf->b_ml.ml_stack_top = 0; /* not found, start at the root */ } else /* ML_DELETE or ML_INSERT */ buf->b_ml.ml_stack_top = 0; /* start at the root */ /* * search downwards in the tree until a data block is found */ for (;;) { if ((hp = mf_get(mfp, bnum, page_count)) == NULL) goto error_noblock; /* * update high for insert/delete */ if (action == ML_INSERT) ++high; else if (action == ML_DELETE) --high; dp = (DATA_BL *)(hp->bh_data); if (dp->db_id == DATA_ID) /* data block */ { buf->b_ml.ml_locked = hp; buf->b_ml.ml_locked_low = low; buf->b_ml.ml_locked_high = high; buf->b_ml.ml_locked_lineadd = 0; buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS); return hp; } pp = (PTR_BL *)(dp); /* must be pointer block */ if (pp->pb_id != PTR_ID) { EMSG(_("E317: pointer block id wrong")); goto error_block; } if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */ goto error_block; ip = &(buf->b_ml.ml_stack[top]); ip->ip_bnum = bnum; ip->ip_low = low; ip->ip_high = high; ip->ip_index = -1; /* index not known yet */ dirty = FALSE; for (idx = 0; idx < (int)pp->pb_count; ++idx) { t = pp->pb_pointer[idx].pe_line_count; CHECK(t == 0, _("pe_line_count is zero")); if ((low += t) > lnum) { ip->ip_index = idx; bnum = pp->pb_pointer[idx].pe_bnum; page_count = pp->pb_pointer[idx].pe_page_count; high = low - 1; low -= t; /* * a negative block number may have been changed */ if (bnum < 0) { bnum2 = mf_trans_del(mfp, bnum); if (bnum != bnum2) { bnum = bnum2; pp->pb_pointer[idx].pe_bnum = bnum; dirty = TRUE; } } break; } } if (idx >= (int)pp->pb_count) /* past the end: something wrong! */ { if (lnum > buf->b_ml.ml_line_count) EMSGN(_("E322: line number out of range: %ld past the end"), lnum - buf->b_ml.ml_line_count); else EMSGN(_("E323: line count wrong in block %ld"), bnum); goto error_block; } if (action == ML_DELETE) { pp->pb_pointer[idx].pe_line_count--; dirty = TRUE; } else if (action == ML_INSERT) { pp->pb_pointer[idx].pe_line_count++; dirty = TRUE; } mf_put(mfp, hp, dirty, FALSE); } error_block: mf_put(mfp, hp, FALSE, FALSE); error_noblock: /* * If action is ML_DELETE or ML_INSERT we have to correct the tree for * the incremented/decremented line counts, because there won't be a line * inserted/deleted after all. */ if (action == ML_DELETE) ml_lineadd(buf, 1); else if (action == ML_INSERT) ml_lineadd(buf, -1); buf->b_ml.ml_stack_top = 0; return NULL; } /* * add an entry to the info pointer stack * * return -1 for failure, number of the new entry otherwise */ static int ml_add_stack(buf) buf_T *buf; { int top; infoptr_T *newstack; top = buf->b_ml.ml_stack_top; /* may have to increase the stack size */ if (top == buf->b_ml.ml_stack_size) { CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */ newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) * (buf->b_ml.ml_stack_size + STACK_INCR)); if (newstack == NULL) return -1; mch_memmove(newstack, buf->b_ml.ml_stack, (size_t)top * sizeof(infoptr_T)); vim_free(buf->b_ml.ml_stack); buf->b_ml.ml_stack = newstack; buf->b_ml.ml_stack_size += STACK_INCR; } buf->b_ml.ml_stack_top++; return top; } /* * Update the pointer blocks on the stack for inserted/deleted lines. * The stack itself is also updated. * * When a insert/delete line action fails, the line is not inserted/deleted, * but the pointer blocks have already been updated. That is fixed here by * walking through the stack. * * Count is the number of lines added, negative if lines have been deleted. */ static void ml_lineadd(buf, count) buf_T *buf; int count; { int idx; infoptr_T *ip; PTR_BL *pp; memfile_T *mfp = buf->b_ml.ml_mfp; bhdr_T *hp; for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx) { ip = &(buf->b_ml.ml_stack[idx]); if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL) break; pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */ if (pp->pb_id != PTR_ID) { mf_put(mfp, hp, FALSE, FALSE); EMSG(_("E317: pointer block id wrong 2")); break; } pp->pb_pointer[ip->ip_index].pe_line_count += count; ip->ip_high += count; mf_put(mfp, hp, TRUE, FALSE); } } #if defined(HAVE_READLINK) || defined(PROTO) /* * Resolve a symlink in the last component of a file name. * Note that f_resolve() does it for every part of the path, we don't do that * here. * If it worked returns OK and the resolved link in "buf[MAXPATHL]". * Otherwise returns FAIL. */ int resolve_symlink(fname, buf) char_u *fname; char_u *buf; { char_u tmp[MAXPATHL]; int ret; int depth = 0; if (fname == NULL) return FAIL; /* Put the result so far in tmp[], starting with the original name. */ vim_strncpy(tmp, fname, MAXPATHL - 1); for (;;) { /* Limit symlink depth to 100, catch recursive loops. */ if (++depth == 100) { EMSG2(_("E773: Symlink loop for \"%s\""), fname); return FAIL; } ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1); if (ret <= 0) { if (errno == EINVAL || errno == ENOENT) { /* Found non-symlink or not existing file, stop here. * When at the first level use the unmodified name, skip the * call to vim_FullName(). */ if (depth == 1) return FAIL; /* Use the resolved name in tmp[]. */ break; } /* There must be some error reading links, use original name. */ return FAIL; } buf[ret] = NUL; /* * Check whether the symlink is relative or absolute. * If it's relative, build a new path based on the directory * portion of the filename (if any) and the path the symlink * points to. */ if (mch_isFullName(buf)) STRCPY(tmp, buf); else { char_u *tail; tail = gettail(tmp); if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL) return FAIL; STRCPY(tail, buf); } } /* * Try to resolve the full name of the file so that the swapfile name will * be consistent even when opening a relative symlink from different * working directories. */ return vim_FullName(tmp, buf, MAXPATHL, TRUE); } #endif /* * Make swap file name out of the file name and a directory name. * Returns pointer to allocated memory or NULL. */ char_u * makeswapname(fname, ffname, buf, dir_name) char_u *fname; char_u *ffname UNUSED; buf_T *buf; char_u *dir_name; { char_u *r, *s; char_u *fname_res = fname; #ifdef HAVE_READLINK char_u fname_buf[MAXPATHL]; #endif #if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */ s = dir_name + STRLEN(dir_name); if (after_pathsep(dir_name, s) && s[-1] == s[-2]) { /* Ends with '//', Use Full path */ r = NULL; if ((s = make_percent_swname(dir_name, fname)) != NULL) { r = modname(s, (char_u *)".swp", FALSE); vim_free(s); } return r; } #endif #ifdef HAVE_READLINK /* Expand symlink in the file name, so that we put the swap file with the * actual file instead of with the symlink. */ if (resolve_symlink(fname, fname_buf) == OK) fname_res = fname_buf; #endif r = buf_modname( #ifdef SHORT_FNAME TRUE, #else (buf->b_p_sn || buf->b_shortname), #endif fname_res, (char_u *) #if defined(VMS) "_swp", #else ".swp", #endif #ifdef SHORT_FNAME /* always 8.3 file name */ FALSE #else /* Prepend a '.' to the swap file name for the current directory. */ dir_name[0] == '.' && dir_name[1] == NUL #endif ); if (r == NULL) /* out of memory */ return NULL; s = get_file_in_dir(r, dir_name); vim_free(r); return s; } /* * Get file name to use for swap file or backup file. * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir' * option "dname". * - If "dname" is ".", return "fname" (swap file in dir of file). * - If "dname" starts with "./", insert "dname" in "fname" (swap file * relative to dir of file). * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific * dir). * * The return value is an allocated string and can be NULL. */ char_u * get_file_in_dir(fname, dname) char_u *fname; char_u *dname; /* don't use "dirname", it is a global for Alpha */ { char_u *t; char_u *tail; char_u *retval; int save_char; tail = gettail(fname); if (dname[0] == '.' && dname[1] == NUL) retval = vim_strsave(fname); else if (dname[0] == '.' && vim_ispathsep(dname[1])) { if (tail == fname) /* no path before file name */ retval = concat_fnames(dname + 2, tail, TRUE); else { save_char = *tail; *tail = NUL; t = concat_fnames(fname, dname + 2, TRUE); *tail = save_char; if (t == NULL) /* out of memory */ retval = NULL; else { retval = concat_fnames(t, tail, TRUE); vim_free(t); } } } else retval = concat_fnames(dname, tail, TRUE); return retval; } static void attention_message __ARGS((buf_T *buf, char_u *fname)); /* * Print the ATTENTION message: info about an existing swap file. */ static void attention_message(buf, fname) buf_T *buf; /* buffer being edited */ char_u *fname; /* swap file name */ { struct stat st; time_t x, sx; char *p; ++no_wait_return; (void)EMSG(_("E325: ATTENTION")); MSG_PUTS(_("\nFound a swap file by the name \"")); msg_home_replace(fname); MSG_PUTS("\"\n"); sx = swapfile_info(fname); MSG_PUTS(_("While opening file \"")); msg_outtrans(buf->b_fname); MSG_PUTS("\"\n"); if (mch_stat((char *)buf->b_fname, &st) != -1) { MSG_PUTS(_(" dated: ")); x = st.st_mtime; /* Manx C can't do &st.st_mtime */ p = ctime(&x); /* includes '\n' */ if (p == NULL) MSG_PUTS("(invalid)\n"); else MSG_PUTS(p); if (sx != 0 && x > sx) MSG_PUTS(_(" NEWER than swap file!\n")); } /* Some of these messages are long to allow translation to * other languages. */ MSG_PUTS(_("\n(1) Another program may be editing the same file. If this is the case,\n be careful not to end up with two different instances of the same\n file when making changes.")); MSG_PUTS(_(" Quit, or continue with caution.\n")); MSG_PUTS(_("(2) An edit session for this file crashed.\n")); MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r ")); msg_outtrans(buf->b_fname); MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n")); MSG_PUTS(_(" If you did this already, delete the swap file \"")); msg_outtrans(fname); MSG_PUTS(_("\"\n to avoid this message.\n")); cmdline_row = msg_row; --no_wait_return; } #ifdef FEAT_AUTOCMD static int do_swapexists __ARGS((buf_T *buf, char_u *fname)); /* * Trigger the SwapExists autocommands. * Returns a value for equivalent to do_dialog() (see below): * 0: still need to ask for a choice * 1: open read-only * 2: edit anyway * 3: recover * 4: delete it * 5: quit * 6: abort */ static int do_swapexists(buf, fname) buf_T *buf; char_u *fname; { set_vim_var_string(VV_SWAPNAME, fname, -1); set_vim_var_string(VV_SWAPCHOICE, NULL, -1); /* Trigger SwapExists autocommands with <afile> set to the file being * edited. Disallow changing directory here. */ ++allbuf_lock; apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL); --allbuf_lock; set_vim_var_string(VV_SWAPNAME, NULL, -1); switch (*get_vim_var_str(VV_SWAPCHOICE)) { case 'o': return 1; case 'e': return 2; case 'r': return 3; case 'd': return 4; case 'q': return 5; case 'a': return 6; } return 0; } #endif /* * Find out what name to use for the swap file for buffer 'buf'. * * Several names are tried to find one that does not exist * Returns the name in allocated memory or NULL. * When out of memory "dirp" is set to NULL. * * Note: If BASENAMELEN is not correct, you will get error messages for * not being able to open the swap or undo file * Note: May trigger SwapExists autocmd, pointers may change! */ static char_u * findswapname(buf, dirp, old_fname) buf_T *buf; char_u **dirp; /* pointer to list of directories */ char_u *old_fname; /* don't give warning for this file name */ { char_u *fname; int n; char_u *dir_name; #ifdef AMIGA BPTR fh; #endif #ifndef SHORT_FNAME int r; #endif #if !defined(SHORT_FNAME) \ && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE)) # define CREATE_DUMMY_FILE FILE *dummyfd = NULL; /* * If we start editing a new file, e.g. "test.doc", which resides on an * MSDOS compatible filesystem, it is possible that the file * "test.doc.swp" which we create will be exactly the same file. To avoid * this problem we temporarily create "test.doc". Don't do this when the * check below for a 8.3 file name is used. */ if (!(buf->b_p_sn || buf->b_shortname) && buf->b_fname != NULL && mch_getperm(buf->b_fname) < 0) dummyfd = mch_fopen((char *)buf->b_fname, "w"); #endif /* * Isolate a directory name from *dirp and put it in dir_name. * First allocate some memory to put the directory name in. */ dir_name = alloc((unsigned)STRLEN(*dirp) + 1); if (dir_name == NULL) *dirp = NULL; else (void)copy_option_part(dirp, dir_name, 31000, ","); /* * we try different names until we find one that does not exist yet */ if (dir_name == NULL) /* out of memory */ fname = NULL; else fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name); for (;;) { if (fname == NULL) /* must be out of memory */ break; if ((n = (int)STRLEN(fname)) == 0) /* safety check */ { vim_free(fname); fname = NULL; break; } #if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME) /* * Some systems have a MS-DOS compatible filesystem that use 8.3 character * file names. If this is the first try and the swap file name does not fit in * 8.3, detect if this is the case, set shortname and try again. */ if (fname[n - 2] == 'w' && fname[n - 1] == 'p' && !(buf->b_p_sn || buf->b_shortname)) { char_u *tail; char_u *fname2; struct stat s1, s2; int f1, f2; int created1 = FALSE, created2 = FALSE; int same = FALSE; /* * Check if swapfile name does not fit in 8.3: * It either contains two dots, is longer than 8 chars, or starts * with a dot. */ tail = gettail(buf->b_fname); if ( vim_strchr(tail, '.') != NULL || STRLEN(tail) > (size_t)8 || *gettail(fname) == '.') { fname2 = alloc(n + 2); if (fname2 != NULL) { STRCPY(fname2, fname); /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx" * if fname == ".xx.swp", fname2 = ".xx.swpx" * if fname == "123456789.swp", fname2 = "12345678x.swp" */ if (vim_strchr(tail, '.') != NULL) fname2[n - 1] = 'x'; else if (*gettail(fname) == '.') { fname2[n] = 'x'; fname2[n + 1] = NUL; } else fname2[n - 5] += 1; /* * may need to create the files to be able to use mch_stat() */ f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0); if (f1 < 0) { f1 = mch_open_rw((char *)fname, O_RDWR|O_CREAT|O_EXCL|O_EXTRA); #if defined(OS2) if (f1 < 0 && errno == ENOENT) same = TRUE; #endif created1 = TRUE; } if (f1 >= 0) { f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0); if (f2 < 0) { f2 = mch_open_rw((char *)fname2, O_RDWR|O_CREAT|O_EXCL|O_EXTRA); created2 = TRUE; } if (f2 >= 0) { /* * Both files exist now. If mch_stat() returns the * same device and inode they are the same file. */ if (mch_fstat(f1, &s1) != -1 && mch_fstat(f2, &s2) != -1 && s1.st_dev == s2.st_dev && s1.st_ino == s2.st_ino) same = TRUE; close(f2); if (created2) mch_remove(fname2); } close(f1); if (created1) mch_remove(fname); } vim_free(fname2); if (same) { buf->b_shortname = TRUE; vim_free(fname); fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name); continue; /* try again with b_shortname set */ } } } } #endif /* * check if the swapfile already exists */ if (mch_getperm(fname) < 0) /* it does not exist */ { #ifdef HAVE_LSTAT struct stat sb; /* * Extra security check: When a swap file is a symbolic link, this * is most likely a symlink attack. */ if (mch_lstat((char *)fname, &sb) < 0) #else # ifdef AMIGA fh = Open((UBYTE *)fname, (long)MODE_NEWFILE); /* * on the Amiga mch_getperm() will return -1 when the file exists * but is being used by another program. This happens if you edit * a file twice. */ if (fh != (BPTR)NULL) /* can open file, OK */ { Close(fh); mch_remove(fname); break; } if (IoErr() != ERROR_OBJECT_IN_USE && IoErr() != ERROR_OBJECT_EXISTS) # endif #endif break; } /* * A file name equal to old_fname is OK to use. */ if (old_fname != NULL && fnamecmp(fname, old_fname) == 0) break; /* * get here when file already exists */ if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */ { #ifndef SHORT_FNAME /* * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp * and file.doc are the same file. To guess if this problem is * present try if file.doc.swx exists. If it does, we set * buf->b_shortname and try file_doc.swp (dots replaced by * underscores for this file), and try again. If it doesn't we * assume that "file.doc.swp" already exists. */ if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */ { fname[n - 1] = 'x'; r = mch_getperm(fname); /* try "file.swx" */ fname[n - 1] = 'p'; if (r >= 0) /* "file.swx" seems to exist */ { buf->b_shortname = TRUE; vim_free(fname); fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name); continue; /* try again with '.' replaced with '_' */ } } #endif /* * If we get here the ".swp" file really exists. * Give an error message, unless recovering, no file name, we are * viewing a help file or when the path of the file is different * (happens when all .swp files are in one directory). */ if (!recoverymode && buf->b_fname != NULL && !buf->b_help && !(buf->b_flags & BF_DUMMY)) { int fd; struct block0 b0; int differ = FALSE; /* * Try to read block 0 from the swap file to get the original * file name (and inode number). */ fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0); if (fd >= 0) { if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0)) { /* * If the swapfile has the same directory as the * buffer don't compare the directory names, they can * have a different mountpoint. */ if (b0.b0_flags & B0_SAME_DIR) { if (fnamecmp(gettail(buf->b_ffname), gettail(b0.b0_fname)) != 0 || !same_directory(fname, buf->b_ffname)) { #ifdef CHECK_INODE /* Symlinks may point to the same file even * when the name differs, need to check the * inode too. */ expand_env(b0.b0_fname, NameBuff, MAXPATHL); if (fnamecmp_ino(buf->b_ffname, NameBuff, char_to_long(b0.b0_ino))) #endif differ = TRUE; } } else { /* * The name in the swap file may be * "~user/path/file". Expand it first. */ expand_env(b0.b0_fname, NameBuff, MAXPATHL); #ifdef CHECK_INODE if (fnamecmp_ino(buf->b_ffname, NameBuff, char_to_long(b0.b0_ino))) differ = TRUE; #else if (fnamecmp(NameBuff, buf->b_ffname) != 0) differ = TRUE; #endif } } close(fd); } /* give the ATTENTION message when there is an old swap file * for the current file, and the buffer was not recovered. */ if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED) && vim_strchr(p_shm, SHM_ATTENTION) == NULL) { #if defined(HAS_SWAP_EXISTS_ACTION) int choice = 0; #endif #ifdef CREATE_DUMMY_FILE int did_use_dummy = FALSE; /* Avoid getting a warning for the file being created * outside of Vim, it was created at the start of this * function. Delete the file now, because Vim might exit * here if the window is closed. */ if (dummyfd != NULL) { fclose(dummyfd); dummyfd = NULL; mch_remove(buf->b_fname); did_use_dummy = TRUE; } #endif #if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)) process_still_running = FALSE; #endif #ifdef FEAT_AUTOCMD /* * If there is an SwapExists autocommand and we can handle * the response, trigger it. It may return 0 to ask the * user anyway. */ if (swap_exists_action != SEA_NONE && has_autocmd(EVENT_SWAPEXISTS, buf->b_fname, buf)) choice = do_swapexists(buf, fname); if (choice == 0) #endif { #ifdef FEAT_GUI /* If we are supposed to start the GUI but it wasn't * completely started yet, start it now. This makes * the messages displayed in the Vim window when * loading a session from the .gvimrc file. */ if (gui.starting && !gui.in_use) gui_start(); #endif /* Show info about the existing swap file. */ attention_message(buf, fname); /* We don't want a 'q' typed at the more-prompt * interrupt loading a file. */ got_int = FALSE; } #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if (swap_exists_action != SEA_NONE && choice == 0) { char_u *name; name = alloc((unsigned)(STRLEN(fname) + STRLEN(_("Swap file \"")) + STRLEN(_("\" already exists!")) + 5)); if (name != NULL) { STRCPY(name, _("Swap file \"")); home_replace(NULL, fname, name + STRLEN(name), 1000, TRUE); STRCAT(name, _("\" already exists!")); } choice = do_dialog(VIM_WARNING, (char_u *)_("VIM - ATTENTION"), name == NULL ? (char_u *)_("Swap file already exists!") : name, # if defined(UNIX) || defined(__EMX__) || defined(VMS) process_still_running ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") : # endif (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort"), 1, NULL, FALSE); # if defined(UNIX) || defined(__EMX__) || defined(VMS) if (process_still_running && choice >= 4) choice++; /* Skip missing "Delete it" button */ # endif vim_free(name); /* pretend screen didn't scroll, need redraw anyway */ msg_scrolled = 0; redraw_all_later(NOT_VALID); } #endif #if defined(HAS_SWAP_EXISTS_ACTION) if (choice > 0) { switch (choice) { case 1: buf->b_p_ro = TRUE; break; case 2: break; case 3: swap_exists_action = SEA_RECOVER; break; case 4: mch_remove(fname); break; case 5: swap_exists_action = SEA_QUIT; break; case 6: swap_exists_action = SEA_QUIT; got_int = TRUE; break; } /* If the file was deleted this fname can be used. */ if (mch_getperm(fname) < 0) break; } else #endif { MSG_PUTS("\n"); if (msg_silent == 0) /* call wait_return() later */ need_wait_return = TRUE; } #ifdef CREATE_DUMMY_FILE /* Going to try another name, need the dummy file again. */ if (did_use_dummy) dummyfd = mch_fopen((char *)buf->b_fname, "w"); #endif } } } /* * Change the ".swp" extension to find another file that can be used. * First decrement the last char: ".swo", ".swn", etc. * If that still isn't enough decrement the last but one char: ".svz" * Can happen when editing many "No Name" buffers. */ if (fname[n - 1] == 'a') /* ".s?a" */ { if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */ { EMSG(_("E326: Too many swap files found")); vim_free(fname); fname = NULL; break; } --fname[n - 2]; /* ".svz", ".suz", etc. */ fname[n - 1] = 'z' + 1; } --fname[n - 1]; /* ".swo", ".swn", etc. */ } vim_free(dir_name); #ifdef CREATE_DUMMY_FILE if (dummyfd != NULL) /* file has been created temporarily */ { fclose(dummyfd); mch_remove(buf->b_fname); } #endif return fname; } static int b0_magic_wrong(b0p) ZERO_BL *b0p; { return (b0p->b0_magic_long != (long)B0_MAGIC_LONG || b0p->b0_magic_int != (int)B0_MAGIC_INT || b0p->b0_magic_short != (short)B0_MAGIC_SHORT || b0p->b0_magic_char != B0_MAGIC_CHAR); } #ifdef CHECK_INODE /* * Compare current file name with file name from swap file. * Try to use inode numbers when possible. * Return non-zero when files are different. * * When comparing file names a few things have to be taken into consideration: * - When working over a network the full path of a file depends on the host. * We check the inode number if possible. It is not 100% reliable though, * because the device number cannot be used over a network. * - When a file does not exist yet (editing a new file) there is no inode * number. * - The file name in a swap file may not be valid on the current host. The * "~user" form is used whenever possible to avoid this. * * This is getting complicated, let's make a table: * * ino_c ino_s fname_c fname_s differ = * * both files exist -> compare inode numbers: * != 0 != 0 X X ino_c != ino_s * * inode number(s) unknown, file names available -> compare file names * == 0 X OK OK fname_c != fname_s * X == 0 OK OK fname_c != fname_s * * current file doesn't exist, file for swap file exist, file name(s) not * available -> probably different * == 0 != 0 FAIL X TRUE * == 0 != 0 X FAIL TRUE * * current file exists, inode for swap unknown, file name(s) not * available -> probably different * != 0 == 0 FAIL X TRUE * != 0 == 0 X FAIL TRUE * * current file doesn't exist, inode for swap unknown, one file name not * available -> probably different * == 0 == 0 FAIL OK TRUE * == 0 == 0 OK FAIL TRUE * * current file doesn't exist, inode for swap unknown, both file names not * available -> probably same file * == 0 == 0 FAIL FAIL FALSE * * Note that when the ino_t is 64 bits, only the last 32 will be used. This * can't be changed without making the block 0 incompatible with 32 bit * versions. */ static int fnamecmp_ino(fname_c, fname_s, ino_block0) char_u *fname_c; /* current file name */ char_u *fname_s; /* file name from swap file */ long ino_block0; { struct stat st; ino_t ino_c = 0; /* ino of current file */ ino_t ino_s; /* ino of file from swap file */ char_u buf_c[MAXPATHL]; /* full path of fname_c */ char_u buf_s[MAXPATHL]; /* full path of fname_s */ int retval_c; /* flag: buf_c valid */ int retval_s; /* flag: buf_s valid */ if (mch_stat((char *)fname_c, &st) == 0) ino_c = (ino_t)st.st_ino; /* * First we try to get the inode from the file name, because the inode in * the swap file may be outdated. If that fails (e.g. this path is not * valid on this machine), use the inode from block 0. */ if (mch_stat((char *)fname_s, &st) == 0) ino_s = (ino_t)st.st_ino; else ino_s = (ino_t)ino_block0; if (ino_c && ino_s) return (ino_c != ino_s); /* * One of the inode numbers is unknown, try a forced vim_FullName() and * compare the file names. */ retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE); retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE); if (retval_c == OK && retval_s == OK) return (STRCMP(buf_c, buf_s) != 0); /* * Can't compare inodes or file names, guess that the files are different, * unless both appear not to exist at all. */ if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL) return FALSE; return TRUE; } #endif /* CHECK_INODE */ /* * Move a long integer into a four byte character array. * Used for machine independency in block zero. */ static void long_to_char(n, s) long n; char_u *s; { s[0] = (char_u)(n & 0xff); n = (unsigned)n >> 8; s[1] = (char_u)(n & 0xff); n = (unsigned)n >> 8; s[2] = (char_u)(n & 0xff); n = (unsigned)n >> 8; s[3] = (char_u)(n & 0xff); } static long char_to_long(s) char_u *s; { long retval; retval = s[3]; retval <<= 8; retval |= s[2]; retval <<= 8; retval |= s[1]; retval <<= 8; retval |= s[0]; return retval; } /* * Set the flags in the first block of the swap file: * - file is modified or not: buf->b_changed * - 'fileformat' * - 'fileencoding' */ void ml_setflags(buf) buf_T *buf; { bhdr_T *hp; ZERO_BL *b0p; if (!buf->b_ml.ml_mfp) return; for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev) { if (hp->bh_bnum == 0) { b0p = (ZERO_BL *)(hp->bh_data); b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0; b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK) | (get_fileformat(buf) + 1); #ifdef FEAT_MBYTE add_b0_fenc(b0p, buf); #endif hp->bh_flags |= BH_DIRTY; mf_sync(buf->b_ml.ml_mfp, MFS_ZERO); break; } } } #if defined(FEAT_CRYPT) || defined(PROTO) /* * If "data" points to a data block encrypt the text in it and return a copy * in allocated memory. Return NULL when out of memory. * Otherwise return "data". */ char_u * ml_encrypt_data(mfp, data, offset, size) memfile_T *mfp; char_u *data; off_t offset; unsigned size; { DATA_BL *dp = (DATA_BL *)data; char_u *head_end; char_u *text_start; char_u *new_data; int text_len; if (dp->db_id != DATA_ID) return data; new_data = (char_u *)alloc(size); if (new_data == NULL) return NULL; head_end = (char_u *)(&dp->db_index[dp->db_line_count]); text_start = (char_u *)dp + dp->db_txt_start; text_len = size - dp->db_txt_start; /* Copy the header and the text. */ mch_memmove(new_data, dp, head_end - (char_u *)dp); /* Encrypt the text. */ crypt_push_state(); ml_crypt_prepare(mfp, offset, FALSE); crypt_encode(text_start, text_len, new_data + dp->db_txt_start); crypt_pop_state(); /* Clear the gap. */ if (head_end < text_start) vim_memset(new_data + (head_end - data), 0, text_start - head_end); return new_data; } /* * Decrypt the text in "data" if it points to a data block. */ void ml_decrypt_data(mfp, data, offset, size) memfile_T *mfp; char_u *data; off_t offset; unsigned size; { DATA_BL *dp = (DATA_BL *)data; char_u *head_end; char_u *text_start; int text_len; if (dp->db_id == DATA_ID) { head_end = (char_u *)(&dp->db_index[dp->db_line_count]); text_start = (char_u *)dp + dp->db_txt_start; text_len = dp->db_txt_end - dp->db_txt_start; if (head_end > text_start || dp->db_txt_start > size || dp->db_txt_end > size) return; /* data was messed up */ /* Decrypt the text in place. */ crypt_push_state(); ml_crypt_prepare(mfp, offset, TRUE); crypt_decode(text_start, text_len); crypt_pop_state(); } } /* * Prepare for encryption/decryption, using the key, seed and offset. */ static void ml_crypt_prepare(mfp, offset, reading) memfile_T *mfp; off_t offset; int reading; { buf_T *buf = mfp->mf_buffer; char_u salt[50]; int method; char_u *key; char_u *seed; if (reading && mfp->mf_old_key != NULL) { /* Reading back blocks with the previous key/method/seed. */ method = mfp->mf_old_cm; key = mfp->mf_old_key; seed = mfp->mf_old_seed; } else { method = get_crypt_method(buf); key = buf->b_p_key; seed = mfp->mf_seed; } use_crypt_method = method; /* select pkzip or blowfish */ if (method == 0) { vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset); crypt_init_keys(salt); } else { /* Using blowfish, add salt and seed. We use the byte offset of the * block for the salt. */ vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset); bf_key_init(key, salt, (int)STRLEN(salt)); bf_ofb_init(seed, MF_SEED_LEN); } } #endif #if defined(FEAT_BYTEOFF) || defined(PROTO) #define MLCS_MAXL 800 /* max no of lines in chunk */ #define MLCS_MINL 400 /* should be half of MLCS_MAXL */ /* * Keep information for finding byte offset of a line, updtype may be one of: * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called. * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity. */ static void ml_updatechunk(buf, line, len, updtype) buf_T *buf; linenr_T line; long len; int updtype; { static buf_T *ml_upd_lastbuf = NULL; static linenr_T ml_upd_lastline; static linenr_T ml_upd_lastcurline; static int ml_upd_lastcurix; linenr_T curline = ml_upd_lastcurline; int curix = ml_upd_lastcurix; long size; chunksize_T *curchnk; int rest; bhdr_T *hp; DATA_BL *dp; if (buf->b_ml.ml_usedchunks == -1 || len == 0) return; if (buf->b_ml.ml_chunksize == NULL) { buf->b_ml.ml_chunksize = (chunksize_T *) alloc((unsigned)sizeof(chunksize_T) * 100); if (buf->b_ml.ml_chunksize == NULL) { buf->b_ml.ml_usedchunks = -1; return; } buf->b_ml.ml_numchunks = 100; buf->b_ml.ml_usedchunks = 1; buf->b_ml.ml_chunksize[0].mlcs_numlines = 1; buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1; } if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1) { /* * First line in empty buffer from ml_flush_line() -- reset */ buf->b_ml.ml_usedchunks = 1; buf->b_ml.ml_chunksize[0].mlcs_numlines = 1; buf->b_ml.ml_chunksize[0].mlcs_totalsize = (long)STRLEN(buf->b_ml.ml_line_ptr) + 1; return; } /* * Find chunk that our line belongs to, curline will be at start of the * chunk. */ if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1 || updtype != ML_CHNK_ADDLINE) { for (curline = 1, curix = 0; curix < buf->b_ml.ml_usedchunks - 1 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines; curix++) { curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines; } } else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines && curix < buf->b_ml.ml_usedchunks - 1) { /* Adjust cached curix & curline */ curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines; curix++; } curchnk = buf->b_ml.ml_chunksize + curix; if (updtype == ML_CHNK_DELLINE) len = -len; curchnk->mlcs_totalsize += len; if (updtype == ML_CHNK_ADDLINE) { curchnk->mlcs_numlines++; /* May resize here so we don't have to do it in both cases below */ if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks) { buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2; buf->b_ml.ml_chunksize = (chunksize_T *) vim_realloc(buf->b_ml.ml_chunksize, sizeof(chunksize_T) * buf->b_ml.ml_numchunks); if (buf->b_ml.ml_chunksize == NULL) { /* Hmmmm, Give up on offset for this buffer */ buf->b_ml.ml_usedchunks = -1; return; } } if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL) { int count; /* number of entries in block */ int idx; int text_end; int linecnt; mch_memmove(buf->b_ml.ml_chunksize + curix + 1, buf->b_ml.ml_chunksize + curix, (buf->b_ml.ml_usedchunks - curix) * sizeof(chunksize_T)); /* Compute length of first half of lines in the split chunk */ size = 0; linecnt = 0; while (curline < buf->b_ml.ml_line_count && linecnt < MLCS_MINL) { if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL) { buf->b_ml.ml_usedchunks = -1; return; } dp = (DATA_BL *)(hp->bh_data); count = (long)(buf->b_ml.ml_locked_high) - (long)(buf->b_ml.ml_locked_low) + 1; idx = curline - buf->b_ml.ml_locked_low; curline = buf->b_ml.ml_locked_high + 1; if (idx == 0)/* first line in block, text at the end */ text_end = dp->db_txt_end; else text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK); /* Compute index of last line to use in this MEMLINE */ rest = count - idx; if (linecnt + rest > MLCS_MINL) { idx += MLCS_MINL - linecnt - 1; linecnt = MLCS_MINL; } else { idx = count - 1; linecnt += rest; } size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK); } buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt; buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt; buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size; buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size; buf->b_ml.ml_usedchunks++; ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */ return; } else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL && curix == buf->b_ml.ml_usedchunks - 1 && buf->b_ml.ml_line_count - line <= 1) { /* * We are in the last chunk and it is cheap to crate a new one * after this. Do it now to avoid the loop above later on */ curchnk = buf->b_ml.ml_chunksize + curix + 1; buf->b_ml.ml_usedchunks++; if (line == buf->b_ml.ml_line_count) { curchnk->mlcs_numlines = 0; curchnk->mlcs_totalsize = 0; } else { /* * Line is just prior to last, move count for last * This is the common case when loading a new file */ hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND); if (hp == NULL) { buf->b_ml.ml_usedchunks = -1; return; } dp = (DATA_BL *)(hp->bh_data); if (dp->db_line_count == 1) rest = dp->db_txt_end - dp->db_txt_start; else rest = ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK) - dp->db_txt_start; curchnk->mlcs_totalsize = rest; curchnk->mlcs_numlines = 1; curchnk[-1].mlcs_totalsize -= rest; curchnk[-1].mlcs_numlines -= 1; } } } else if (updtype == ML_CHNK_DELLINE) { curchnk->mlcs_numlines--; ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */ if (curix < (buf->b_ml.ml_usedchunks - 1) && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines) <= MLCS_MINL) { curix++; curchnk = buf->b_ml.ml_chunksize + curix; } else if (curix == 0 && curchnk->mlcs_numlines <= 0) { buf->b_ml.ml_usedchunks--; mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1, buf->b_ml.ml_usedchunks * sizeof(chunksize_T)); return; } else if (curix == 0 || (curchnk->mlcs_numlines > 10 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines) > MLCS_MINL)) { return; } /* Collapse chunks */ curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines; curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize; buf->b_ml.ml_usedchunks--; if (curix < buf->b_ml.ml_usedchunks) { mch_memmove(buf->b_ml.ml_chunksize + curix, buf->b_ml.ml_chunksize + curix + 1, (buf->b_ml.ml_usedchunks - curix) * sizeof(chunksize_T)); } return; } ml_upd_lastbuf = buf; ml_upd_lastline = line; ml_upd_lastcurline = curline; ml_upd_lastcurix = curix; } /* * Find offset for line or line with offset. * Find line with offset if "lnum" is 0; return remaining offset in offp * Find offset of line if "lnum" > 0 * return -1 if information is not available */ long ml_find_line_or_offset(buf, lnum, offp) buf_T *buf; linenr_T lnum; long *offp; { linenr_T curline; int curix; long size; bhdr_T *hp; DATA_BL *dp; int count; /* number of entries in block */ int idx; int start_idx; int text_end; long offset; int len; int ffdos = (get_fileformat(buf) == EOL_DOS); int extra = 0; /* take care of cached line first */ ml_flush_line(curbuf); if (buf->b_ml.ml_usedchunks == -1 || buf->b_ml.ml_chunksize == NULL || lnum < 0) return -1; if (offp == NULL) offset = 0; else offset = *offp; if (lnum == 0 && offset <= 0) return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */ /* * Find the last chunk before the one containing our line. Last chunk is * special because it will never qualify */ curline = 1; curix = size = 0; while (curix < buf->b_ml.ml_usedchunks - 1 && ((lnum != 0 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines) || (offset != 0 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines))) { curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines; size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize; if (offset && ffdos) size += buf->b_ml.ml_chunksize[curix].mlcs_numlines; curix++; } while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset)) { if (curline > buf->b_ml.ml_line_count || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL) return -1; dp = (DATA_BL *)(hp->bh_data); count = (long)(buf->b_ml.ml_locked_high) - (long)(buf->b_ml.ml_locked_low) + 1; start_idx = idx = curline - buf->b_ml.ml_locked_low; if (idx == 0)/* first line in block, text at the end */ text_end = dp->db_txt_end; else text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK); /* Compute index of last line to use in this MEMLINE */ if (lnum != 0) { if (curline + (count - idx) >= lnum) idx += lnum - curline - 1; else idx = count - 1; } else { extra = 0; while (offset >= size + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK) + ffdos) { if (ffdos) size++; if (idx == count - 1) { extra = 1; break; } idx++; } } len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK); size += len; if (offset != 0 && size >= offset) { if (size + ffdos == offset) *offp = 0; else if (idx == start_idx) *offp = offset - size + len; else *offp = offset - size + len - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK)); curline += idx - start_idx + extra; if (curline > buf->b_ml.ml_line_count) return -1; /* exactly one byte beyond the end */ return curline; } curline = buf->b_ml.ml_locked_high + 1; } if (lnum != 0) { /* Count extra CR characters. */ if (ffdos) size += lnum - 1; /* Don't count the last line break if 'bin' and 'noeol'. */ if (buf->b_p_bin && !buf->b_p_eol) size -= ffdos + 1; } return size; } /* * Goto byte in buffer with offset 'cnt'. */ void goto_byte(cnt) long cnt; { long boff = cnt; linenr_T lnum; ml_flush_line(curbuf); /* cached line may be dirty */ setpcmark(); if (boff) --boff; lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff); if (lnum < 1) /* past the end */ { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; curwin->w_curswant = MAXCOL; coladvance((colnr_T)MAXCOL); } else { curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = (colnr_T)boff; # ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; # endif curwin->w_set_curswant = TRUE; } check_cursor(); # ifdef FEAT_MBYTE /* Make sure the cursor is on the first byte of a multi-byte char. */ if (has_mbyte) mb_adjust_cursor(); # endif } #endif
zyz2011-vim
src/memline.c
C
gpl2
143,629
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * eval.c: Expression evaluation. */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) #ifdef AMIGA # include <time.h> /* for strftime() */ #endif #ifdef VMS # include <float.h> #endif #ifdef MACOS # include <time.h> /* for time_t */ #endif #if defined(FEAT_FLOAT) && defined(HAVE_MATH_H) # include <math.h> #endif #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */ #define DO_NOT_FREE_CNT 99999 /* refcount for dict or list that should not be freed. */ /* * In a hashtab item "hi_key" points to "di_key" in a dictitem. * This avoids adding a pointer to the hashtab item. * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer. * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer. * HI2DI() converts a hashitem pointer to a dictitem pointer. */ static dictitem_T dumdi; #define DI2HIKEY(di) ((di)->di_key) #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi))) #define HI2DI(hi) HIKEY2DI((hi)->hi_key) /* * Structure returned by get_lval() and used by set_var_lval(). * For a plain name: * "name" points to the variable name. * "exp_name" is NULL. * "tv" is NULL * For a magic braces name: * "name" points to the expanded variable name. * "exp_name" is non-NULL, to be freed later. * "tv" is NULL * For an index in a list: * "name" points to the (expanded) variable name. * "exp_name" NULL or non-NULL, to be freed later. * "tv" points to the (first) list item value * "li" points to the (first) list item * "range", "n1", "n2" and "empty2" indicate what items are used. * For an existing Dict item: * "name" points to the (expanded) variable name. * "exp_name" NULL or non-NULL, to be freed later. * "tv" points to the dict item value * "newkey" is NULL * For a non-existing Dict item: * "name" points to the (expanded) variable name. * "exp_name" NULL or non-NULL, to be freed later. * "tv" points to the Dictionary typval_T * "newkey" is the key for the new item. */ typedef struct lval_S { char_u *ll_name; /* start of variable name (can be NULL) */ char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */ typval_T *ll_tv; /* Typeval of item being used. If "newkey" isn't NULL it's the Dict to which to add the item. */ listitem_T *ll_li; /* The list item or NULL. */ list_T *ll_list; /* The list or NULL. */ int ll_range; /* TRUE when a [i:j] range was used */ long ll_n1; /* First index for list */ long ll_n2; /* Second index for list range */ int ll_empty2; /* Second index is empty: [i:] */ dict_T *ll_dict; /* The Dictionary or NULL */ dictitem_T *ll_di; /* The dictitem or NULL */ char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */ } lval_T; static char *e_letunexp = N_("E18: Unexpected characters in :let"); static char *e_listidx = N_("E684: list index out of range: %ld"); static char *e_undefvar = N_("E121: Undefined variable: %s"); static char *e_missbrac = N_("E111: Missing ']'"); static char *e_listarg = N_("E686: Argument of %s must be a List"); static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary"); static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary"); static char *e_listreq = N_("E714: List required"); static char *e_dictreq = N_("E715: Dictionary required"); static char *e_toomanyarg = N_("E118: Too many arguments for function: %s"); static char *e_dictkey = N_("E716: Key not present in Dictionary: %s"); static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it"); static char *e_funcdict = N_("E717: Dictionary entry already exists"); static char *e_funcref = N_("E718: Funcref required"); static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary"); static char *e_letwrong = N_("E734: Wrong variable type for %s="); static char *e_nofunc = N_("E130: Unknown function: %s"); static char *e_illvar = N_("E461: Illegal variable name: %s"); /* * All user-defined global variables are stored in dictionary "globvardict". * "globvars_var" is the variable that is used for "g:". */ static dict_T globvardict; static dictitem_T globvars_var; #define globvarht globvardict.dv_hashtab /* * Old Vim variables such as "v:version" are also available without the "v:". * Also in functions. We need a special hashtable for them. */ static hashtab_T compat_hashtab; /* When using exists() don't auto-load a script. */ static int no_autoload = FALSE; /* * When recursively copying lists and dicts we need to remember which ones we * have done to avoid endless recursiveness. This unique ID is used for that. * The last bit is used for previous_funccal, ignored when comparing. */ static int current_copyID = 0; #define COPYID_INC 2 #define COPYID_MASK (~0x1) /* * Array to hold the hashtab with variables local to each sourced script. * Each item holds a variable (nameless) that points to the dict_T. */ typedef struct { dictitem_T sv_var; dict_T sv_dict; } scriptvar_T; static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL}; #define SCRIPT_SV(id) (((scriptvar_T **)ga_scripts.ga_data)[(id) - 1]) #define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab) static int echo_attr = 0; /* attributes used for ":echo" */ /* Values for trans_function_name() argument: */ #define TFN_INT 1 /* internal function name OK */ #define TFN_QUIET 2 /* no error messages */ /* * Structure to hold info for a user function. */ typedef struct ufunc ufunc_T; struct ufunc { int uf_varargs; /* variable nr of arguments */ int uf_flags; int uf_calls; /* nr of active calls */ garray_T uf_args; /* arguments */ garray_T uf_lines; /* function lines */ #ifdef FEAT_PROFILE int uf_profiling; /* TRUE when func is being profiled */ /* profiling the function as a whole */ int uf_tm_count; /* nr of calls */ proftime_T uf_tm_total; /* time spent in function + children */ proftime_T uf_tm_self; /* time spent in function itself */ proftime_T uf_tm_children; /* time spent in children this call */ /* profiling the function per line */ int *uf_tml_count; /* nr of times line was executed */ proftime_T *uf_tml_total; /* time spent in a line + children */ proftime_T *uf_tml_self; /* time spent in a line itself */ proftime_T uf_tml_start; /* start time for current line */ proftime_T uf_tml_children; /* time spent in children for this line */ proftime_T uf_tml_wait; /* start wait time for current line */ int uf_tml_idx; /* index of line being timed; -1 if none */ int uf_tml_execed; /* line being timed was executed */ #endif scid_T uf_script_ID; /* ID of script where function was defined, used for s: variables */ int uf_refcount; /* for numbered function: reference count */ char_u uf_name[1]; /* name of function (actually longer); can start with <SNR>123_ (<SNR> is K_SPECIAL KS_EXTRA KE_SNR) */ }; /* function flags */ #define FC_ABORT 1 /* abort function on error */ #define FC_RANGE 2 /* function accepts range */ #define FC_DICT 4 /* Dict function, uses "self" */ /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; /* The names of packages that once were loaded are remembered. */ static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL}; /* list heads for garbage collection */ static dict_T *first_dict = NULL; /* list of all dicts */ static list_T *first_list = NULL; /* list of all lists */ /* From user function to hashitem and back. */ static ufunc_T dumuf; #define UF2HIKEY(fp) ((fp)->uf_name) #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf))) #define HI2UF(hi) HIKEY2UF((hi)->hi_key) #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j] #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j] #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */ #define VAR_SHORT_LEN 20 /* short variable name length */ #define FIXVAR_CNT 12 /* number of fixed variables */ /* structure to hold info for a function that is currently being executed. */ typedef struct funccall_S funccall_T; struct funccall_S { ufunc_T *func; /* function being called */ int linenr; /* next line to be executed */ int returned; /* ":return" used */ struct /* fixed variables for arguments */ { dictitem_T var; /* variable (without room for name) */ char_u room[VAR_SHORT_LEN]; /* room for the name */ } fixvar[FIXVAR_CNT]; dict_T l_vars; /* l: local function variables */ dictitem_T l_vars_var; /* variable for l: scope */ dict_T l_avars; /* a: argument variables */ dictitem_T l_avars_var; /* variable for a: scope */ list_T l_varlist; /* list for a:000 */ listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */ typval_T *rettv; /* return value */ linenr_T breakpoint; /* next line with breakpoint or zero */ int dbg_tick; /* debug_tick when breakpoint was set */ int level; /* top nesting level of executed function */ #ifdef FEAT_PROFILE proftime_T prof_child; /* time spent in a child */ #endif funccall_T *caller; /* calling function or NULL */ }; /* * Info used by a ":for" loop. */ typedef struct { int fi_semicolon; /* TRUE if ending in '; var]' */ int fi_varcount; /* nr of variables in the list */ listwatch_T fi_lw; /* keep an eye on the item used. */ list_T *fi_list; /* list being used */ } forinfo_T; /* * Struct used by trans_function_name() */ typedef struct { dict_T *fd_dict; /* Dictionary used */ char_u *fd_newkey; /* new key in "dict" in allocated memory */ dictitem_T *fd_di; /* Dictionary item used */ } funcdict_T; /* * Array to hold the value of v: variables. * The value is in a dictitem, so that it can also be used in the v: scope. * The reason to use this table anyway is for very quick access to the * variables with the VV_ defines. */ #include "version.h" /* values for vv_flags: */ #define VV_COMPAT 1 /* compatible, also used without "v:" */ #define VV_RO 2 /* read-only */ #define VV_RO_SBX 4 /* read-only in the sandbox */ #define VV_NAME(s, t) s, {{t, 0, {0}}, 0, {0}}, {0} static struct vimvar { char *vv_name; /* name of variable, without v: */ dictitem_T vv_di; /* value and name for key */ char vv_filler[16]; /* space for LONGEST name below!!! */ char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */ } vimvars[VV_LEN] = { /* * The order here must match the VV_ defines in vim.h! * Initializing a union does not work, leave tv.vval empty to get zero's. */ {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO}, {VV_NAME("count1", VAR_NUMBER), VV_RO}, {VV_NAME("prevcount", VAR_NUMBER), VV_RO}, {VV_NAME("errmsg", VAR_STRING), VV_COMPAT}, {VV_NAME("warningmsg", VAR_STRING), 0}, {VV_NAME("statusmsg", VAR_STRING), 0}, {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO}, {VV_NAME("this_session", VAR_STRING), VV_COMPAT}, {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO}, {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX}, {VV_NAME("termresponse", VAR_STRING), VV_RO}, {VV_NAME("fname", VAR_STRING), VV_RO}, {VV_NAME("lang", VAR_STRING), VV_RO}, {VV_NAME("lc_time", VAR_STRING), VV_RO}, {VV_NAME("ctype", VAR_STRING), VV_RO}, {VV_NAME("charconvert_from", VAR_STRING), VV_RO}, {VV_NAME("charconvert_to", VAR_STRING), VV_RO}, {VV_NAME("fname_in", VAR_STRING), VV_RO}, {VV_NAME("fname_out", VAR_STRING), VV_RO}, {VV_NAME("fname_new", VAR_STRING), VV_RO}, {VV_NAME("fname_diff", VAR_STRING), VV_RO}, {VV_NAME("cmdarg", VAR_STRING), VV_RO}, {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX}, {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX}, {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX}, {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX}, {VV_NAME("progname", VAR_STRING), VV_RO}, {VV_NAME("servername", VAR_STRING), VV_RO}, {VV_NAME("dying", VAR_NUMBER), VV_RO}, {VV_NAME("exception", VAR_STRING), VV_RO}, {VV_NAME("throwpoint", VAR_STRING), VV_RO}, {VV_NAME("register", VAR_STRING), VV_RO}, {VV_NAME("cmdbang", VAR_NUMBER), VV_RO}, {VV_NAME("insertmode", VAR_STRING), VV_RO}, {VV_NAME("val", VAR_UNKNOWN), VV_RO}, {VV_NAME("key", VAR_UNKNOWN), VV_RO}, {VV_NAME("profiling", VAR_NUMBER), VV_RO}, {VV_NAME("fcs_reason", VAR_STRING), VV_RO}, {VV_NAME("fcs_choice", VAR_STRING), 0}, {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO}, {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO}, {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO}, {VV_NAME("beval_col", VAR_NUMBER), VV_RO}, {VV_NAME("beval_text", VAR_STRING), VV_RO}, {VV_NAME("scrollstart", VAR_STRING), 0}, {VV_NAME("swapname", VAR_STRING), VV_RO}, {VV_NAME("swapchoice", VAR_STRING), 0}, {VV_NAME("swapcommand", VAR_STRING), VV_RO}, {VV_NAME("char", VAR_STRING), 0}, {VV_NAME("mouse_win", VAR_NUMBER), 0}, {VV_NAME("mouse_lnum", VAR_NUMBER), 0}, {VV_NAME("mouse_col", VAR_NUMBER), 0}, {VV_NAME("operator", VAR_STRING), VV_RO}, {VV_NAME("searchforward", VAR_NUMBER), 0}, {VV_NAME("oldfiles", VAR_LIST), 0}, {VV_NAME("windowid", VAR_NUMBER), VV_RO}, }; /* shorthand */ #define vv_type vv_di.di_tv.v_type #define vv_nr vv_di.di_tv.vval.v_number #define vv_float vv_di.di_tv.vval.v_float #define vv_str vv_di.di_tv.vval.v_string #define vv_list vv_di.di_tv.vval.v_list #define vv_tv vv_di.di_tv /* * The v: variables are stored in dictionary "vimvardict". * "vimvars_var" is the variable that is used for the "l:" scope. */ static dict_T vimvardict; static dictitem_T vimvars_var; #define vimvarht vimvardict.dv_hashtab static void prepare_vimvar __ARGS((int idx, typval_T *save_tv)); static void restore_vimvar __ARGS((int idx, typval_T *save_tv)); static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars)); static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon)); static char_u *skip_var_one __ARGS((char_u *arg)); static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first)); static void list_glob_vars __ARGS((int *first)); static void list_buf_vars __ARGS((int *first)); static void list_win_vars __ARGS((int *first)); #ifdef FEAT_WINDOWS static void list_tab_vars __ARGS((int *first)); #endif static void list_vim_vars __ARGS((int *first)); static void list_script_vars __ARGS((int *first)); static void list_func_vars __ARGS((int *first)); static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first)); static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op)); static int check_changedtick __ARGS((char_u *arg)); static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags)); static void clear_lval __ARGS((lval_T *lp)); static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op)); static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op)); static void list_add_watch __ARGS((list_T *l, listwatch_T *lw)); static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem)); static void list_fix_watch __ARGS((list_T *l, listitem_T *item)); static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep)); static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit)); static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock)); static void item_lock __ARGS((typval_T *tv, int deep, int lock)); static int tv_islocked __ARGS((typval_T *tv)); static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate)); static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string)); static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string)); static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose)); static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int rettv_list_alloc __ARGS((typval_T *rettv)); static listitem_T *listitem_alloc __ARGS((void)); static void listitem_free __ARGS((listitem_T *item)); static void listitem_remove __ARGS((list_T *l, listitem_T *item)); static long list_len __ARGS((list_T *l)); static int list_equal __ARGS((list_T *l1, list_T *l2, int ic, int recursive)); static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic, int recursive)); static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic, int recursive)); static listitem_T *list_find __ARGS((list_T *l, long n)); static long list_find_nr __ARGS((list_T *l, long idx, int *errorp)); static long list_idx_of_item __ARGS((list_T *l, listitem_T *item)); static void list_append __ARGS((list_T *l, listitem_T *item)); static int list_append_number __ARGS((list_T *l, varnumber_T n)); static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item)); static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef)); static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv)); static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID)); static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2)); static char_u *list2string __ARGS((typval_T *tv, int copyID)); static int list_join_inner __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo_style, int copyID, garray_T *join_gap)); static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID)); static int free_unref_items __ARGS((int copyID)); static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID)); static void set_ref_in_list __ARGS((list_T *l, int copyID)); static void set_ref_in_item __ARGS((typval_T *tv, int copyID)); static int rettv_dict_alloc __ARGS((typval_T *rettv)); static void dict_free __ARGS((dict_T *d, int recurse)); static dictitem_T *dictitem_copy __ARGS((dictitem_T *org)); static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item)); static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID)); static long dict_len __ARGS((dict_T *d)); static char_u *dict2string __ARGS((typval_T *tv, int copyID)); static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID)); static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID)); static char_u *string_quote __ARGS((char_u *str, int function)); #ifdef FEAT_FLOAT static int string2float __ARGS((char_u *text, float_T *value)); #endif static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate)); static int find_internal_func __ARGS((char_u *name)); static char_u *deref_func_name __ARGS((char_u *name, int *lenp)); static int get_func_tv __ARGS((char_u *name, int len, typval_T *rettv, char_u **arg, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict)); static int call_func __ARGS((char_u *funcname, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict)); static void emsg_funcname __ARGS((char *ermsg, char_u *name)); static int non_zero_arg __ARGS((typval_T *argvars)); #ifdef FEAT_FLOAT static void f_abs __ARGS((typval_T *argvars, typval_T *rettv)); static void f_acos __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_add __ARGS((typval_T *argvars, typval_T *rettv)); static void f_and __ARGS((typval_T *argvars, typval_T *rettv)); static void f_append __ARGS((typval_T *argvars, typval_T *rettv)); static void f_argc __ARGS((typval_T *argvars, typval_T *rettv)); static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv)); static void f_argv __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_asin __ARGS((typval_T *argvars, typval_T *rettv)); static void f_atan __ARGS((typval_T *argvars, typval_T *rettv)); static void f_atan2 __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_browse __ARGS((typval_T *argvars, typval_T *rettv)); static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv)); static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv)); static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv)); static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv)); static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv)); static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv)); static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv)); static void f_call __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv)); static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv)); static void f_col __ARGS((typval_T *argvars, typval_T *rettv)); #if defined(FEAT_INS_EXPAND) static void f_complete __ARGS((typval_T *argvars, typval_T *rettv)); static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv)); static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv)); static void f_copy __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_cos __ARGS((typval_T *argvars, typval_T *rettv)); static void f_cosh __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_count __ARGS((typval_T *argvars, typval_T *rettv)); static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv)); static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv)); static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv)); static void f_delete __ARGS((typval_T *argvars, typval_T *rettv)); static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv)); static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv)); static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv)); static void f_empty __ARGS((typval_T *argvars, typval_T *rettv)); static void f_escape __ARGS((typval_T *argvars, typval_T *rettv)); static void f_eval __ARGS((typval_T *argvars, typval_T *rettv)); static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv)); static void f_executable __ARGS((typval_T *argvars, typval_T *rettv)); static void f_exists __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_exp __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_expand __ARGS((typval_T *argvars, typval_T *rettv)); static void f_extend __ARGS((typval_T *argvars, typval_T *rettv)); static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv)); static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv)); static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv)); static void f_filter __ARGS((typval_T *argvars, typval_T *rettv)); static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv)); static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_floor __ARGS((typval_T *argvars, typval_T *rettv)); static void f_fmod __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv)); static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv)); static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv)); static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv)); static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv)); static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv)); static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv)); static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv)); static void f_function __ARGS((typval_T *argvars, typval_T *rettv)); static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv)); static void f_get __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getline __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv)); static void f_gettabvar __ARGS((typval_T *argvars, typval_T *rettv)); static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv)); static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv)); static void f_glob __ARGS((typval_T *argvars, typval_T *rettv)); static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv)); static void f_has __ARGS((typval_T *argvars, typval_T *rettv)); static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv)); static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv)); static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv)); static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv)); static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv)); static void f_histget __ARGS((typval_T *argvars, typval_T *rettv)); static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv)); static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv)); static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv)); static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv)); static void f_indent __ARGS((typval_T *argvars, typval_T *rettv)); static void f_index __ARGS((typval_T *argvars, typval_T *rettv)); static void f_input __ARGS((typval_T *argvars, typval_T *rettv)); static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv)); static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv)); static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv)); static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv)); static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv)); static void f_insert __ARGS((typval_T *argvars, typval_T *rettv)); static void f_invert __ARGS((typval_T *argvars, typval_T *rettv)); static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv)); static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv)); static void f_items __ARGS((typval_T *argvars, typval_T *rettv)); static void f_join __ARGS((typval_T *argvars, typval_T *rettv)); static void f_keys __ARGS((typval_T *argvars, typval_T *rettv)); static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_len __ARGS((typval_T *argvars, typval_T *rettv)); static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv)); static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_line __ARGS((typval_T *argvars, typval_T *rettv)); static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv)); static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv)); static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_log __ARGS((typval_T *argvars, typval_T *rettv)); static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv)); #endif #ifdef FEAT_LUA static void f_luaeval __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_map __ARGS((typval_T *argvars, typval_T *rettv)); static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv)); static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv)); static void f_match __ARGS((typval_T *argvars, typval_T *rettv)); static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv)); static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv)); static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv)); static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv)); static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv)); static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_max __ARGS((typval_T *argvars, typval_T *rettv)); static void f_min __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef vim_mkdir static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_mode __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_MZSCHEME static void f_mzeval __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv)); static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv)); static void f_or __ARGS((typval_T *argvars, typval_T *rettv)); static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_pow __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv)); static void f_printf __ARGS((typval_T *argvars, typval_T *rettv)); static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv)); static void f_range __ARGS((typval_T *argvars, typval_T *rettv)); static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv)); static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv)); static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv)); static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv)); static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv)); static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv)); static void f_remove __ARGS((typval_T *argvars, typval_T *rettv)); static void f_rename __ARGS((typval_T *argvars, typval_T *rettv)); static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv)); static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv)); static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_round __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_search __ARGS((typval_T *argvars, typval_T *rettv)); static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv)); static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv)); static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv)); static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv)); static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv)); static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv)); static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv)); static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv)); static void f_setline __ARGS((typval_T *argvars, typval_T *rettv)); static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv)); static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv)); static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv)); static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv)); static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv)); static void f_settabvar __ARGS((typval_T *argvars, typval_T *rettv)); static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv)); static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv)); static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv)); static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_sin __ARGS((typval_T *argvars, typval_T *rettv)); static void f_sinh __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_sort __ARGS((typval_T *argvars, typval_T *rettv)); static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv)); static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv)); static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv)); static void f_split __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv)); static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_strchars __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef HAVE_STRFTIME static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv)); static void f_string __ARGS((typval_T *argvars, typval_T *rettv)); static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv)); static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv)); static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv)); static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv)); static void f_strdisplaywidth __ARGS((typval_T *argvars, typval_T *rettv)); static void f_strwidth __ARGS((typval_T *argvars, typval_T *rettv)); static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv)); static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv)); static void f_synID __ARGS((typval_T *argvars, typval_T *rettv)); static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv)); static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv)); static void f_synconcealed __ARGS((typval_T *argvars, typval_T *rettv)); static void f_system __ARGS((typval_T *argvars, typval_T *rettv)); static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv)); static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv)); static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv)); static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv)); static void f_test __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_tan __ARGS((typval_T *argvars, typval_T *rettv)); static void f_tanh __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv)); static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv)); static void f_tr __ARGS((typval_T *argvars, typval_T *rettv)); #ifdef FEAT_FLOAT static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv)); #endif static void f_type __ARGS((typval_T *argvars, typval_T *rettv)); static void f_undofile __ARGS((typval_T *argvars, typval_T *rettv)); static void f_undotree __ARGS((typval_T *argvars, typval_T *rettv)); static void f_values __ARGS((typval_T *argvars, typval_T *rettv)); static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv)); static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv)); static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv)); static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv)); static void f_winline __ARGS((typval_T *argvars, typval_T *rettv)); static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv)); static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv)); static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv)); static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv)); static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv)); static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv)); static void f_xor __ARGS((typval_T *argvars, typval_T *rettv)); static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump)); static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum)); static int get_env_len __ARGS((char_u **arg)); static int get_id_len __ARGS((char_u **arg)); static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose)); static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags)); #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */ #define FNE_CHECK_START 2 /* find_name_end(): check name starts with valid character */ static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end)); static int eval_isnamec __ARGS((int c)); static int eval_isnamec1 __ARGS((int c)); static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose)); static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose)); static typval_T *alloc_tv __ARGS((void)); static typval_T *alloc_string_tv __ARGS((char_u *string)); static void init_tv __ARGS((typval_T *varp)); static long get_tv_number __ARGS((typval_T *varp)); static linenr_T get_tv_lnum __ARGS((typval_T *argvars)); static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf)); static char_u *get_tv_string __ARGS((typval_T *varp)); static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf)); static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf)); static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp)); static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing)); static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname)); static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val)); static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi)); static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first)); static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first)); static void set_var __ARGS((char_u *name, typval_T *varp, int copy)); static int var_check_ro __ARGS((int flags, char_u *name)); static int var_check_fixed __ARGS((int flags, char_u *name)); static int var_check_func_name __ARGS((char_u *name, int new_var)); static int valid_varname __ARGS((char_u *varname)); static int tv_check_lock __ARGS((int lock, char_u *name)); static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID)); static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags)); static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd)); static int eval_fname_script __ARGS((char_u *p)); static int eval_fname_sid __ARGS((char_u *p)); static void list_func_head __ARGS((ufunc_T *fp, int indent)); static ufunc_T *find_func __ARGS((char_u *name)); static int function_exists __ARGS((char_u *name)); static int builtin_function __ARGS((char_u *name)); #ifdef FEAT_PROFILE static void func_do_profile __ARGS((ufunc_T *fp)); static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self)); static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self)); static int # ifdef __BORLANDC__ _RTLENTRYF # endif prof_total_cmp __ARGS((const void *s1, const void *s2)); static int # ifdef __BORLANDC__ _RTLENTRYF # endif prof_self_cmp __ARGS((const void *s1, const void *s2)); #endif static int script_autoload __ARGS((char_u *name, int reload)); static char_u *autoload_name __ARGS((char_u *name)); static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp)); static void func_free __ARGS((ufunc_T *fp)); static void func_unref __ARGS((char_u *name)); static void func_ref __ARGS((char_u *name)); static void call_user_func __ARGS((ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, linenr_T firstline, linenr_T lastline, dict_T *selfdict)); static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ; static void free_funccal __ARGS((funccall_T *fc, int free_val)); static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr)); static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp)); static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off)); static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos)); static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp)); static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off)); #ifdef EBCDIC static int compare_func_name __ARGS((const void *s1, const void *s2)); static void sortFunctions __ARGS(()); #endif /* Character used as separated in autoload function/variable names. */ #define AUTOLOAD_CHAR '#' /* * Initialize the global and v: variables. */ void eval_init() { int i; struct vimvar *p; init_var_dict(&globvardict, &globvars_var); init_var_dict(&vimvardict, &vimvars_var); vimvardict.dv_lock = VAR_FIXED; hash_init(&compat_hashtab); hash_init(&func_hashtab); for (i = 0; i < VV_LEN; ++i) { p = &vimvars[i]; STRCPY(p->vv_di.di_key, p->vv_name); if (p->vv_flags & VV_RO) p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; else if (p->vv_flags & VV_RO_SBX) p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX; else p->vv_di.di_flags = DI_FLAGS_FIX; /* add to v: scope dict, unless the value is not always available */ if (p->vv_type != VAR_UNKNOWN) hash_add(&vimvarht, p->vv_di.di_key); if (p->vv_flags & VV_COMPAT) /* add to compat scope dict */ hash_add(&compat_hashtab, p->vv_di.di_key); } set_vim_var_nr(VV_SEARCHFORWARD, 1L); set_reg_var(0); /* default for v:register is not 0 but '"' */ #ifdef EBCDIC /* * Sort the function table, to enable binary search. */ sortFunctions(); #endif } #if defined(EXITFREE) || defined(PROTO) void eval_clear() { int i; struct vimvar *p; for (i = 0; i < VV_LEN; ++i) { p = &vimvars[i]; if (p->vv_di.di_tv.v_type == VAR_STRING) { vim_free(p->vv_str); p->vv_str = NULL; } else if (p->vv_di.di_tv.v_type == VAR_LIST) { list_unref(p->vv_list); p->vv_list = NULL; } } hash_clear(&vimvarht); hash_init(&vimvarht); /* garbage_collect() will access it */ hash_clear(&compat_hashtab); free_scriptnames(); free_locales(); /* global variables */ vars_clear(&globvarht); /* autoloaded script names */ ga_clear_strings(&ga_loaded); /* script-local variables */ for (i = 1; i <= ga_scripts.ga_len; ++i) { vars_clear(&SCRIPT_VARS(i)); vim_free(SCRIPT_SV(i)); } ga_clear(&ga_scripts); /* unreferenced lists and dicts */ (void)garbage_collect(); /* functions */ free_all_functions(); hash_clear(&func_hashtab); } #endif /* * Return the name of the executed function. */ char_u * func_name(cookie) void *cookie; { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(cookie) void *cookie; { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(cookie) void *cookie; { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(cookie) void *cookie; { return ((funccall_T *)cookie)->level; } /* pointer to funccal for currently active function */ funccall_T *current_funccal = NULL; /* pointer to list of previously used funccal, still around because some * item in it is still being used. */ funccall_T *previous_funccal = NULL; /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned() { return current_funccal->returned; } /* * Set an internal variable to a string value. Creates the variable if it does * not already exist. */ void set_internal_string_var(name, value) char_u *name; char_u *value; { char_u *val; typval_T *tvp; val = vim_strsave(value); if (val != NULL) { tvp = alloc_string_tv(val); if (tvp != NULL) { set_var(name, tvp, FALSE); free_tv(tvp); } } } static lval_T *redir_lval = NULL; static garray_T redir_ga; /* only valid when redir_lval is not NULL */ static char_u *redir_endp = NULL; static char_u *redir_varname = NULL; /* * Start recording command output to a variable * Returns OK if successfully completed the setup. FAIL otherwise. */ int var_redir_start(name, append) char_u *name; int append; /* append to an existing variable */ { int save_emsg; int err; typval_T tv; /* Catch a bad name early. */ if (!eval_isnamec1(*name)) { EMSG(_(e_invarg)); return FAIL; } /* Make a copy of the name, it is used in redir_lval until redir ends. */ redir_varname = vim_strsave(name); if (redir_varname == NULL) return FAIL; redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T)); if (redir_lval == NULL) { var_redir_stop(); return FAIL; } /* The output is stored in growarray "redir_ga" until redirection ends. */ ga_init2(&redir_ga, (int)sizeof(char), 500); /* Parse the variable name (can be a dict or list entry). */ redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE, FNE_CHECK_START); if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL) { clear_lval(redir_lval); if (redir_endp != NULL && *redir_endp != NUL) /* Trailing characters are present after the variable name */ EMSG(_(e_trailing)); else EMSG(_(e_invarg)); redir_endp = NULL; /* don't store a value, only cleanup */ var_redir_stop(); return FAIL; } /* check if we can write to the variable: set it to or append an empty * string */ save_emsg = did_emsg; did_emsg = FALSE; tv.v_type = VAR_STRING; tv.vval.v_string = (char_u *)""; if (append) set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"."); else set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"="); clear_lval(redir_lval); err = did_emsg; did_emsg |= save_emsg; if (err) { redir_endp = NULL; /* don't store a value, only cleanup */ var_redir_stop(); return FAIL; } return OK; } /* * Append "value[value_len]" to the variable set by var_redir_start(). * The actual appending is postponed until redirection ends, because the value * appended may in fact be the string we write to, changing it may cause freed * memory to be used: * :redir => foo * :let foo * :redir END */ void var_redir_str(value, value_len) char_u *value; int value_len; { int len; if (redir_lval == NULL) return; if (value_len == -1) len = (int)STRLEN(value); /* Append the entire string */ else len = value_len; /* Append only "value_len" characters */ if (ga_grow(&redir_ga, len) == OK) { mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len); redir_ga.ga_len += len; } else var_redir_stop(); } /* * Stop redirecting command output to a variable. * Frees the allocated memory. */ void var_redir_stop() { typval_T tv; if (redir_lval != NULL) { /* If there was no error: assign the text to the variable. */ if (redir_endp != NULL) { ga_append(&redir_ga, NUL); /* Append the trailing NUL. */ tv.v_type = VAR_STRING; tv.vval.v_string = redir_ga.ga_data; /* Call get_lval() again, if it's inside a Dict or List it may * have changed. */ redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE, FNE_CHECK_START); if (redir_endp != NULL && redir_lval->ll_name != NULL) set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)"."); clear_lval(redir_lval); } /* free the collected output */ vim_free(redir_ga.ga_data); redir_ga.ga_data = NULL; vim_free(redir_lval); redir_lval = NULL; } vim_free(redir_varname); redir_varname = NULL; } # if defined(FEAT_MBYTE) || defined(PROTO) int eval_charconvert(enc_from, enc_to, fname_from, fname_to) char_u *enc_from; char_u *enc_to; char_u *fname_from; char_u *fname_to; { int err = FALSE; set_vim_var_string(VV_CC_FROM, enc_from, -1); set_vim_var_string(VV_CC_TO, enc_to, -1); set_vim_var_string(VV_FNAME_IN, fname_from, -1); set_vim_var_string(VV_FNAME_OUT, fname_to, -1); if (eval_to_bool(p_ccv, &err, NULL, FALSE)) err = TRUE; set_vim_var_string(VV_CC_FROM, NULL, -1); set_vim_var_string(VV_CC_TO, NULL, -1); set_vim_var_string(VV_FNAME_IN, NULL, -1); set_vim_var_string(VV_FNAME_OUT, NULL, -1); if (err) return FAIL; return OK; } # endif # if defined(FEAT_POSTSCRIPT) || defined(PROTO) int eval_printexpr(fname, args) char_u *fname; char_u *args; { int err = FALSE; set_vim_var_string(VV_FNAME_IN, fname, -1); set_vim_var_string(VV_CMDARG, args, -1); if (eval_to_bool(p_pexpr, &err, NULL, FALSE)) err = TRUE; set_vim_var_string(VV_FNAME_IN, NULL, -1); set_vim_var_string(VV_CMDARG, NULL, -1); if (err) { mch_remove(fname); return FAIL; } return OK; } # endif # if defined(FEAT_DIFF) || defined(PROTO) void eval_diff(origfile, newfile, outfile) char_u *origfile; char_u *newfile; char_u *outfile; { int err = FALSE; set_vim_var_string(VV_FNAME_IN, origfile, -1); set_vim_var_string(VV_FNAME_NEW, newfile, -1); set_vim_var_string(VV_FNAME_OUT, outfile, -1); (void)eval_to_bool(p_dex, &err, NULL, FALSE); set_vim_var_string(VV_FNAME_IN, NULL, -1); set_vim_var_string(VV_FNAME_NEW, NULL, -1); set_vim_var_string(VV_FNAME_OUT, NULL, -1); } void eval_patch(origfile, difffile, outfile) char_u *origfile; char_u *difffile; char_u *outfile; { int err; set_vim_var_string(VV_FNAME_IN, origfile, -1); set_vim_var_string(VV_FNAME_DIFF, difffile, -1); set_vim_var_string(VV_FNAME_OUT, outfile, -1); (void)eval_to_bool(p_pex, &err, NULL, FALSE); set_vim_var_string(VV_FNAME_IN, NULL, -1); set_vim_var_string(VV_FNAME_DIFF, NULL, -1); set_vim_var_string(VV_FNAME_OUT, NULL, -1); } # endif /* * Top level evaluation function, returning a boolean. * Sets "error" to TRUE if there was an error. * Return TRUE or FALSE. */ int eval_to_bool(arg, error, nextcmd, skip) char_u *arg; int *error; char_u **nextcmd; int skip; /* only parse, don't execute */ { typval_T tv; int retval = FALSE; if (skip) ++emsg_skip; if (eval0(arg, &tv, nextcmd, !skip) == FAIL) *error = TRUE; else { *error = FALSE; if (!skip) { retval = (get_tv_number_chk(&tv, error) != 0); clear_tv(&tv); } } if (skip) --emsg_skip; return retval; } /* * Top level evaluation function, returning a string. If "skip" is TRUE, * only parsing to "nextcmd" is done, without reporting errors. Return * pointer to allocated memory, or NULL for failure or when "skip" is TRUE. */ char_u * eval_to_string_skip(arg, nextcmd, skip) char_u *arg; char_u **nextcmd; int skip; /* only parse, don't execute */ { typval_T tv; char_u *retval; if (skip) ++emsg_skip; if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip) retval = NULL; else { retval = vim_strsave(get_tv_string(&tv)); clear_tv(&tv); } if (skip) --emsg_skip; return retval; } /* * Skip over an expression at "*pp". * Return FAIL for an error, OK otherwise. */ int skip_expr(pp) char_u **pp; { typval_T rettv; *pp = skipwhite(*pp); return eval1(pp, &rettv, FALSE); } /* * Top level evaluation function, returning a string. * When "convert" is TRUE convert a List into a sequence of lines and convert * a Float to a String. * Return pointer to allocated memory, or NULL for failure. */ char_u * eval_to_string(arg, nextcmd, convert) char_u *arg; char_u **nextcmd; int convert; { typval_T tv; char_u *retval; garray_T ga; #ifdef FEAT_FLOAT char_u numbuf[NUMBUFLEN]; #endif if (eval0(arg, &tv, nextcmd, TRUE) == FAIL) retval = NULL; else { if (convert && tv.v_type == VAR_LIST) { ga_init2(&ga, (int)sizeof(char), 80); if (tv.vval.v_list != NULL) { list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0); if (tv.vval.v_list->lv_len > 0) ga_append(&ga, NL); } ga_append(&ga, NUL); retval = (char_u *)ga.ga_data; } #ifdef FEAT_FLOAT else if (convert && tv.v_type == VAR_FLOAT) { vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float); retval = vim_strsave(numbuf); } #endif else retval = vim_strsave(get_tv_string(&tv)); clear_tv(&tv); } return retval; } /* * Call eval_to_string() without using current local variables and using * textlock. When "use_sandbox" is TRUE use the sandbox. */ char_u * eval_to_string_safe(arg, nextcmd, use_sandbox) char_u *arg; char_u **nextcmd; int use_sandbox; { char_u *retval; void *save_funccalp; save_funccalp = save_funccal(); if (use_sandbox) ++sandbox; ++textlock; retval = eval_to_string(arg, nextcmd, FALSE); if (use_sandbox) --sandbox; --textlock; restore_funccal(save_funccalp); return retval; } /* * Top level evaluation function, returning a number. * Evaluates "expr" silently. * Returns -1 for an error. */ int eval_to_number(expr) char_u *expr; { typval_T rettv; int retval; char_u *p = skipwhite(expr); ++emsg_off; if (eval1(&p, &rettv, TRUE) == FAIL) retval = -1; else { retval = get_tv_number_chk(&rettv, NULL); clear_tv(&rettv); } --emsg_off; return retval; } /* * Prepare v: variable "idx" to be used. * Save the current typeval in "save_tv". * When not used yet add the variable to the v: hashtable. */ static void prepare_vimvar(idx, save_tv) int idx; typval_T *save_tv; { *save_tv = vimvars[idx].vv_tv; if (vimvars[idx].vv_type == VAR_UNKNOWN) hash_add(&vimvarht, vimvars[idx].vv_di.di_key); } /* * Restore v: variable "idx" to typeval "save_tv". * When no longer defined, remove the variable from the v: hashtable. */ static void restore_vimvar(idx, save_tv) int idx; typval_T *save_tv; { hashitem_T *hi; vimvars[idx].vv_tv = *save_tv; if (vimvars[idx].vv_type == VAR_UNKNOWN) { hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key); if (HASHITEM_EMPTY(hi)) EMSG2(_(e_intern2), "restore_vimvar()"); else hash_remove(&vimvarht, hi); } } #if defined(FEAT_SPELL) || defined(PROTO) /* * Evaluate an expression to a list with suggestions. * For the "expr:" part of 'spellsuggest'. * Returns NULL when there is an error. */ list_T * eval_spell_expr(badword, expr) char_u *badword; char_u *expr; { typval_T save_val; typval_T rettv; list_T *list = NULL; char_u *p = skipwhite(expr); /* Set "v:val" to the bad word. */ prepare_vimvar(VV_VAL, &save_val); vimvars[VV_VAL].vv_type = VAR_STRING; vimvars[VV_VAL].vv_str = badword; if (p_verbose == 0) ++emsg_off; if (eval1(&p, &rettv, TRUE) == OK) { if (rettv.v_type != VAR_LIST) clear_tv(&rettv); else list = rettv.vval.v_list; } if (p_verbose == 0) --emsg_off; restore_vimvar(VV_VAL, &save_val); return list; } /* * "list" is supposed to contain two items: a word and a number. Return the * word in "pp" and the number as the return value. * Return -1 if anything isn't right. * Used to get the good word and score from the eval_spell_expr() result. */ int get_spellword(list, pp) list_T *list; char_u **pp; { listitem_T *li; li = list->lv_first; if (li == NULL) return -1; *pp = get_tv_string(&li->li_tv); li = li->li_next; if (li == NULL) return -1; return get_tv_number(&li->li_tv); } #endif /* * Top level evaluation function. * Returns an allocated typval_T with the result. * Returns NULL when there is an error. */ typval_T * eval_expr(arg, nextcmd) char_u *arg; char_u **nextcmd; { typval_T *tv; tv = (typval_T *)alloc(sizeof(typval_T)); if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL) { vim_free(tv); tv = NULL; } return tv; } #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \ || defined(FEAT_COMPL_FUNC) || defined(PROTO) /* * Call some vimL function and return the result in "*rettv". * Uses argv[argc] for the function arguments. Only Number and String * arguments are currently supported. * Returns OK or FAIL. */ int call_vim_function(func, argc, argv, safe, rettv) char_u *func; int argc; char_u **argv; int safe; /* use the sandbox */ typval_T *rettv; { typval_T *argvars; long n; int len; int i; int doesrange; void *save_funccalp = NULL; int ret; argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T))); if (argvars == NULL) return FAIL; for (i = 0; i < argc; i++) { /* Pass a NULL or empty argument as an empty string */ if (argv[i] == NULL || *argv[i] == NUL) { argvars[i].v_type = VAR_STRING; argvars[i].vval.v_string = (char_u *)""; continue; } /* Recognize a number argument, the others must be strings. */ vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL); if (len != 0 && len == (int)STRLEN(argv[i])) { argvars[i].v_type = VAR_NUMBER; argvars[i].vval.v_number = n; } else { argvars[i].v_type = VAR_STRING; argvars[i].vval.v_string = argv[i]; } } if (safe) { save_funccalp = save_funccal(); ++sandbox; } rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */ ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars, curwin->w_cursor.lnum, curwin->w_cursor.lnum, &doesrange, TRUE, NULL); if (safe) { --sandbox; restore_funccal(save_funccalp); } vim_free(argvars); if (ret == FAIL) clear_tv(rettv); return ret; } # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO) /* * Call vimL function "func" and return the result as a string. * Returns NULL when calling the function fails. * Uses argv[argc] for the function arguments. */ void * call_func_retstr(func, argc, argv, safe) char_u *func; int argc; char_u **argv; int safe; /* use the sandbox */ { typval_T rettv; char_u *retval; if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL) return NULL; retval = vim_strsave(get_tv_string(&rettv)); clear_tv(&rettv); return retval; } # endif # if defined(FEAT_COMPL_FUNC) || defined(PROTO) /* * Call vimL function "func" and return the result as a number. * Returns -1 when calling the function fails. * Uses argv[argc] for the function arguments. */ long call_func_retnr(func, argc, argv, safe) char_u *func; int argc; char_u **argv; int safe; /* use the sandbox */ { typval_T rettv; long retval; if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL) return -1; retval = get_tv_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } # endif /* * Call vimL function "func" and return the result as a List. * Uses argv[argc] for the function arguments. * Returns NULL when there is something wrong. */ void * call_func_retlist(func, argc, argv, safe) char_u *func; int argc; char_u **argv; int safe; /* use the sandbox */ { typval_T rettv; if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL) return NULL; if (rettv.v_type != VAR_LIST) { clear_tv(&rettv); return NULL; } return rettv.vval.v_list; } #endif /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void * save_funccal() { funccall_T *fc = current_funccal; current_funccal = NULL; return (void *)fc; } void restore_funccal(vfc) void *vfc; { funccall_T *fc = (funccall_T *)vfc; current_funccal = fc; } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Prepare profiling for entering a child or something else that is not * counted for the script/function itself. * Should always be called in pair with prof_child_exit(). */ void prof_child_enter(tm) proftime_T *tm; /* place to store waittime */ { funccall_T *fc = current_funccal; if (fc != NULL && fc->func->uf_profiling) profile_start(&fc->prof_child); script_prof_save(tm); } /* * Take care of time spent in a child. * Should always be called after prof_child_enter(). */ void prof_child_exit(tm) proftime_T *tm; /* where waittime was stored */ { funccall_T *fc = current_funccal; if (fc != NULL && fc->func->uf_profiling) { profile_end(&fc->prof_child); profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */ profile_add(&fc->func->uf_tm_children, &fc->prof_child); profile_add(&fc->func->uf_tml_children, &fc->prof_child); } script_prof_restore(tm); } #endif #ifdef FEAT_FOLDING /* * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding * it in "*cp". Doesn't give error messages. */ int eval_foldexpr(arg, cp) char_u *arg; int *cp; { typval_T tv; int retval; char_u *s; int use_sandbox = was_set_insecurely((char_u *)"foldexpr", OPT_LOCAL); ++emsg_off; if (use_sandbox) ++sandbox; ++textlock; *cp = NUL; if (eval0(arg, &tv, NULL, TRUE) == FAIL) retval = 0; else { /* If the result is a number, just return the number. */ if (tv.v_type == VAR_NUMBER) retval = tv.vval.v_number; else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL) retval = 0; else { /* If the result is a string, check if there is a non-digit before * the number. */ s = tv.vval.v_string; if (!VIM_ISDIGIT(*s) && *s != '-') *cp = *s++; retval = atol((char *)s); } clear_tv(&tv); } --emsg_off; if (use_sandbox) --sandbox; --textlock; return retval; } #endif /* * ":let" list all variable values * ":let var1 var2" list variable values * ":let var = expr" assignment command. * ":let var += expr" assignment command. * ":let var -= expr" assignment command. * ":let var .= expr" assignment command. * ":let [var1, var2] = expr" unpack list. */ void ex_let(eap) exarg_T *eap; { char_u *arg = eap->arg; char_u *expr = NULL; typval_T rettv; int i; int var_count = 0; int semicolon = 0; char_u op[2]; char_u *argend; int first = TRUE; argend = skip_var_list(arg, &var_count, &semicolon); if (argend == NULL) return; if (argend > arg && argend[-1] == '.') /* for var.='str' */ --argend; expr = vim_strchr(argend, '='); if (expr == NULL) { /* * ":let" without "=": list variables */ if (*arg == '[') EMSG(_(e_invarg)); else if (!ends_excmd(*arg)) /* ":let var1 var2" */ arg = list_arg_vars(eap, arg, &first); else if (!eap->skip) { /* ":let" */ list_glob_vars(&first); list_buf_vars(&first); list_win_vars(&first); #ifdef FEAT_WINDOWS list_tab_vars(&first); #endif list_script_vars(&first); list_func_vars(&first); list_vim_vars(&first); } eap->nextcmd = check_nextcmd(arg); } else { op[0] = '='; op[1] = NUL; if (expr > argend) { if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL) op[0] = expr[-1]; /* +=, -= or .= */ } expr = skipwhite(expr + 1); if (eap->skip) ++emsg_skip; i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip); if (eap->skip) { if (i != FAIL) clear_tv(&rettv); --emsg_skip; } else if (i != FAIL) { (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count, op); clear_tv(&rettv); } } } /* * Assign the typevalue "tv" to the variable or variables at "arg_start". * Handles both "var" with any type and "[var, var; var]" with a list type. * When "nextchars" is not NULL it points to a string with characters that * must appear after the variable(s). Use "+", "-" or "." for add, subtract * or concatenate. * Returns OK or FAIL; */ static int ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars) char_u *arg_start; typval_T *tv; int copy; /* copy values from "tv", don't move */ int semicolon; /* from skip_var_list() */ int var_count; /* from skip_var_list() */ char_u *nextchars; { char_u *arg = arg_start; list_T *l; int i; listitem_T *item; typval_T ltv; if (*arg != '[') { /* * ":let var = expr" or ":for var in list" */ if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL) return FAIL; return OK; } /* * ":let [v1, v2] = list" or ":for [v1, v2] in listlist" */ if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL) { EMSG(_(e_listreq)); return FAIL; } i = list_len(l); if (semicolon == 0 && var_count < i) { EMSG(_("E687: Less targets than List items")); return FAIL; } if (var_count - semicolon > i) { EMSG(_("E688: More targets than List items")); return FAIL; } item = l->lv_first; while (*arg != ']') { arg = skipwhite(arg + 1); arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars); item = item->li_next; if (arg == NULL) return FAIL; arg = skipwhite(arg); if (*arg == ';') { /* Put the rest of the list (may be empty) in the var after ';'. * Create a new list for this. */ l = list_alloc(); if (l == NULL) return FAIL; while (item != NULL) { list_append_tv(l, &item->li_tv); item = item->li_next; } ltv.v_type = VAR_LIST; ltv.v_lock = 0; ltv.vval.v_list = l; l->lv_refcount = 1; arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE, (char_u *)"]", nextchars); clear_tv(&ltv); if (arg == NULL) return FAIL; break; } else if (*arg != ',' && *arg != ']') { EMSG2(_(e_intern2), "ex_let_vars()"); return FAIL; } } return OK; } /* * Skip over assignable variable "var" or list of variables "[var, var]". * Used for ":let varvar = expr" and ":for varvar in expr". * For "[var, var]" increment "*var_count" for each variable. * for "[var, var; var]" set "semicolon". * Return NULL for an error. */ static char_u * skip_var_list(arg, var_count, semicolon) char_u *arg; int *var_count; int *semicolon; { char_u *p, *s; if (*arg == '[') { /* "[var, var]": find the matching ']'. */ p = arg; for (;;) { p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */ s = skip_var_one(p); if (s == p) { EMSG2(_(e_invarg2), p); return NULL; } ++*var_count; p = skipwhite(s); if (*p == ']') break; else if (*p == ';') { if (*semicolon == 1) { EMSG(_("Double ; in list of variables")); return NULL; } *semicolon = 1; } else if (*p != ',') { EMSG2(_(e_invarg2), p); return NULL; } } return p + 1; } else return skip_var_one(arg); } /* * Skip one (assignable) variable name, including @r, $VAR, &option, d.key, * l[idx]. */ static char_u * skip_var_one(arg) char_u *arg; { if (*arg == '@' && arg[1] != NUL) return arg + 2; return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START); } /* * List variables for hashtab "ht" with prefix "prefix". * If "empty" is TRUE also list NULL strings as empty strings. */ static void list_hashtable_vars(ht, prefix, empty, first) hashtab_T *ht; char_u *prefix; int empty; int *first; { hashitem_T *hi; dictitem_T *di; int todo; todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); if (empty || di->di_tv.v_type != VAR_STRING || di->di_tv.vval.v_string != NULL) list_one_var(di, prefix, first); } } } /* * List global variables. */ static void list_glob_vars(first) int *first; { list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first); } /* * List buffer variables. */ static void list_buf_vars(first) int *first; { char_u numbuf[NUMBUFLEN]; list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:", TRUE, first); sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick); list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER, numbuf, first); } /* * List window variables. */ static void list_win_vars(first) int *first; { list_hashtable_vars(&curwin->w_vars.dv_hashtab, (char_u *)"w:", TRUE, first); } #ifdef FEAT_WINDOWS /* * List tab page variables. */ static void list_tab_vars(first) int *first; { list_hashtable_vars(&curtab->tp_vars.dv_hashtab, (char_u *)"t:", TRUE, first); } #endif /* * List Vim variables. */ static void list_vim_vars(first) int *first; { list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first); } /* * List script-local variables, if there is a script. */ static void list_script_vars(first) int *first; { if (current_SID > 0 && current_SID <= ga_scripts.ga_len) list_hashtable_vars(&SCRIPT_VARS(current_SID), (char_u *)"s:", FALSE, first); } /* * List function variables, if there is a function. */ static void list_func_vars(first) int *first; { if (current_funccal != NULL) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, (char_u *)"l:", FALSE, first); } /* * List variables in "arg". */ static char_u * list_arg_vars(eap, arg, first) exarg_T *eap; char_u *arg; int *first; { int error = FALSE; int len; char_u *name; char_u *name_start; char_u *arg_subsc; char_u *tofree; typval_T tv; while (!ends_excmd(*arg) && !got_int) { if (error || eap->skip) { arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START); if (!vim_iswhite(*arg) && !ends_excmd(*arg)) { emsg_severe = TRUE; EMSG(_(e_trailing)); break; } } else { /* get_name_len() takes care of expanding curly braces */ name_start = name = arg; len = get_name_len(&arg, &tofree, TRUE, TRUE); if (len <= 0) { /* This is mainly to keep test 49 working: when expanding * curly braces fails overrule the exception error message. */ if (len < 0 && !aborting()) { emsg_severe = TRUE; EMSG2(_(e_invarg2), arg); break; } error = TRUE; } else { if (tofree != NULL) name = tofree; if (get_var_tv(name, len, &tv, TRUE) == FAIL) error = TRUE; else { /* handle d.key, l[idx], f(expr) */ arg_subsc = arg; if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL) error = TRUE; else { if (arg == arg_subsc && len == 2 && name[1] == ':') { switch (*name) { case 'g': list_glob_vars(first); break; case 'b': list_buf_vars(first); break; case 'w': list_win_vars(first); break; #ifdef FEAT_WINDOWS case 't': list_tab_vars(first); break; #endif case 'v': list_vim_vars(first); break; case 's': list_script_vars(first); break; case 'l': list_func_vars(first); break; default: EMSG2(_("E738: Can't list variables for %s"), name); } } else { char_u numbuf[NUMBUFLEN]; char_u *tf; int c; char_u *s; s = echo_string(&tv, &tf, numbuf, 0); c = *arg; *arg = NUL; list_one_var_a((char_u *)"", arg == arg_subsc ? name : name_start, tv.v_type, s == NULL ? (char_u *)"" : s, first); *arg = c; vim_free(tf); } clear_tv(&tv); } } } vim_free(tofree); } arg = skipwhite(arg); } return arg; } /* * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value. * Returns a pointer to the char just after the var name. * Returns NULL if there is an error. */ static char_u * ex_let_one(arg, tv, copy, endchars, op) char_u *arg; /* points to variable name */ typval_T *tv; /* value to assign to variable */ int copy; /* copy value from "tv" */ char_u *endchars; /* valid chars after variable name or NULL */ char_u *op; /* "+", "-", "." or NULL*/ { int c1; char_u *name; char_u *p; char_u *arg_end = NULL; int len; int opt_flags; char_u *tofree = NULL; /* * ":let $VAR = expr": Set environment variable. */ if (*arg == '$') { /* Find the end of the name. */ ++arg; name = arg; len = get_env_len(&arg); if (len == 0) EMSG2(_(e_invarg2), name - 1); else { if (op != NULL && (*op == '+' || *op == '-')) EMSG2(_(e_letwrong), op); else if (endchars != NULL && vim_strchr(endchars, *skipwhite(arg)) == NULL) EMSG(_(e_letunexp)); else if (!check_secure()) { c1 = name[len]; name[len] = NUL; p = get_tv_string_chk(tv); if (p != NULL && op != NULL && *op == '.') { int mustfree = FALSE; char_u *s = vim_getenv(name, &mustfree); if (s != NULL) { p = tofree = concat_str(s, p); if (mustfree) vim_free(s); } } if (p != NULL) { vim_setenv(name, p); if (STRICMP(name, "HOME") == 0) init_homedir(); else if (didset_vim && STRICMP(name, "VIM") == 0) didset_vim = FALSE; else if (didset_vimruntime && STRICMP(name, "VIMRUNTIME") == 0) didset_vimruntime = FALSE; arg_end = arg; } name[len] = c1; vim_free(tofree); } } } /* * ":let &option = expr": Set option value. * ":let &l:option = expr": Set local option value. * ":let &g:option = expr": Set global option value. */ else if (*arg == '&') { /* Find the end of the name. */ p = find_option_end(&arg, &opt_flags); if (p == NULL || (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)) EMSG(_(e_letunexp)); else { long n; int opt_type; long numval; char_u *stringval = NULL; char_u *s; c1 = *p; *p = NUL; n = get_tv_number(tv); s = get_tv_string_chk(tv); /* != NULL if number or string */ if (s != NULL && op != NULL && *op != '=') { opt_type = get_option_value(arg, &numval, &stringval, opt_flags); if ((opt_type == 1 && *op == '.') || (opt_type == 0 && *op != '.')) EMSG2(_(e_letwrong), op); else { if (opt_type == 1) /* number */ { if (*op == '+') n = numval + n; else n = numval - n; } else if (opt_type == 0 && stringval != NULL) /* string */ { s = concat_str(stringval, s); vim_free(stringval); stringval = s; } } } if (s != NULL) { set_option_value(arg, n, s, opt_flags); arg_end = p; } *p = c1; vim_free(stringval); } } /* * ":let @r = expr": Set register contents. */ else if (*arg == '@') { ++arg; if (op != NULL && (*op == '+' || *op == '-')) EMSG2(_(e_letwrong), op); else if (endchars != NULL && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL) EMSG(_(e_letunexp)); else { char_u *ptofree = NULL; char_u *s; p = get_tv_string_chk(tv); if (p != NULL && op != NULL && *op == '.') { s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE); if (s != NULL) { p = ptofree = concat_str(s, p); vim_free(s); } } if (p != NULL) { write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE); arg_end = arg + 1; } vim_free(ptofree); } } /* * ":let var = expr": Set internal variable. * ":let {expr} = expr": Idem, name made with curly braces */ else if (eval_isnamec1(*arg) || *arg == '{') { lval_T lv; p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START); if (p != NULL && lv.ll_name != NULL) { if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL) EMSG(_(e_letunexp)); else { set_var_lval(&lv, p, tv, copy, op); arg_end = p; } } clear_lval(&lv); } else EMSG2(_(e_invarg2), arg); return arg_end; } /* * If "arg" is equal to "b:changedtick" give an error and return TRUE. */ static int check_changedtick(arg) char_u *arg; { if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13])) { EMSG2(_(e_readonlyvar), arg); return TRUE; } return FALSE; } /* * Get an lval: variable, Dict item or List item that can be assigned a value * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]", * "name.key", "name.key[expr]" etc. * Indexing only works if "name" is an existing List or Dictionary. * "name" points to the start of the name. * If "rettv" is not NULL it points to the value to be assigned. * "unlet" is TRUE for ":unlet": slightly different behavior when something is * wrong; must end in space or cmd separator. * * Returns a pointer to just after the name, including indexes. * When an evaluation error occurs "lp->ll_name" is NULL; * Returns NULL for a parsing error. Still need to free items in "lp"! */ static char_u * get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags) char_u *name; typval_T *rettv; lval_T *lp; int unlet; int skip; int quiet; /* don't give error messages */ int fne_flags; /* flags for find_name_end() */ { char_u *p; char_u *expr_start, *expr_end; int cc; dictitem_T *v; typval_T var1; typval_T var2; int empty1 = FALSE; listitem_T *ni; char_u *key = NULL; int len; hashtab_T *ht; /* Clear everything in "lp". */ vim_memset(lp, 0, sizeof(lval_T)); if (skip) { /* When skipping just find the end of the name. */ lp->ll_name = name; return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags); } /* Find the end of the name. */ p = find_name_end(name, &expr_start, &expr_end, fne_flags); if (expr_start != NULL) { /* Don't expand the name when we already know there is an error. */ if (unlet && !vim_iswhite(*p) && !ends_excmd(*p) && *p != '[' && *p != '.') { EMSG(_(e_trailing)); return NULL; } lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p); if (lp->ll_exp_name == NULL) { /* Report an invalid expression in braces, unless the * expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting() && !quiet) { emsg_severe = TRUE; EMSG2(_(e_invarg2), name); return NULL; } } lp->ll_name = lp->ll_exp_name; } else lp->ll_name = name; /* Without [idx] or .key we are done. */ if ((*p != '[' && *p != '.') || lp->ll_name == NULL) return p; cc = *p; *p = NUL; v = find_var(lp->ll_name, &ht); if (v == NULL && !quiet) EMSG2(_(e_undefvar), lp->ll_name); *p = cc; if (v == NULL) return NULL; /* * Loop until no more [idx] or .key is following. */ lp->ll_tv = &v->di_tv; while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT)) { if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL) && !(lp->ll_tv->v_type == VAR_DICT && lp->ll_tv->vval.v_dict != NULL)) { if (!quiet) EMSG(_("E689: Can only index a List or Dictionary")); return NULL; } if (lp->ll_range) { if (!quiet) EMSG(_("E708: [:] must come last")); return NULL; } len = -1; if (*p == '.') { key = p + 1; for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len) ; if (len == 0) { if (!quiet) EMSG(_(e_emptykey)); return NULL; } p = key + len; } else { /* Get the index [expr] or the first index [expr: ]. */ p = skipwhite(p + 1); if (*p == ':') empty1 = TRUE; else { empty1 = FALSE; if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */ return NULL; if (get_tv_string_chk(&var1) == NULL) { /* not a number or string */ clear_tv(&var1); return NULL; } } /* Optionally get the second index [ :expr]. */ if (*p == ':') { if (lp->ll_tv->v_type == VAR_DICT) { if (!quiet) EMSG(_(e_dictrange)); if (!empty1) clear_tv(&var1); return NULL; } if (rettv != NULL && (rettv->v_type != VAR_LIST || rettv->vval.v_list == NULL)) { if (!quiet) EMSG(_("E709: [:] requires a List value")); if (!empty1) clear_tv(&var1); return NULL; } p = skipwhite(p + 1); if (*p == ']') lp->ll_empty2 = TRUE; else { lp->ll_empty2 = FALSE; if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */ { if (!empty1) clear_tv(&var1); return NULL; } if (get_tv_string_chk(&var2) == NULL) { /* not a number or string */ if (!empty1) clear_tv(&var1); clear_tv(&var2); return NULL; } } lp->ll_range = TRUE; } else lp->ll_range = FALSE; if (*p != ']') { if (!quiet) EMSG(_(e_missbrac)); if (!empty1) clear_tv(&var1); if (lp->ll_range && !lp->ll_empty2) clear_tv(&var2); return NULL; } /* Skip to past ']'. */ ++p; } if (lp->ll_tv->v_type == VAR_DICT) { if (len == -1) { /* "[key]": get key from "var1" */ key = get_tv_string(&var1); /* is number or string */ if (*key == NUL) { if (!quiet) EMSG(_(e_emptykey)); clear_tv(&var1); return NULL; } } lp->ll_list = NULL; lp->ll_dict = lp->ll_tv->vval.v_dict; lp->ll_di = dict_find(lp->ll_dict, key, len); /* When assigning to g: check that a function and variable name is * valid. */ if (rettv != NULL && lp->ll_dict == &globvardict) { if (rettv->v_type == VAR_FUNC && var_check_func_name(key, lp->ll_di == NULL)) return NULL; if (!valid_varname(key)) return NULL; } if (lp->ll_di == NULL) { /* Can't add "v:" variable. */ if (lp->ll_dict == &vimvardict) { EMSG2(_(e_illvar), name); return NULL; } /* Key does not exist in dict: may need to add it. */ if (*p == '[' || *p == '.' || unlet) { if (!quiet) EMSG2(_(e_dictkey), key); if (len == -1) clear_tv(&var1); return NULL; } if (len == -1) lp->ll_newkey = vim_strsave(key); else lp->ll_newkey = vim_strnsave(key, len); if (len == -1) clear_tv(&var1); if (lp->ll_newkey == NULL) p = NULL; break; } /* existing variable, need to check if it can be changed */ else if (var_check_ro(lp->ll_di->di_flags, name)) return NULL; if (len == -1) clear_tv(&var1); lp->ll_tv = &lp->ll_di->di_tv; } else { /* * Get the number and item for the only or first index of the List. */ if (empty1) lp->ll_n1 = 0; else { lp->ll_n1 = get_tv_number(&var1); /* is number or string */ clear_tv(&var1); } lp->ll_dict = NULL; lp->ll_list = lp->ll_tv->vval.v_list; lp->ll_li = list_find(lp->ll_list, lp->ll_n1); if (lp->ll_li == NULL) { if (lp->ll_n1 < 0) { lp->ll_n1 = 0; lp->ll_li = list_find(lp->ll_list, lp->ll_n1); } } if (lp->ll_li == NULL) { if (lp->ll_range && !lp->ll_empty2) clear_tv(&var2); if (!quiet) EMSGN(_(e_listidx), lp->ll_n1); return NULL; } /* * May need to find the item or absolute index for the second * index of a range. * When no index given: "lp->ll_empty2" is TRUE. * Otherwise "lp->ll_n2" is set to the second index. */ if (lp->ll_range && !lp->ll_empty2) { lp->ll_n2 = get_tv_number(&var2); /* is number or string */ clear_tv(&var2); if (lp->ll_n2 < 0) { ni = list_find(lp->ll_list, lp->ll_n2); if (ni == NULL) { if (!quiet) EMSGN(_(e_listidx), lp->ll_n2); return NULL; } lp->ll_n2 = list_idx_of_item(lp->ll_list, ni); } /* Check that lp->ll_n2 isn't before lp->ll_n1. */ if (lp->ll_n1 < 0) lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li); if (lp->ll_n2 < lp->ll_n1) { if (!quiet) EMSGN(_(e_listidx), lp->ll_n2); return NULL; } } lp->ll_tv = &lp->ll_li->li_tv; } } return p; } /* * Clear lval "lp" that was filled by get_lval(). */ static void clear_lval(lp) lval_T *lp; { vim_free(lp->ll_exp_name); vim_free(lp->ll_newkey); } /* * Set a variable that was parsed by get_lval() to "rettv". * "endp" points to just after the parsed name. * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=". */ static void set_var_lval(lp, endp, rettv, copy, op) lval_T *lp; char_u *endp; typval_T *rettv; int copy; char_u *op; { int cc; listitem_T *ri; dictitem_T *di; if (lp->ll_tv == NULL) { if (!check_changedtick(lp->ll_name)) { cc = *endp; *endp = NUL; if (op != NULL && *op != '=') { typval_T tv; /* handle +=, -= and .= */ if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name), &tv, TRUE) == OK) { if (tv_op(&tv, rettv, op) == OK) set_var(lp->ll_name, &tv, FALSE); clear_tv(&tv); } } else set_var(lp->ll_name, rettv, copy); *endp = cc; } } else if (tv_check_lock(lp->ll_newkey == NULL ? lp->ll_tv->v_lock : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name)) ; else if (lp->ll_range) { /* * Assign the List values to the list items. */ for (ri = rettv->vval.v_list->lv_first; ri != NULL; ) { if (op != NULL && *op != '=') tv_op(&lp->ll_li->li_tv, &ri->li_tv, op); else { clear_tv(&lp->ll_li->li_tv); copy_tv(&ri->li_tv, &lp->ll_li->li_tv); } ri = ri->li_next; if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1)) break; if (lp->ll_li->li_next == NULL) { /* Need to add an empty item. */ if (list_append_number(lp->ll_list, 0) == FAIL) { ri = NULL; break; } } lp->ll_li = lp->ll_li->li_next; ++lp->ll_n1; } if (ri != NULL) EMSG(_("E710: List value has more items than target")); else if (lp->ll_empty2 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL) : lp->ll_n1 != lp->ll_n2) EMSG(_("E711: List value has not enough items")); } else { /* * Assign to a List or Dictionary item. */ if (lp->ll_newkey != NULL) { if (op != NULL && *op != '=') { EMSG2(_(e_letwrong), op); return; } /* Need to add an item to the Dictionary. */ di = dictitem_alloc(lp->ll_newkey); if (di == NULL) return; if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL) { vim_free(di); return; } lp->ll_tv = &di->di_tv; } else if (op != NULL && *op != '=') { tv_op(lp->ll_tv, rettv, op); return; } else clear_tv(lp->ll_tv); /* * Assign the value to the variable or list item. */ if (copy) copy_tv(rettv, lp->ll_tv); else { *lp->ll_tv = *rettv; lp->ll_tv->v_lock = 0; init_tv(rettv); } } } /* * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2" * Returns OK or FAIL. */ static int tv_op(tv1, tv2, op) typval_T *tv1; typval_T *tv2; char_u *op; { long n; char_u numbuf[NUMBUFLEN]; char_u *s; /* Can't do anything with a Funcref or a Dict on the right. */ if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT) { switch (tv1->v_type) { case VAR_DICT: case VAR_FUNC: break; case VAR_LIST: if (*op != '+' || tv2->v_type != VAR_LIST) break; /* List += List */ if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL) list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL); return OK; case VAR_NUMBER: case VAR_STRING: if (tv2->v_type == VAR_LIST) break; if (*op == '+' || *op == '-') { /* nr += nr or nr -= nr*/ n = get_tv_number(tv1); #ifdef FEAT_FLOAT if (tv2->v_type == VAR_FLOAT) { float_T f = n; if (*op == '+') f += tv2->vval.v_float; else f -= tv2->vval.v_float; clear_tv(tv1); tv1->v_type = VAR_FLOAT; tv1->vval.v_float = f; } else #endif { if (*op == '+') n += get_tv_number(tv2); else n -= get_tv_number(tv2); clear_tv(tv1); tv1->v_type = VAR_NUMBER; tv1->vval.v_number = n; } } else { if (tv2->v_type == VAR_FLOAT) break; /* str .= str */ s = get_tv_string(tv1); s = concat_str(s, get_tv_string_buf(tv2, numbuf)); clear_tv(tv1); tv1->v_type = VAR_STRING; tv1->vval.v_string = s; } return OK; #ifdef FEAT_FLOAT case VAR_FLOAT: { float_T f; if (*op == '.' || (tv2->v_type != VAR_FLOAT && tv2->v_type != VAR_NUMBER && tv2->v_type != VAR_STRING)) break; if (tv2->v_type == VAR_FLOAT) f = tv2->vval.v_float; else f = get_tv_number(tv2); if (*op == '+') tv1->vval.v_float += f; else tv1->vval.v_float -= f; } return OK; #endif } } EMSG2(_(e_letwrong), op); return FAIL; } /* * Add a watcher to a list. */ static void list_add_watch(l, lw) list_T *l; listwatch_T *lw; { lw->lw_next = l->lv_watch; l->lv_watch = lw; } /* * Remove a watcher from a list. * No warning when it isn't found... */ static void list_rem_watch(l, lwrem) list_T *l; listwatch_T *lwrem; { listwatch_T *lw, **lwp; lwp = &l->lv_watch; for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next) { if (lw == lwrem) { *lwp = lw->lw_next; break; } lwp = &lw->lw_next; } } /* * Just before removing an item from a list: advance watchers to the next * item. */ static void list_fix_watch(l, item) list_T *l; listitem_T *item; { listwatch_T *lw; for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next) if (lw->lw_item == item) lw->lw_item = item->li_next; } /* * Evaluate the expression used in a ":for var in expr" command. * "arg" points to "var". * Set "*errp" to TRUE for an error, FALSE otherwise; * Return a pointer that holds the info. Null when there is an error. */ void * eval_for_line(arg, errp, nextcmdp, skip) char_u *arg; int *errp; char_u **nextcmdp; int skip; { forinfo_T *fi; char_u *expr; typval_T tv; list_T *l; *errp = TRUE; /* default: there is an error */ fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T)); if (fi == NULL) return NULL; expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon); if (expr == NULL) return fi; expr = skipwhite(expr); if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2])) { EMSG(_("E690: Missing \"in\" after :for")); return fi; } if (skip) ++emsg_skip; if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK) { *errp = FALSE; if (!skip) { l = tv.vval.v_list; if (tv.v_type != VAR_LIST || l == NULL) { EMSG(_(e_listreq)); clear_tv(&tv); } else { /* No need to increment the refcount, it's already set for the * list being used in "tv". */ fi->fi_list = l; list_add_watch(l, &fi->fi_lw); fi->fi_lw.lw_item = l->lv_first; } } } if (skip) --emsg_skip; return fi; } /* * Use the first item in a ":for" list. Advance to the next. * Assign the values to the variable (list). "arg" points to the first one. * Return TRUE when a valid item was found, FALSE when at end of list or * something wrong. */ int next_for_item(fi_void, arg) void *fi_void; char_u *arg; { forinfo_T *fi = (forinfo_T *)fi_void; int result; listitem_T *item; item = fi->fi_lw.lw_item; if (item == NULL) result = FALSE; else { fi->fi_lw.lw_item = item->li_next; result = (ex_let_vars(arg, &item->li_tv, TRUE, fi->fi_semicolon, fi->fi_varcount, NULL) == OK); } return result; } /* * Free the structure used to store info used by ":for". */ void free_for_info(fi_void) void *fi_void; { forinfo_T *fi = (forinfo_T *)fi_void; if (fi != NULL && fi->fi_list != NULL) { list_rem_watch(fi->fi_list, &fi->fi_lw); list_unref(fi->fi_list); } vim_free(fi); } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) void set_context_for_expression(xp, arg, cmdidx) expand_T *xp; char_u *arg; cmdidx_T cmdidx; { int got_eq = FALSE; int c; char_u *p; if (cmdidx == CMD_let) { xp->xp_context = EXPAND_USER_VARS; if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL) { /* ":let var1 var2 ...": find last space. */ for (p = arg + STRLEN(arg); p >= arg; ) { xp->xp_pattern = p; mb_ptr_back(arg, p); if (vim_iswhite(*p)) break; } return; } } else xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS : EXPAND_EXPRESSION; while ((xp->xp_pattern = vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL) { c = *xp->xp_pattern; if (c == '&') { c = xp->xp_pattern[1]; if (c == '&') { ++xp->xp_pattern; xp->xp_context = cmdidx != CMD_let || got_eq ? EXPAND_EXPRESSION : EXPAND_NOTHING; } else if (c != ' ') { xp->xp_context = EXPAND_SETTINGS; if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':') xp->xp_pattern += 2; } } else if (c == '$') { /* environment variable */ xp->xp_context = EXPAND_ENV_VARS; } else if (c == '=') { got_eq = TRUE; xp->xp_context = EXPAND_EXPRESSION; } else if (c == '<' && xp->xp_context == EXPAND_FUNCTIONS && vim_strchr(xp->xp_pattern, '(') == NULL) { /* Function name can start with "<SNR>" */ break; } else if (cmdidx != CMD_let || got_eq) { if (c == '"') /* string */ { while ((c = *++xp->xp_pattern) != NUL && c != '"') if (c == '\\' && xp->xp_pattern[1] != NUL) ++xp->xp_pattern; xp->xp_context = EXPAND_NOTHING; } else if (c == '\'') /* literal string */ { /* Trick: '' is like stopping and starting a literal string. */ while ((c = *++xp->xp_pattern) != NUL && c != '\'') /* skip */ ; xp->xp_context = EXPAND_NOTHING; } else if (c == '|') { if (xp->xp_pattern[1] == '|') { ++xp->xp_pattern; xp->xp_context = EXPAND_EXPRESSION; } else xp->xp_context = EXPAND_COMMANDS; } else xp->xp_context = EXPAND_EXPRESSION; } else /* Doesn't look like something valid, expand as an expression * anyway. */ xp->xp_context = EXPAND_EXPRESSION; arg = xp->xp_pattern; if (*arg != NUL) while ((c = *++arg) != NUL && (c == ' ' || c == '\t')) /* skip */ ; } xp->xp_pattern = arg; } #endif /* FEAT_CMDL_COMPL */ /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(eap) exarg_T *eap; { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; if (eap->skip) { /* trans_function_name() doesn't work well when skipping, use eval0() * instead to skip to any following command, e.g. for: * :if 0 | call dict.foo().bar() | endif */ ++emsg_skip; if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL) clear_tv(&rettv); --emsg_skip; return; } tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi); if (fudi.fd_newkey != NULL) { /* Still need to give an error message for missing key. */ EMSG2(_(e_dictkey), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; /* Increase refcount on dictionary, it could get deleted when evaluating * the arguments. */ if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; /* If it is the name of a variable of type VAR_FUNC use its contents. */ len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len); /* Skip white space to allow ":call func ()". Not good, but required for * backward compatibility. */ startarg = skipwhite(arg); rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */ if (*startarg != '(') { EMSG2(_("E107: Missing parentheses: %s"), eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; /* do it once, also with an invalid range */ } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { if (!eap->skip && eap->addr_count > 0) { curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif } arg = startarg; if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg, eap->line1, eap->line2, &doesrange, !eap->skip, fudi.fd_dict) == FAIL) { failed = TRUE; break; } /* Handle a function returning a Funcref, Dictionary or List. */ if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; /* Stop when immediately aborting on error, or when an interrupt * occurred or an exception was thrown but not caught. * get_func_tv() returned OK, so that the check for trailing * characters below is executed. */ if (aborting()) break; } if (eap->skip) --emsg_skip; if (!failed) { /* Check for trailing illegal characters and a following command. */ if (!ends_excmd(*arg)) { emsg_severe = TRUE; EMSG(_(e_trailing)); } else eap->nextcmd = check_nextcmd(arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * ":unlet[!] var1 ... " command. */ void ex_unlet(eap) exarg_T *eap; { ex_unletlock(eap, eap->arg, 0); } /* * ":lockvar" and ":unlockvar" commands */ void ex_lockvar(eap) exarg_T *eap; { char_u *arg = eap->arg; int deep = 2; if (eap->forceit) deep = -1; else if (vim_isdigit(*arg)) { deep = getdigits(&arg); arg = skipwhite(arg); } ex_unletlock(eap, arg, deep); } /* * ":unlet", ":lockvar" and ":unlockvar" are quite similar. */ static void ex_unletlock(eap, argstart, deep) exarg_T *eap; char_u *argstart; int deep; { char_u *arg = argstart; char_u *name_end; int error = FALSE; lval_T lv; do { /* Parse the name and find the end. */ name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE, FNE_CHECK_START); if (lv.ll_name == NULL) error = TRUE; /* error but continue parsing */ if (name_end == NULL || (!vim_iswhite(*name_end) && !ends_excmd(*name_end))) { if (name_end != NULL) { emsg_severe = TRUE; EMSG(_(e_trailing)); } if (!(eap->skip || error)) clear_lval(&lv); break; } if (!error && !eap->skip) { if (eap->cmdidx == CMD_unlet) { if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL) error = TRUE; } else { if (do_lock_var(&lv, name_end, deep, eap->cmdidx == CMD_lockvar) == FAIL) error = TRUE; } } if (!eap->skip) clear_lval(&lv); arg = skipwhite(name_end); } while (!ends_excmd(*arg)); eap->nextcmd = check_nextcmd(arg); } static int do_unlet_var(lp, name_end, forceit) lval_T *lp; char_u *name_end; int forceit; { int ret = OK; int cc; if (lp->ll_tv == NULL) { cc = *name_end; *name_end = NUL; /* Normal name or expanded name. */ if (check_changedtick(lp->ll_name)) ret = FAIL; else if (do_unlet(lp->ll_name, forceit) == FAIL) ret = FAIL; *name_end = cc; } else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name)) return FAIL; else if (lp->ll_range) { listitem_T *li; /* Delete a range of List items. */ while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1)) { li = lp->ll_li->li_next; listitem_remove(lp->ll_list, lp->ll_li); lp->ll_li = li; ++lp->ll_n1; } } else { if (lp->ll_list != NULL) /* unlet a List item. */ listitem_remove(lp->ll_list, lp->ll_li); else /* unlet a Dictionary item. */ dictitem_remove(lp->ll_dict, lp->ll_di); } return ret; } /* * "unlet" a variable. Return OK if it existed, FAIL if not. * When "forceit" is TRUE don't complain if the variable doesn't exist. */ int do_unlet(name, forceit) char_u *name; int forceit; { hashtab_T *ht; hashitem_T *hi; char_u *varname; dictitem_T *di; ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { di = HI2DI(hi); if (var_check_fixed(di->di_flags, name) || var_check_ro(di->di_flags, name)) return FAIL; delete_var(ht, hi); return OK; } } if (forceit) return OK; EMSG2(_("E108: No such variable: \"%s\""), name); return FAIL; } /* * Lock or unlock variable indicated by "lp". * "deep" is the levels to go (-1 for unlimited); * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar". */ static int do_lock_var(lp, name_end, deep, lock) lval_T *lp; char_u *name_end; int deep; int lock; { int ret = OK; int cc; dictitem_T *di; if (deep == 0) /* nothing to do */ return OK; if (lp->ll_tv == NULL) { cc = *name_end; *name_end = NUL; /* Normal name or expanded name. */ if (check_changedtick(lp->ll_name)) ret = FAIL; else { di = find_var(lp->ll_name, NULL); if (di == NULL) ret = FAIL; else { if (lock) di->di_flags |= DI_FLAGS_LOCK; else di->di_flags &= ~DI_FLAGS_LOCK; item_lock(&di->di_tv, deep, lock); } } *name_end = cc; } else if (lp->ll_range) { listitem_T *li = lp->ll_li; /* (un)lock a range of List items. */ while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1)) { item_lock(&li->li_tv, deep, lock); li = li->li_next; ++lp->ll_n1; } } else if (lp->ll_list != NULL) /* (un)lock a List item. */ item_lock(&lp->ll_li->li_tv, deep, lock); else /* un(lock) a Dictionary item. */ item_lock(&lp->ll_di->di_tv, deep, lock); return ret; } /* * Lock or unlock an item. "deep" is nr of levels to go. */ static void item_lock(tv, deep, lock) typval_T *tv; int deep; int lock; { static int recurse = 0; list_T *l; listitem_T *li; dict_T *d; hashitem_T *hi; int todo; if (recurse >= DICT_MAXNEST) { EMSG(_("E743: variable nested too deep for (un)lock")); return; } if (deep == 0) return; ++recurse; /* lock/unlock the item itself */ if (lock) tv->v_lock |= VAR_LOCKED; else tv->v_lock &= ~VAR_LOCKED; switch (tv->v_type) { case VAR_LIST: if ((l = tv->vval.v_list) != NULL) { if (lock) l->lv_lock |= VAR_LOCKED; else l->lv_lock &= ~VAR_LOCKED; if (deep < 0 || deep > 1) /* recursive: lock/unlock the items the List contains */ for (li = l->lv_first; li != NULL; li = li->li_next) item_lock(&li->li_tv, deep - 1, lock); } break; case VAR_DICT: if ((d = tv->vval.v_dict) != NULL) { if (lock) d->dv_lock |= VAR_LOCKED; else d->dv_lock &= ~VAR_LOCKED; if (deep < 0 || deep > 1) { /* recursive: lock/unlock the items the List contains */ todo = (int)d->dv_hashtab.ht_used; for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; item_lock(&HI2DI(hi)->di_tv, deep - 1, lock); } } } } } --recurse; } /* * Return TRUE if typeval "tv" is locked: Either that value is locked itself * or it refers to a List or Dictionary that is locked. */ static int tv_islocked(tv) typval_T *tv; { return (tv->v_lock & VAR_LOCKED) || (tv->v_type == VAR_LIST && tv->vval.v_list != NULL && (tv->vval.v_list->lv_lock & VAR_LOCKED)) || (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL && (tv->vval.v_dict->dv_lock & VAR_LOCKED)); } #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO) /* * Delete all "menutrans_" variables. */ void del_menutrans_vars() { hashitem_T *hi; int todo; hash_lock(&globvarht); todo = (int)globvarht.ht_used; for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0) delete_var(&globvarht, hi); } } hash_unlock(&globvarht); } #endif #if defined(FEAT_CMDL_COMPL) || defined(PROTO) /* * Local string buffer for the next two functions to store a variable name * with its prefix. Allocated in cat_prefix_varname(), freed later in * get_user_var_name(). */ static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name)); static char_u *varnamebuf = NULL; static int varnamebuflen = 0; /* * Function to concatenate a prefix and a variable name. */ static char_u * cat_prefix_varname(prefix, name) int prefix; char_u *name; { int len; len = (int)STRLEN(name) + 3; if (len > varnamebuflen) { vim_free(varnamebuf); len += 10; /* some additional space */ varnamebuf = alloc(len); if (varnamebuf == NULL) { varnamebuflen = 0; return NULL; } varnamebuflen = len; } *varnamebuf = prefix; varnamebuf[1] = ':'; STRCPY(varnamebuf + 2, name); return varnamebuf; } /* * Function given to ExpandGeneric() to obtain the list of user defined * (global/buffer/window/built-in) variable names. */ char_u * get_user_var_name(xp, idx) expand_T *xp; int idx; { static long_u gdone; static long_u bdone; static long_u wdone; #ifdef FEAT_WINDOWS static long_u tdone; #endif static int vidx; static hashitem_T *hi; hashtab_T *ht; if (idx == 0) { gdone = bdone = wdone = vidx = 0; #ifdef FEAT_WINDOWS tdone = 0; #endif } /* Global variables */ if (gdone < globvarht.ht_used) { if (gdone++ == 0) hi = globvarht.ht_array; else ++hi; while (HASHITEM_EMPTY(hi)) ++hi; if (STRNCMP("g:", xp->xp_pattern, 2) == 0) return cat_prefix_varname('g', hi->hi_key); return hi->hi_key; } /* b: variables */ ht = &curbuf->b_vars.dv_hashtab; if (bdone < ht->ht_used) { if (bdone++ == 0) hi = ht->ht_array; else ++hi; while (HASHITEM_EMPTY(hi)) ++hi; return cat_prefix_varname('b', hi->hi_key); } if (bdone == ht->ht_used) { ++bdone; return (char_u *)"b:changedtick"; } /* w: variables */ ht = &curwin->w_vars.dv_hashtab; if (wdone < ht->ht_used) { if (wdone++ == 0) hi = ht->ht_array; else ++hi; while (HASHITEM_EMPTY(hi)) ++hi; return cat_prefix_varname('w', hi->hi_key); } #ifdef FEAT_WINDOWS /* t: variables */ ht = &curtab->tp_vars.dv_hashtab; if (tdone < ht->ht_used) { if (tdone++ == 0) hi = ht->ht_array; else ++hi; while (HASHITEM_EMPTY(hi)) ++hi; return cat_prefix_varname('t', hi->hi_key); } #endif /* v: variables */ if (vidx < VV_LEN) return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name); vim_free(varnamebuf); varnamebuf = NULL; varnamebuflen = 0; return NULL; } #endif /* FEAT_CMDL_COMPL */ /* * types for expressions. */ typedef enum { TYPE_UNKNOWN = 0 , TYPE_EQUAL /* == */ , TYPE_NEQUAL /* != */ , TYPE_GREATER /* > */ , TYPE_GEQUAL /* >= */ , TYPE_SMALLER /* < */ , TYPE_SEQUAL /* <= */ , TYPE_MATCH /* =~ */ , TYPE_NOMATCH /* !~ */ } exptype_T; /* * The "evaluate" argument: When FALSE, the argument is only parsed but not * executed. The function may return OK, but the rettv will be of type * VAR_UNKNOWN. The function still returns FAIL for a syntax error. */ /* * Handle zero level expression. * This calls eval1() and handles error message and nextcmd. * Put the result in "rettv" when returning OK and "evaluate" is TRUE. * Note: "rettv.v_lock" is not set. * Return OK or FAIL. */ static int eval0(arg, rettv, nextcmd, evaluate) char_u *arg; typval_T *rettv; char_u **nextcmd; int evaluate; { int ret; char_u *p; p = skipwhite(arg); ret = eval1(&p, rettv, evaluate); if (ret == FAIL || !ends_excmd(*p)) { if (ret != FAIL) clear_tv(rettv); /* * Report the invalid expression unless the expression evaluation has * been cancelled due to an aborting error, an interrupt, or an * exception. */ if (!aborting()) EMSG2(_(e_invexpr2), arg); ret = FAIL; } if (nextcmd != NULL) *nextcmd = check_nextcmd(p); return ret; } /* * Handle top level expression: * expr2 ? expr1 : expr1 * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Note: "rettv.v_lock" is not set. * * Return OK or FAIL. */ static int eval1(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { int result; typval_T var2; /* * Get the first variable. */ if (eval2(arg, rettv, evaluate) == FAIL) return FAIL; if ((*arg)[0] == '?') { result = FALSE; if (evaluate) { int error = FALSE; if (get_tv_number_chk(rettv, &error) != 0) result = TRUE; clear_tv(rettv); if (error) return FAIL; } /* * Get the second variable. */ *arg = skipwhite(*arg + 1); if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */ return FAIL; /* * Check for the ":". */ if ((*arg)[0] != ':') { EMSG(_("E109: Missing ':' after '?'")); if (evaluate && result) clear_tv(rettv); return FAIL; } /* * Get the third variable. */ *arg = skipwhite(*arg + 1); if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */ { if (evaluate && result) clear_tv(rettv); return FAIL; } if (evaluate && !result) *rettv = var2; } return OK; } /* * Handle first level expression: * expr2 || expr2 || expr2 logical OR * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval2(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { typval_T var2; long result; int first; int error = FALSE; /* * Get the first variable. */ if (eval3(arg, rettv, evaluate) == FAIL) return FAIL; /* * Repeat until there is no following "||". */ first = TRUE; result = FALSE; while ((*arg)[0] == '|' && (*arg)[1] == '|') { if (evaluate && first) { if (get_tv_number_chk(rettv, &error) != 0) result = TRUE; clear_tv(rettv); if (error) return FAIL; first = FALSE; } /* * Get the second variable. */ *arg = skipwhite(*arg + 2); if (eval3(arg, &var2, evaluate && !result) == FAIL) return FAIL; /* * Compute the result. */ if (evaluate && !result) { if (get_tv_number_chk(&var2, &error) != 0) result = TRUE; clear_tv(&var2); if (error) return FAIL; } if (evaluate) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = result; } } return OK; } /* * Handle second level expression: * expr3 && expr3 && expr3 logical AND * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval3(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { typval_T var2; long result; int first; int error = FALSE; /* * Get the first variable. */ if (eval4(arg, rettv, evaluate) == FAIL) return FAIL; /* * Repeat until there is no following "&&". */ first = TRUE; result = TRUE; while ((*arg)[0] == '&' && (*arg)[1] == '&') { if (evaluate && first) { if (get_tv_number_chk(rettv, &error) == 0) result = FALSE; clear_tv(rettv); if (error) return FAIL; first = FALSE; } /* * Get the second variable. */ *arg = skipwhite(*arg + 2); if (eval4(arg, &var2, evaluate && result) == FAIL) return FAIL; /* * Compute the result. */ if (evaluate && result) { if (get_tv_number_chk(&var2, &error) == 0) result = FALSE; clear_tv(&var2); if (error) return FAIL; } if (evaluate) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = result; } } return OK; } /* * Handle third level expression: * var1 == var2 * var1 =~ var2 * var1 != var2 * var1 !~ var2 * var1 > var2 * var1 >= var2 * var1 < var2 * var1 <= var2 * var1 is var2 * var1 isnot var2 * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval4(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { typval_T var2; char_u *p; int i; exptype_T type = TYPE_UNKNOWN; int type_is = FALSE; /* TRUE for "is" and "isnot" */ int len = 2; long n1, n2; char_u *s1, *s2; char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN]; regmatch_T regmatch; int ic; char_u *save_cpo; /* * Get the first variable. */ if (eval5(arg, rettv, evaluate) == FAIL) return FAIL; p = *arg; switch (p[0]) { case '=': if (p[1] == '=') type = TYPE_EQUAL; else if (p[1] == '~') type = TYPE_MATCH; break; case '!': if (p[1] == '=') type = TYPE_NEQUAL; else if (p[1] == '~') type = TYPE_NOMATCH; break; case '>': if (p[1] != '=') { type = TYPE_GREATER; len = 1; } else type = TYPE_GEQUAL; break; case '<': if (p[1] != '=') { type = TYPE_SMALLER; len = 1; } else type = TYPE_SEQUAL; break; case 'i': if (p[1] == 's') { if (p[2] == 'n' && p[3] == 'o' && p[4] == 't') len = 5; if (!vim_isIDc(p[len])) { type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL; type_is = TRUE; } } break; } /* * If there is a comparative operator, use it. */ if (type != TYPE_UNKNOWN) { /* extra question mark appended: ignore case */ if (p[len] == '?') { ic = TRUE; ++len; } /* extra '#' appended: match case */ else if (p[len] == '#') { ic = FALSE; ++len; } /* nothing appended: use 'ignorecase' */ else ic = p_ic; /* * Get the second variable. */ *arg = skipwhite(p + len); if (eval5(arg, &var2, evaluate) == FAIL) { clear_tv(rettv); return FAIL; } if (evaluate) { if (type_is && rettv->v_type != var2.v_type) { /* For "is" a different type always means FALSE, for "notis" * it means TRUE. */ n1 = (type == TYPE_NEQUAL); } else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST) { if (type_is) { n1 = (rettv->v_type == var2.v_type && rettv->vval.v_list == var2.vval.v_list); if (type == TYPE_NEQUAL) n1 = !n1; } else if (rettv->v_type != var2.v_type || (type != TYPE_EQUAL && type != TYPE_NEQUAL)) { if (rettv->v_type != var2.v_type) EMSG(_("E691: Can only compare List with List")); else EMSG(_("E692: Invalid operation for Lists")); clear_tv(rettv); clear_tv(&var2); return FAIL; } else { /* Compare two Lists for being equal or unequal. */ n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic, FALSE); if (type == TYPE_NEQUAL) n1 = !n1; } } else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT) { if (type_is) { n1 = (rettv->v_type == var2.v_type && rettv->vval.v_dict == var2.vval.v_dict); if (type == TYPE_NEQUAL) n1 = !n1; } else if (rettv->v_type != var2.v_type || (type != TYPE_EQUAL && type != TYPE_NEQUAL)) { if (rettv->v_type != var2.v_type) EMSG(_("E735: Can only compare Dictionary with Dictionary")); else EMSG(_("E736: Invalid operation for Dictionary")); clear_tv(rettv); clear_tv(&var2); return FAIL; } else { /* Compare two Dictionaries for being equal or unequal. */ n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic, FALSE); if (type == TYPE_NEQUAL) n1 = !n1; } } else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC) { if (rettv->v_type != var2.v_type || (type != TYPE_EQUAL && type != TYPE_NEQUAL)) { if (rettv->v_type != var2.v_type) EMSG(_("E693: Can only compare Funcref with Funcref")); else EMSG(_("E694: Invalid operation for Funcrefs")); clear_tv(rettv); clear_tv(&var2); return FAIL; } else { /* Compare two Funcrefs for being equal or unequal. */ if (rettv->vval.v_string == NULL || var2.vval.v_string == NULL) n1 = FALSE; else n1 = STRCMP(rettv->vval.v_string, var2.vval.v_string) == 0; if (type == TYPE_NEQUAL) n1 = !n1; } } #ifdef FEAT_FLOAT /* * If one of the two variables is a float, compare as a float. * When using "=~" or "!~", always compare as string. */ else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT) && type != TYPE_MATCH && type != TYPE_NOMATCH) { float_T f1, f2; if (rettv->v_type == VAR_FLOAT) f1 = rettv->vval.v_float; else f1 = get_tv_number(rettv); if (var2.v_type == VAR_FLOAT) f2 = var2.vval.v_float; else f2 = get_tv_number(&var2); n1 = FALSE; switch (type) { case TYPE_EQUAL: n1 = (f1 == f2); break; case TYPE_NEQUAL: n1 = (f1 != f2); break; case TYPE_GREATER: n1 = (f1 > f2); break; case TYPE_GEQUAL: n1 = (f1 >= f2); break; case TYPE_SMALLER: n1 = (f1 < f2); break; case TYPE_SEQUAL: n1 = (f1 <= f2); break; case TYPE_UNKNOWN: case TYPE_MATCH: case TYPE_NOMATCH: break; /* avoid gcc warning */ } } #endif /* * If one of the two variables is a number, compare as a number. * When using "=~" or "!~", always compare as string. */ else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER) && type != TYPE_MATCH && type != TYPE_NOMATCH) { n1 = get_tv_number(rettv); n2 = get_tv_number(&var2); switch (type) { case TYPE_EQUAL: n1 = (n1 == n2); break; case TYPE_NEQUAL: n1 = (n1 != n2); break; case TYPE_GREATER: n1 = (n1 > n2); break; case TYPE_GEQUAL: n1 = (n1 >= n2); break; case TYPE_SMALLER: n1 = (n1 < n2); break; case TYPE_SEQUAL: n1 = (n1 <= n2); break; case TYPE_UNKNOWN: case TYPE_MATCH: case TYPE_NOMATCH: break; /* avoid gcc warning */ } } else { s1 = get_tv_string_buf(rettv, buf1); s2 = get_tv_string_buf(&var2, buf2); if (type != TYPE_MATCH && type != TYPE_NOMATCH) i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2); else i = 0; n1 = FALSE; switch (type) { case TYPE_EQUAL: n1 = (i == 0); break; case TYPE_NEQUAL: n1 = (i != 0); break; case TYPE_GREATER: n1 = (i > 0); break; case TYPE_GEQUAL: n1 = (i >= 0); break; case TYPE_SMALLER: n1 = (i < 0); break; case TYPE_SEQUAL: n1 = (i <= 0); break; case TYPE_MATCH: case TYPE_NOMATCH: /* avoid 'l' flag in 'cpoptions' */ save_cpo = p_cpo; p_cpo = (char_u *)""; regmatch.regprog = vim_regcomp(s2, RE_MAGIC + RE_STRING); regmatch.rm_ic = ic; if (regmatch.regprog != NULL) { n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0); vim_free(regmatch.regprog); if (type == TYPE_NOMATCH) n1 = !n1; } p_cpo = save_cpo; break; case TYPE_UNKNOWN: break; /* avoid gcc warning */ } } clear_tv(rettv); clear_tv(&var2); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = n1; } } return OK; } /* * Handle fourth level expression: * + number addition * - number subtraction * . string concatenation * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval5(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { typval_T var2; typval_T var3; int op; long n1, n2; #ifdef FEAT_FLOAT float_T f1 = 0, f2 = 0; #endif char_u *s1, *s2; char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN]; char_u *p; /* * Get the first variable. */ if (eval6(arg, rettv, evaluate, FALSE) == FAIL) return FAIL; /* * Repeat computing, until no '+', '-' or '.' is following. */ for (;;) { op = **arg; if (op != '+' && op != '-' && op != '.') break; if ((op != '+' || rettv->v_type != VAR_LIST) #ifdef FEAT_FLOAT && (op == '.' || rettv->v_type != VAR_FLOAT) #endif ) { /* For "list + ...", an illegal use of the first operand as * a number cannot be determined before evaluating the 2nd * operand: if this is also a list, all is ok. * For "something . ...", "something - ..." or "non-list + ...", * we know that the first operand needs to be a string or number * without evaluating the 2nd operand. So check before to avoid * side effects after an error. */ if (evaluate && get_tv_string_chk(rettv) == NULL) { clear_tv(rettv); return FAIL; } } /* * Get the second variable. */ *arg = skipwhite(*arg + 1); if (eval6(arg, &var2, evaluate, op == '.') == FAIL) { clear_tv(rettv); return FAIL; } if (evaluate) { /* * Compute the result. */ if (op == '.') { s1 = get_tv_string_buf(rettv, buf1); /* already checked */ s2 = get_tv_string_buf_chk(&var2, buf2); if (s2 == NULL) /* type error ? */ { clear_tv(rettv); clear_tv(&var2); return FAIL; } p = concat_str(s1, s2); clear_tv(rettv); rettv->v_type = VAR_STRING; rettv->vval.v_string = p; } else if (op == '+' && rettv->v_type == VAR_LIST && var2.v_type == VAR_LIST) { /* concatenate Lists */ if (list_concat(rettv->vval.v_list, var2.vval.v_list, &var3) == FAIL) { clear_tv(rettv); clear_tv(&var2); return FAIL; } clear_tv(rettv); *rettv = var3; } else { int error = FALSE; #ifdef FEAT_FLOAT if (rettv->v_type == VAR_FLOAT) { f1 = rettv->vval.v_float; n1 = 0; } else #endif { n1 = get_tv_number_chk(rettv, &error); if (error) { /* This can only happen for "list + non-list". For * "non-list + ..." or "something - ...", we returned * before evaluating the 2nd operand. */ clear_tv(rettv); return FAIL; } #ifdef FEAT_FLOAT if (var2.v_type == VAR_FLOAT) f1 = n1; #endif } #ifdef FEAT_FLOAT if (var2.v_type == VAR_FLOAT) { f2 = var2.vval.v_float; n2 = 0; } else #endif { n2 = get_tv_number_chk(&var2, &error); if (error) { clear_tv(rettv); clear_tv(&var2); return FAIL; } #ifdef FEAT_FLOAT if (rettv->v_type == VAR_FLOAT) f2 = n2; #endif } clear_tv(rettv); #ifdef FEAT_FLOAT /* If there is a float on either side the result is a float. */ if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT) { if (op == '+') f1 = f1 + f2; else f1 = f1 - f2; rettv->v_type = VAR_FLOAT; rettv->vval.v_float = f1; } else #endif { if (op == '+') n1 = n1 + n2; else n1 = n1 - n2; rettv->v_type = VAR_NUMBER; rettv->vval.v_number = n1; } } clear_tv(&var2); } } return OK; } /* * Handle fifth level expression: * * number multiplication * / number division * % number modulo * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval6(arg, rettv, evaluate, want_string) char_u **arg; typval_T *rettv; int evaluate; int want_string; /* after "." operator */ { typval_T var2; int op; long n1, n2; #ifdef FEAT_FLOAT int use_float = FALSE; float_T f1 = 0, f2; #endif int error = FALSE; /* * Get the first variable. */ if (eval7(arg, rettv, evaluate, want_string) == FAIL) return FAIL; /* * Repeat computing, until no '*', '/' or '%' is following. */ for (;;) { op = **arg; if (op != '*' && op != '/' && op != '%') break; if (evaluate) { #ifdef FEAT_FLOAT if (rettv->v_type == VAR_FLOAT) { f1 = rettv->vval.v_float; use_float = TRUE; n1 = 0; } else #endif n1 = get_tv_number_chk(rettv, &error); clear_tv(rettv); if (error) return FAIL; } else n1 = 0; /* * Get the second variable. */ *arg = skipwhite(*arg + 1); if (eval7(arg, &var2, evaluate, FALSE) == FAIL) return FAIL; if (evaluate) { #ifdef FEAT_FLOAT if (var2.v_type == VAR_FLOAT) { if (!use_float) { f1 = n1; use_float = TRUE; } f2 = var2.vval.v_float; n2 = 0; } else #endif { n2 = get_tv_number_chk(&var2, &error); clear_tv(&var2); if (error) return FAIL; #ifdef FEAT_FLOAT if (use_float) f2 = n2; #endif } /* * Compute the result. * When either side is a float the result is a float. */ #ifdef FEAT_FLOAT if (use_float) { if (op == '*') f1 = f1 * f2; else if (op == '/') { # ifdef VMS /* VMS crashes on divide by zero, work around it */ if (f2 == 0.0) { if (f1 == 0) f1 = -1 * __F_FLT_MAX - 1L; /* similar to NaN */ else if (f1 < 0) f1 = -1 * __F_FLT_MAX; else f1 = __F_FLT_MAX; } else f1 = f1 / f2; # else /* We rely on the floating point library to handle divide * by zero to result in "inf" and not a crash. */ f1 = f1 / f2; # endif } else { EMSG(_("E804: Cannot use '%' with Float")); return FAIL; } rettv->v_type = VAR_FLOAT; rettv->vval.v_float = f1; } else #endif { if (op == '*') n1 = n1 * n2; else if (op == '/') { if (n2 == 0) /* give an error message? */ { if (n1 == 0) n1 = -0x7fffffffL - 1L; /* similar to NaN */ else if (n1 < 0) n1 = -0x7fffffffL; else n1 = 0x7fffffffL; } else n1 = n1 / n2; } else { if (n2 == 0) /* give an error message? */ n1 = 0; else n1 = n1 % n2; } rettv->v_type = VAR_NUMBER; rettv->vval.v_number = n1; } } } return OK; } /* * Handle sixth level expression: * number number constant * "string" string constant * 'string' literal string constant * &option-name option value * @r register contents * identifier variable value * function() function call * $VAR environment variable * (expression) nested expression * [expr, expr] List * {key: val, key: val} Dictionary * * Also handle: * ! in front logical NOT * - in front unary minus * + in front unary plus (ignored) * trailing [] subscript in String or List * trailing .name entry in Dictionary * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval7(arg, rettv, evaluate, want_string) char_u **arg; typval_T *rettv; int evaluate; int want_string UNUSED; /* after "." operator */ { long n; int len; char_u *s; char_u *start_leader, *end_leader; int ret = OK; char_u *alias; /* * Initialise variable so that clear_tv() can't mistake this for a * string and free a string that isn't there. */ rettv->v_type = VAR_UNKNOWN; /* * Skip '!' and '-' characters. They are handled later. */ start_leader = *arg; while (**arg == '!' || **arg == '-' || **arg == '+') *arg = skipwhite(*arg + 1); end_leader = *arg; switch (**arg) { /* * Number constant. */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { #ifdef FEAT_FLOAT char_u *p = skipdigits(*arg + 1); int get_float = FALSE; /* We accept a float when the format matches * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very * strict to avoid backwards compatibility problems. * Don't look for a float after the "." operator, so that * ":let vers = 1.2.3" doesn't fail. */ if (!want_string && p[0] == '.' && vim_isdigit(p[1])) { get_float = TRUE; p = skipdigits(p + 2); if (*p == 'e' || *p == 'E') { ++p; if (*p == '-' || *p == '+') ++p; if (!vim_isdigit(*p)) get_float = FALSE; else p = skipdigits(p + 1); } if (ASCII_ISALPHA(*p) || *p == '.') get_float = FALSE; } if (get_float) { float_T f; *arg += string2float(*arg, &f); if (evaluate) { rettv->v_type = VAR_FLOAT; rettv->vval.v_float = f; } } else #endif { vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL); *arg += len; if (evaluate) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = n; } } break; } /* * String constant: "string". */ case '"': ret = get_string_tv(arg, rettv, evaluate); break; /* * Literal string constant: 'str''ing'. */ case '\'': ret = get_lit_string_tv(arg, rettv, evaluate); break; /* * List: [expr, expr] */ case '[': ret = get_list_tv(arg, rettv, evaluate); break; /* * Dictionary: {key: val, key: val} */ case '{': ret = get_dict_tv(arg, rettv, evaluate); break; /* * Option value: &name */ case '&': ret = get_option_tv(arg, rettv, evaluate); break; /* * Environment variable: $VAR. */ case '$': ret = get_env_tv(arg, rettv, evaluate); break; /* * Register contents: @r. */ case '@': ++*arg; if (evaluate) { rettv->v_type = VAR_STRING; rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE); } if (**arg != NUL) ++*arg; break; /* * nested expression: (expression). */ case '(': *arg = skipwhite(*arg + 1); ret = eval1(arg, rettv, evaluate); /* recursive! */ if (**arg == ')') ++*arg; else if (ret == OK) { EMSG(_("E110: Missing ')'")); clear_tv(rettv); ret = FAIL; } break; default: ret = NOTDONE; break; } if (ret == NOTDONE) { /* * Must be a variable or function name. * Can also be a curly-braces kind of name: {expr}. */ s = *arg; len = get_name_len(arg, &alias, evaluate, TRUE); if (alias != NULL) s = alias; if (len <= 0) ret = FAIL; else { if (**arg == '(') /* recursive! */ { /* If "s" is the name of a variable of type VAR_FUNC * use its contents. */ s = deref_func_name(s, &len); /* Invoke the function. */ ret = get_func_tv(s, len, rettv, arg, curwin->w_cursor.lnum, curwin->w_cursor.lnum, &len, evaluate, NULL); /* Stop the expression evaluation when immediately * aborting on error, or when an interrupt occurred or * an exception was thrown but not caught. */ if (aborting()) { if (ret == OK) clear_tv(rettv); ret = FAIL; } } else if (evaluate) ret = get_var_tv(s, len, rettv, TRUE); else ret = OK; } vim_free(alias); } *arg = skipwhite(*arg); /* Handle following '[', '(' and '.' for expr[expr], expr.name, * expr(expr). */ if (ret == OK) ret = handle_subscript(arg, rettv, evaluate, TRUE); /* * Apply logical NOT and unary '-', from right to left, ignore '+'. */ if (ret == OK && evaluate && end_leader > start_leader) { int error = FALSE; int val = 0; #ifdef FEAT_FLOAT float_T f = 0.0; if (rettv->v_type == VAR_FLOAT) f = rettv->vval.v_float; else #endif val = get_tv_number_chk(rettv, &error); if (error) { clear_tv(rettv); ret = FAIL; } else { while (end_leader > start_leader) { --end_leader; if (*end_leader == '!') { #ifdef FEAT_FLOAT if (rettv->v_type == VAR_FLOAT) f = !f; else #endif val = !val; } else if (*end_leader == '-') { #ifdef FEAT_FLOAT if (rettv->v_type == VAR_FLOAT) f = -f; else #endif val = -val; } } #ifdef FEAT_FLOAT if (rettv->v_type == VAR_FLOAT) { clear_tv(rettv); rettv->vval.v_float = f; } else #endif { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = val; } } } return ret; } /* * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key". * "*arg" points to the '[' or '.'. * Returns FAIL or OK. "*arg" is advanced to after the ']'. */ static int eval_index(arg, rettv, evaluate, verbose) char_u **arg; typval_T *rettv; int evaluate; int verbose; /* give error messages */ { int empty1 = FALSE, empty2 = FALSE; typval_T var1, var2; long n1, n2 = 0; long len = -1; int range = FALSE; char_u *s; char_u *key = NULL; if (rettv->v_type == VAR_FUNC #ifdef FEAT_FLOAT || rettv->v_type == VAR_FLOAT #endif ) { if (verbose) EMSG(_("E695: Cannot index a Funcref")); return FAIL; } if (**arg == '.') { /* * dict.name */ key = *arg + 1; for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len) ; if (len == 0) return FAIL; *arg = skipwhite(key + len); } else { /* * something[idx] * * Get the (first) variable from inside the []. */ *arg = skipwhite(*arg + 1); if (**arg == ':') empty1 = TRUE; else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */ return FAIL; else if (evaluate && get_tv_string_chk(&var1) == NULL) { /* not a number or string */ clear_tv(&var1); return FAIL; } /* * Get the second variable from inside the [:]. */ if (**arg == ':') { range = TRUE; *arg = skipwhite(*arg + 1); if (**arg == ']') empty2 = TRUE; else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */ { if (!empty1) clear_tv(&var1); return FAIL; } else if (evaluate && get_tv_string_chk(&var2) == NULL) { /* not a number or string */ if (!empty1) clear_tv(&var1); clear_tv(&var2); return FAIL; } } /* Check for the ']'. */ if (**arg != ']') { if (verbose) EMSG(_(e_missbrac)); clear_tv(&var1); if (range) clear_tv(&var2); return FAIL; } *arg = skipwhite(*arg + 1); /* skip the ']' */ } if (evaluate) { n1 = 0; if (!empty1 && rettv->v_type != VAR_DICT) { n1 = get_tv_number(&var1); clear_tv(&var1); } if (range) { if (empty2) n2 = -1; else { n2 = get_tv_number(&var2); clear_tv(&var2); } } switch (rettv->v_type) { case VAR_NUMBER: case VAR_STRING: s = get_tv_string(rettv); len = (long)STRLEN(s); if (range) { /* The resulting variable is a substring. If the indexes * are out of range the result is empty. */ if (n1 < 0) { n1 = len + n1; if (n1 < 0) n1 = 0; } if (n2 < 0) n2 = len + n2; else if (n2 >= len) n2 = len; if (n1 >= len || n2 < 0 || n1 > n2) s = NULL; else s = vim_strnsave(s + n1, (int)(n2 - n1 + 1)); } else { /* The resulting variable is a string of a single * character. If the index is too big or negative the * result is empty. */ if (n1 >= len || n1 < 0) s = NULL; else s = vim_strnsave(s + n1, 1); } clear_tv(rettv); rettv->v_type = VAR_STRING; rettv->vval.v_string = s; break; case VAR_LIST: len = list_len(rettv->vval.v_list); if (n1 < 0) n1 = len + n1; if (!empty1 && (n1 < 0 || n1 >= len)) { /* For a range we allow invalid values and return an empty * list. A list index out of range is an error. */ if (!range) { if (verbose) EMSGN(_(e_listidx), n1); return FAIL; } n1 = len; } if (range) { list_T *l; listitem_T *item; if (n2 < 0) n2 = len + n2; else if (n2 >= len) n2 = len - 1; if (!empty2 && (n2 < 0 || n2 + 1 < n1)) n2 = -1; l = list_alloc(); if (l == NULL) return FAIL; for (item = list_find(rettv->vval.v_list, n1); n1 <= n2; ++n1) { if (list_append_tv(l, &item->li_tv) == FAIL) { list_free(l, TRUE); return FAIL; } item = item->li_next; } clear_tv(rettv); rettv->v_type = VAR_LIST; rettv->vval.v_list = l; ++l->lv_refcount; } else { copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1); clear_tv(rettv); *rettv = var1; } break; case VAR_DICT: if (range) { if (verbose) EMSG(_(e_dictrange)); if (len == -1) clear_tv(&var1); return FAIL; } { dictitem_T *item; if (len == -1) { key = get_tv_string(&var1); if (*key == NUL) { if (verbose) EMSG(_(e_emptykey)); clear_tv(&var1); return FAIL; } } item = dict_find(rettv->vval.v_dict, key, (int)len); if (item == NULL && verbose) EMSG2(_(e_dictkey), key); if (len == -1) clear_tv(&var1); if (item == NULL) return FAIL; copy_tv(&item->di_tv, &var1); clear_tv(rettv); *rettv = var1; } break; } } return OK; } /* * Get an option value. * "arg" points to the '&' or '+' before the option name. * "arg" is advanced to character after the option name. * Return OK or FAIL. */ static int get_option_tv(arg, rettv, evaluate) char_u **arg; typval_T *rettv; /* when NULL, only check if option exists */ int evaluate; { char_u *option_end; long numval; char_u *stringval; int opt_type; int c; int working = (**arg == '+'); /* has("+option") */ int ret = OK; int opt_flags; /* * Isolate the option name and find its value. */ option_end = find_option_end(arg, &opt_flags); if (option_end == NULL) { if (rettv != NULL) EMSG2(_("E112: Option name missing: %s"), *arg); return FAIL; } if (!evaluate) { *arg = option_end; return OK; } c = *option_end; *option_end = NUL; opt_type = get_option_value(*arg, &numval, rettv == NULL ? NULL : &stringval, opt_flags); if (opt_type == -3) /* invalid name */ { if (rettv != NULL) EMSG2(_("E113: Unknown option: %s"), *arg); ret = FAIL; } else if (rettv != NULL) { if (opt_type == -2) /* hidden string option */ { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; } else if (opt_type == -1) /* hidden number option */ { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; } else if (opt_type == 1) /* number option */ { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = numval; } else /* string option */ { rettv->v_type = VAR_STRING; rettv->vval.v_string = stringval; } } else if (working && (opt_type == -2 || opt_type == -1)) ret = FAIL; *option_end = c; /* put back for error messages */ *arg = option_end; return ret; } /* * Allocate a variable for a string constant. * Return OK or FAIL. */ static int get_string_tv(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { char_u *p; char_u *name; int extra = 0; /* * Find the end of the string, skipping backslashed characters. */ for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p)) { if (*p == '\\' && p[1] != NUL) { ++p; /* A "\<x>" form occupies at least 4 characters, and produces up * to 6 characters: reserve space for 2 extra */ if (*p == '<') extra += 2; } } if (*p != '"') { EMSG2(_("E114: Missing quote: %s"), *arg); return FAIL; } /* If only parsing, set *arg and return here */ if (!evaluate) { *arg = p + 1; return OK; } /* * Copy the string into allocated memory, handling backslashed * characters. */ name = alloc((unsigned)(p - *arg + extra)); if (name == NULL) return FAIL; rettv->v_type = VAR_STRING; rettv->vval.v_string = name; for (p = *arg + 1; *p != NUL && *p != '"'; ) { if (*p == '\\') { switch (*++p) { case 'b': *name++ = BS; ++p; break; case 'e': *name++ = ESC; ++p; break; case 'f': *name++ = FF; ++p; break; case 'n': *name++ = NL; ++p; break; case 'r': *name++ = CAR; ++p; break; case 't': *name++ = TAB; ++p; break; case 'X': /* hex: "\x1", "\x12" */ case 'x': case 'u': /* Unicode: "\u0023" */ case 'U': if (vim_isxdigit(p[1])) { int n, nr; int c = toupper(*p); if (c == 'X') n = 2; else n = 4; nr = 0; while (--n >= 0 && vim_isxdigit(p[1])) { ++p; nr = (nr << 4) + hex2nr(*p); } ++p; #ifdef FEAT_MBYTE /* For "\u" store the number according to * 'encoding'. */ if (c != 'X') name += (*mb_char2bytes)(nr, name); else #endif *name++ = nr; } break; /* octal: "\1", "\12", "\123" */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': *name = *p++ - '0'; if (*p >= '0' && *p <= '7') { *name = (*name << 3) + *p++ - '0'; if (*p >= '0' && *p <= '7') *name = (*name << 3) + *p++ - '0'; } ++name; break; /* Special key, e.g.: "\<C-W>" */ case '<': extra = trans_special(&p, name, TRUE); if (extra != 0) { name += extra; break; } /* FALLTHROUGH */ default: MB_COPY_CHAR(p, name); break; } } else MB_COPY_CHAR(p, name); } *name = NUL; *arg = p + 1; return OK; } /* * Allocate a variable for a 'str''ing' constant. * Return OK or FAIL. */ static int get_lit_string_tv(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { char_u *p; char_u *str; int reduce = 0; /* * Find the end of the string, skipping ''. */ for (p = *arg + 1; *p != NUL; mb_ptr_adv(p)) { if (*p == '\'') { if (p[1] != '\'') break; ++reduce; ++p; } } if (*p != '\'') { EMSG2(_("E115: Missing quote: %s"), *arg); return FAIL; } /* If only parsing return after setting "*arg" */ if (!evaluate) { *arg = p + 1; return OK; } /* * Copy the string into allocated memory, handling '' to ' reduction. */ str = alloc((unsigned)((p - *arg) - reduce)); if (str == NULL) return FAIL; rettv->v_type = VAR_STRING; rettv->vval.v_string = str; for (p = *arg + 1; *p != NUL; ) { if (*p == '\'') { if (p[1] != '\'') break; ++p; } MB_COPY_CHAR(p, str); } *str = NUL; *arg = p + 1; return OK; } /* * Allocate a variable for a List and fill it from "*arg". * Return OK or FAIL. */ static int get_list_tv(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { list_T *l = NULL; typval_T tv; listitem_T *item; if (evaluate) { l = list_alloc(); if (l == NULL) return FAIL; } *arg = skipwhite(*arg + 1); while (**arg != ']' && **arg != NUL) { if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */ goto failret; if (evaluate) { item = listitem_alloc(); if (item != NULL) { item->li_tv = tv; item->li_tv.v_lock = 0; list_append(l, item); } else clear_tv(&tv); } if (**arg == ']') break; if (**arg != ',') { EMSG2(_("E696: Missing comma in List: %s"), *arg); goto failret; } *arg = skipwhite(*arg + 1); } if (**arg != ']') { EMSG2(_("E697: Missing end of List ']': %s"), *arg); failret: if (evaluate) list_free(l, TRUE); return FAIL; } *arg = skipwhite(*arg + 1); if (evaluate) { rettv->v_type = VAR_LIST; rettv->vval.v_list = l; ++l->lv_refcount; } return OK; } /* * Allocate an empty header for a list. * Caller should take care of the reference count. */ list_T * list_alloc() { list_T *l; l = (list_T *)alloc_clear(sizeof(list_T)); if (l != NULL) { /* Prepend the list to the list of lists for garbage collection. */ if (first_list != NULL) first_list->lv_used_prev = l; l->lv_used_prev = NULL; l->lv_used_next = first_list; first_list = l; } return l; } /* * Allocate an empty list for a return value. * Returns OK or FAIL. */ static int rettv_list_alloc(rettv) typval_T *rettv; { list_T *l = list_alloc(); if (l == NULL) return FAIL; rettv->vval.v_list = l; rettv->v_type = VAR_LIST; ++l->lv_refcount; return OK; } /* * Unreference a list: decrement the reference count and free it when it * becomes zero. */ void list_unref(l) list_T *l; { if (l != NULL && --l->lv_refcount <= 0) list_free(l, TRUE); } /* * Free a list, including all items it points to. * Ignores the reference count. */ void list_free(l, recurse) list_T *l; int recurse; /* Free Lists and Dictionaries recursively. */ { listitem_T *item; /* Remove the list from the list of lists for garbage collection. */ if (l->lv_used_prev == NULL) first_list = l->lv_used_next; else l->lv_used_prev->lv_used_next = l->lv_used_next; if (l->lv_used_next != NULL) l->lv_used_next->lv_used_prev = l->lv_used_prev; for (item = l->lv_first; item != NULL; item = l->lv_first) { /* Remove the item before deleting it. */ l->lv_first = item->li_next; if (recurse || (item->li_tv.v_type != VAR_LIST && item->li_tv.v_type != VAR_DICT)) clear_tv(&item->li_tv); vim_free(item); } vim_free(l); } /* * Allocate a list item. */ static listitem_T * listitem_alloc() { return (listitem_T *)alloc(sizeof(listitem_T)); } /* * Free a list item. Also clears the value. Does not notify watchers. */ static void listitem_free(item) listitem_T *item; { clear_tv(&item->li_tv); vim_free(item); } /* * Remove a list item from a List and free it. Also clears the value. */ static void listitem_remove(l, item) list_T *l; listitem_T *item; { list_remove(l, item, item); listitem_free(item); } /* * Get the number of items in a list. */ static long list_len(l) list_T *l; { if (l == NULL) return 0L; return l->lv_len; } /* * Return TRUE when two lists have exactly the same values. */ static int list_equal(l1, l2, ic, recursive) list_T *l1; list_T *l2; int ic; /* ignore case for strings */ int recursive; /* TRUE when used recursively */ { listitem_T *item1, *item2; if (l1 == NULL || l2 == NULL) return FALSE; if (l1 == l2) return TRUE; if (list_len(l1) != list_len(l2)) return FALSE; for (item1 = l1->lv_first, item2 = l2->lv_first; item1 != NULL && item2 != NULL; item1 = item1->li_next, item2 = item2->li_next) if (!tv_equal(&item1->li_tv, &item2->li_tv, ic, recursive)) return FALSE; return item1 == NULL && item2 == NULL; } #if defined(FEAT_RUBY) || defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) \ || defined(FEAT_MZSCHEME) || defined(FEAT_LUA) || defined(PROTO) /* * Return the dictitem that an entry in a hashtable points to. */ dictitem_T * dict_lookup(hi) hashitem_T *hi; { return HI2DI(hi); } #endif /* * Return TRUE when two dictionaries have exactly the same key/values. */ static int dict_equal(d1, d2, ic, recursive) dict_T *d1; dict_T *d2; int ic; /* ignore case for strings */ int recursive; /* TRUE when used recursively */ { hashitem_T *hi; dictitem_T *item2; int todo; if (d1 == NULL || d2 == NULL) return FALSE; if (d1 == d2) return TRUE; if (dict_len(d1) != dict_len(d2)) return FALSE; todo = (int)d1->dv_hashtab.ht_used; for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { item2 = dict_find(d2, hi->hi_key, -1); if (item2 == NULL) return FALSE; if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic, recursive)) return FALSE; --todo; } } return TRUE; } static int tv_equal_recurse_limit; /* * Return TRUE if "tv1" and "tv2" have the same value. * Compares the items just like "==" would compare them, but strings and * numbers are different. Floats and numbers are also different. */ static int tv_equal(tv1, tv2, ic, recursive) typval_T *tv1; typval_T *tv2; int ic; /* ignore case */ int recursive; /* TRUE when used recursively */ { char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN]; char_u *s1, *s2; static int recursive_cnt = 0; /* catch recursive loops */ int r; if (tv1->v_type != tv2->v_type) return FALSE; /* Catch lists and dicts that have an endless loop by limiting * recursiveness to a limit. We guess they are equal then. * A fixed limit has the problem of still taking an awful long time. * Reduce the limit every time running into it. That should work fine for * deeply linked structures that are not recursively linked and catch * recursiveness quickly. */ if (!recursive) tv_equal_recurse_limit = 1000; if (recursive_cnt >= tv_equal_recurse_limit) { --tv_equal_recurse_limit; return TRUE; } switch (tv1->v_type) { case VAR_LIST: ++recursive_cnt; r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic, TRUE); --recursive_cnt; return r; case VAR_DICT: ++recursive_cnt; r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic, TRUE); --recursive_cnt; return r; case VAR_FUNC: return (tv1->vval.v_string != NULL && tv2->vval.v_string != NULL && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0); case VAR_NUMBER: return tv1->vval.v_number == tv2->vval.v_number; #ifdef FEAT_FLOAT case VAR_FLOAT: return tv1->vval.v_float == tv2->vval.v_float; #endif case VAR_STRING: s1 = get_tv_string_buf(tv1, buf1); s2 = get_tv_string_buf(tv2, buf2); return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0); } EMSG2(_(e_intern2), "tv_equal()"); return TRUE; } /* * Locate item with index "n" in list "l" and return it. * A negative index is counted from the end; -1 is the last item. * Returns NULL when "n" is out of range. */ static listitem_T * list_find(l, n) list_T *l; long n; { listitem_T *item; long idx; if (l == NULL) return NULL; /* Negative index is relative to the end. */ if (n < 0) n = l->lv_len + n; /* Check for index out of range. */ if (n < 0 || n >= l->lv_len) return NULL; /* When there is a cached index may start search from there. */ if (l->lv_idx_item != NULL) { if (n < l->lv_idx / 2) { /* closest to the start of the list */ item = l->lv_first; idx = 0; } else if (n > (l->lv_idx + l->lv_len) / 2) { /* closest to the end of the list */ item = l->lv_last; idx = l->lv_len - 1; } else { /* closest to the cached index */ item = l->lv_idx_item; idx = l->lv_idx; } } else { if (n < l->lv_len / 2) { /* closest to the start of the list */ item = l->lv_first; idx = 0; } else { /* closest to the end of the list */ item = l->lv_last; idx = l->lv_len - 1; } } while (n > idx) { /* search forward */ item = item->li_next; ++idx; } while (n < idx) { /* search backward */ item = item->li_prev; --idx; } /* cache the used index */ l->lv_idx = idx; l->lv_idx_item = item; return item; } /* * Get list item "l[idx]" as a number. */ static long list_find_nr(l, idx, errorp) list_T *l; long idx; int *errorp; /* set to TRUE when something wrong */ { listitem_T *li; li = list_find(l, idx); if (li == NULL) { if (errorp != NULL) *errorp = TRUE; return -1L; } return get_tv_number_chk(&li->li_tv, errorp); } /* * Get list item "l[idx - 1]" as a string. Returns NULL for failure. */ char_u * list_find_str(l, idx) list_T *l; long idx; { listitem_T *li; li = list_find(l, idx - 1); if (li == NULL) { EMSGN(_(e_listidx), idx); return NULL; } return get_tv_string(&li->li_tv); } /* * Locate "item" list "l" and return its index. * Returns -1 when "item" is not in the list. */ static long list_idx_of_item(l, item) list_T *l; listitem_T *item; { long idx = 0; listitem_T *li; if (l == NULL) return -1; idx = 0; for (li = l->lv_first; li != NULL && li != item; li = li->li_next) ++idx; if (li == NULL) return -1; return idx; } /* * Append item "item" to the end of list "l". */ static void list_append(l, item) list_T *l; listitem_T *item; { if (l->lv_last == NULL) { /* empty list */ l->lv_first = item; l->lv_last = item; item->li_prev = NULL; } else { l->lv_last->li_next = item; item->li_prev = l->lv_last; l->lv_last = item; } ++l->lv_len; item->li_next = NULL; } /* * Append typval_T "tv" to the end of list "l". * Return FAIL when out of memory. */ int list_append_tv(l, tv) list_T *l; typval_T *tv; { listitem_T *li = listitem_alloc(); if (li == NULL) return FAIL; copy_tv(tv, &li->li_tv); list_append(l, li); return OK; } /* * Add a dictionary to a list. Used by getqflist(). * Return FAIL when out of memory. */ int list_append_dict(list, dict) list_T *list; dict_T *dict; { listitem_T *li = listitem_alloc(); if (li == NULL) return FAIL; li->li_tv.v_type = VAR_DICT; li->li_tv.v_lock = 0; li->li_tv.vval.v_dict = dict; list_append(list, li); ++dict->dv_refcount; return OK; } /* * Make a copy of "str" and append it as an item to list "l". * When "len" >= 0 use "str[len]". * Returns FAIL when out of memory. */ int list_append_string(l, str, len) list_T *l; char_u *str; int len; { listitem_T *li = listitem_alloc(); if (li == NULL) return FAIL; list_append(l, li); li->li_tv.v_type = VAR_STRING; li->li_tv.v_lock = 0; if (str == NULL) li->li_tv.vval.v_string = NULL; else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len) : vim_strsave(str))) == NULL) return FAIL; return OK; } /* * Append "n" to list "l". * Returns FAIL when out of memory. */ static int list_append_number(l, n) list_T *l; varnumber_T n; { listitem_T *li; li = listitem_alloc(); if (li == NULL) return FAIL; li->li_tv.v_type = VAR_NUMBER; li->li_tv.v_lock = 0; li->li_tv.vval.v_number = n; list_append(l, li); return OK; } /* * Insert typval_T "tv" in list "l" before "item". * If "item" is NULL append at the end. * Return FAIL when out of memory. */ static int list_insert_tv(l, tv, item) list_T *l; typval_T *tv; listitem_T *item; { listitem_T *ni = listitem_alloc(); if (ni == NULL) return FAIL; copy_tv(tv, &ni->li_tv); if (item == NULL) /* Append new item at end of list. */ list_append(l, ni); else { /* Insert new item before existing item. */ ni->li_prev = item->li_prev; ni->li_next = item; if (item->li_prev == NULL) { l->lv_first = ni; ++l->lv_idx; } else { item->li_prev->li_next = ni; l->lv_idx_item = NULL; } item->li_prev = ni; ++l->lv_len; } return OK; } /* * Extend "l1" with "l2". * If "bef" is NULL append at the end, otherwise insert before this item. * Returns FAIL when out of memory. */ static int list_extend(l1, l2, bef) list_T *l1; list_T *l2; listitem_T *bef; { listitem_T *item; int todo = l2->lv_len; /* We also quit the loop when we have inserted the original item count of * the list, avoid a hang when we extend a list with itself. */ for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next) if (list_insert_tv(l1, &item->li_tv, bef) == FAIL) return FAIL; return OK; } /* * Concatenate lists "l1" and "l2" into a new list, stored in "tv". * Return FAIL when out of memory. */ static int list_concat(l1, l2, tv) list_T *l1; list_T *l2; typval_T *tv; { list_T *l; if (l1 == NULL || l2 == NULL) return FAIL; /* make a copy of the first list. */ l = list_copy(l1, FALSE, 0); if (l == NULL) return FAIL; tv->v_type = VAR_LIST; tv->vval.v_list = l; /* append all items from the second list */ return list_extend(l, l2, NULL); } /* * Make a copy of list "orig". Shallow if "deep" is FALSE. * The refcount of the new list is set to 1. * See item_copy() for "copyID". * Returns NULL when out of memory. */ static list_T * list_copy(orig, deep, copyID) list_T *orig; int deep; int copyID; { list_T *copy; listitem_T *item; listitem_T *ni; if (orig == NULL) return NULL; copy = list_alloc(); if (copy != NULL) { if (copyID != 0) { /* Do this before adding the items, because one of the items may * refer back to this list. */ orig->lv_copyID = copyID; orig->lv_copylist = copy; } for (item = orig->lv_first; item != NULL && !got_int; item = item->li_next) { ni = listitem_alloc(); if (ni == NULL) break; if (deep) { if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL) { vim_free(ni); break; } } else copy_tv(&item->li_tv, &ni->li_tv); list_append(copy, ni); } ++copy->lv_refcount; if (item != NULL) { list_unref(copy); copy = NULL; } } return copy; } /* * Remove items "item" to "item2" from list "l". * Does not free the listitem or the value! */ static void list_remove(l, item, item2) list_T *l; listitem_T *item; listitem_T *item2; { listitem_T *ip; /* notify watchers */ for (ip = item; ip != NULL; ip = ip->li_next) { --l->lv_len; list_fix_watch(l, ip); if (ip == item2) break; } if (item2->li_next == NULL) l->lv_last = item->li_prev; else item2->li_next->li_prev = item->li_prev; if (item->li_prev == NULL) l->lv_first = item2->li_next; else item->li_prev->li_next = item2->li_next; l->lv_idx_item = NULL; } /* * Return an allocated string with the string representation of a list. * May return NULL. */ static char_u * list2string(tv, copyID) typval_T *tv; int copyID; { garray_T ga; if (tv->vval.v_list == NULL) return NULL; ga_init2(&ga, (int)sizeof(char), 80); ga_append(&ga, '['); if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL) { vim_free(ga.ga_data); return NULL; } ga_append(&ga, ']'); ga_append(&ga, NUL); return (char_u *)ga.ga_data; } typedef struct join_S { char_u *s; char_u *tofree; } join_T; static int list_join_inner(gap, l, sep, echo_style, copyID, join_gap) garray_T *gap; /* to store the result in */ list_T *l; char_u *sep; int echo_style; int copyID; garray_T *join_gap; /* to keep each list item string */ { int i; join_T *p; int len; int sumlen = 0; int first = TRUE; char_u *tofree; char_u numbuf[NUMBUFLEN]; listitem_T *item; char_u *s; /* Stringify each item in the list. */ for (item = l->lv_first; item != NULL && !got_int; item = item->li_next) { if (echo_style) s = echo_string(&item->li_tv, &tofree, numbuf, copyID); else s = tv2string(&item->li_tv, &tofree, numbuf, copyID); if (s == NULL) return FAIL; len = (int)STRLEN(s); sumlen += len; ga_grow(join_gap, 1); p = ((join_T *)join_gap->ga_data) + (join_gap->ga_len++); if (tofree != NULL || s != numbuf) { p->s = s; p->tofree = tofree; } else { p->s = vim_strnsave(s, len); p->tofree = p->s; } line_breakcheck(); } /* Allocate result buffer with its total size, avoid re-allocation and * multiple copy operations. Add 2 for a tailing ']' and NUL. */ if (join_gap->ga_len >= 2) sumlen += (int)STRLEN(sep) * (join_gap->ga_len - 1); if (ga_grow(gap, sumlen + 2) == FAIL) return FAIL; for (i = 0; i < join_gap->ga_len && !got_int; ++i) { if (first) first = FALSE; else ga_concat(gap, sep); p = ((join_T *)join_gap->ga_data) + i; if (p->s != NULL) ga_concat(gap, p->s); line_breakcheck(); } return OK; } /* * Join list "l" into a string in "*gap", using separator "sep". * When "echo_style" is TRUE use String as echoed, otherwise as inside a List. * Return FAIL or OK. */ static int list_join(gap, l, sep, echo_style, copyID) garray_T *gap; list_T *l; char_u *sep; int echo_style; int copyID; { garray_T join_ga; int retval; join_T *p; int i; ga_init2(&join_ga, (int)sizeof(join_T), l->lv_len); retval = list_join_inner(gap, l, sep, echo_style, copyID, &join_ga); /* Dispose each item in join_ga. */ if (join_ga.ga_data != NULL) { p = (join_T *)join_ga.ga_data; for (i = 0; i < join_ga.ga_len; ++i) { vim_free(p->tofree); ++p; } ga_clear(&join_ga); } return retval; } /* * Garbage collection for lists and dictionaries. * * We use reference counts to be able to free most items right away when they * are no longer used. But for composite items it's possible that it becomes * unused while the reference count is > 0: When there is a recursive * reference. Example: * :let l = [1, 2, 3] * :let d = {9: l} * :let l[1] = d * * Since this is quite unusual we handle this with garbage collection: every * once in a while find out which lists and dicts are not referenced from any * variable. * * Here is a good reference text about garbage collection (refers to Python * but it applies to all reference-counting mechanisms): * http://python.ca/nas/python/gc/ */ /* * Do garbage collection for lists and dicts. * Return TRUE if some memory was freed. */ int garbage_collect() { int copyID; buf_T *buf; win_T *wp; int i; funccall_T *fc, **pfc; int did_free; int did_free_funccal = FALSE; #ifdef FEAT_WINDOWS tabpage_T *tp; #endif /* Only do this once. */ want_garbage_collect = FALSE; may_garbage_collect = FALSE; garbage_collect_at_exit = FALSE; /* We advance by two because we add one for items referenced through * previous_funccal. */ current_copyID += COPYID_INC; copyID = current_copyID; /* * 1. Go through all accessible variables and mark all lists and dicts * with copyID. */ /* Don't free variables in the previous_funccal list unless they are only * referenced through previous_funccal. This must be first, because if * the item is referenced elsewhere the funccal must not be freed. */ for (fc = previous_funccal; fc != NULL; fc = fc->caller) { set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1); set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1); } /* script-local variables */ for (i = 1; i <= ga_scripts.ga_len; ++i) set_ref_in_ht(&SCRIPT_VARS(i), copyID); /* buffer-local variables */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID); /* window-local variables */ FOR_ALL_TAB_WINDOWS(tp, wp) set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID); #ifdef FEAT_WINDOWS /* tabpage-local variables */ for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID); #endif /* global variables */ set_ref_in_ht(&globvarht, copyID); /* function-local variables */ for (fc = current_funccal; fc != NULL; fc = fc->caller) { set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID); set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID); } /* v: vars */ set_ref_in_ht(&vimvarht, copyID); #ifdef FEAT_LUA set_ref_in_lua(copyID); #endif /* * 2. Free lists and dictionaries that are not referenced. */ did_free = free_unref_items(copyID); /* * 3. Check if any funccal can be freed now. */ for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal(fc, TRUE); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) /* When a funccal was freed some more items might be garbage * collected, so run again. */ (void)garbage_collect(); return did_free; } /* * Free lists and dictionaries that are no longer referenced. */ static int free_unref_items(copyID) int copyID; { dict_T *dd; list_T *ll; int did_free = FALSE; /* * Go through the list of dicts and free items without the copyID. */ for (dd = first_dict; dd != NULL; ) if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)) { /* Free the Dictionary and ordinary items it contains, but don't * recurse into Lists and Dictionaries, they will be in the list * of dicts or list of lists. */ dict_free(dd, FALSE); did_free = TRUE; /* restart, next dict may also have been freed */ dd = first_dict; } else dd = dd->dv_used_next; /* * Go through the list of lists and free items without the copyID. * But don't free a list that has a watcher (used in a for loop), these * are not referenced anywhere. */ for (ll = first_list; ll != NULL; ) if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK) && ll->lv_watch == NULL) { /* Free the List and ordinary items it contains, but don't recurse * into Lists and Dictionaries, they will be in the list of dicts * or list of lists. */ list_free(ll, FALSE); did_free = TRUE; /* restart, next list may also have been freed */ ll = first_list; } else ll = ll->lv_used_next; return did_free; } /* * Mark all lists and dicts referenced through hashtab "ht" with "copyID". */ static void set_ref_in_ht(ht, copyID) hashtab_T *ht; int copyID; { int todo; hashitem_T *hi; todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; set_ref_in_item(&HI2DI(hi)->di_tv, copyID); } } /* * Mark all lists and dicts referenced through list "l" with "copyID". */ static void set_ref_in_list(l, copyID) list_T *l; int copyID; { listitem_T *li; for (li = l->lv_first; li != NULL; li = li->li_next) set_ref_in_item(&li->li_tv, copyID); } /* * Mark all lists and dicts referenced through typval "tv" with "copyID". */ static void set_ref_in_item(tv, copyID) typval_T *tv; int copyID; { dict_T *dd; list_T *ll; switch (tv->v_type) { case VAR_DICT: dd = tv->vval.v_dict; if (dd != NULL && dd->dv_copyID != copyID) { /* Didn't see this dict yet. */ dd->dv_copyID = copyID; set_ref_in_ht(&dd->dv_hashtab, copyID); } break; case VAR_LIST: ll = tv->vval.v_list; if (ll != NULL && ll->lv_copyID != copyID) { /* Didn't see this list yet. */ ll->lv_copyID = copyID; set_ref_in_list(ll, copyID); } break; } return; } /* * Allocate an empty header for a dictionary. */ dict_T * dict_alloc() { dict_T *d; d = (dict_T *)alloc(sizeof(dict_T)); if (d != NULL) { /* Add the list to the list of dicts for garbage collection. */ if (first_dict != NULL) first_dict->dv_used_prev = d; d->dv_used_next = first_dict; d->dv_used_prev = NULL; first_dict = d; hash_init(&d->dv_hashtab); d->dv_lock = 0; d->dv_refcount = 0; d->dv_copyID = 0; } return d; } /* * Allocate an empty dict for a return value. * Returns OK or FAIL. */ static int rettv_dict_alloc(rettv) typval_T *rettv; { dict_T *d = dict_alloc(); if (d == NULL) return FAIL; rettv->vval.v_dict = d; rettv->v_type = VAR_DICT; ++d->dv_refcount; return OK; } /* * Unreference a Dictionary: decrement the reference count and free it when it * becomes zero. */ void dict_unref(d) dict_T *d; { if (d != NULL && --d->dv_refcount <= 0) dict_free(d, TRUE); } /* * Free a Dictionary, including all items it contains. * Ignores the reference count. */ static void dict_free(d, recurse) dict_T *d; int recurse; /* Free Lists and Dictionaries recursively. */ { int todo; hashitem_T *hi; dictitem_T *di; /* Remove the dict from the list of dicts for garbage collection. */ if (d->dv_used_prev == NULL) first_dict = d->dv_used_next; else d->dv_used_prev->dv_used_next = d->dv_used_next; if (d->dv_used_next != NULL) d->dv_used_next->dv_used_prev = d->dv_used_prev; /* Lock the hashtab, we don't want it to resize while freeing items. */ hash_lock(&d->dv_hashtab); todo = (int)d->dv_hashtab.ht_used; for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { /* Remove the item before deleting it, just in case there is * something recursive causing trouble. */ di = HI2DI(hi); hash_remove(&d->dv_hashtab, hi); if (recurse || (di->di_tv.v_type != VAR_LIST && di->di_tv.v_type != VAR_DICT)) clear_tv(&di->di_tv); vim_free(di); --todo; } } hash_clear(&d->dv_hashtab); vim_free(d); } /* * Allocate a Dictionary item. * The "key" is copied to the new item. * Note that the value of the item "di_tv" still needs to be initialized! * Returns NULL when out of memory. */ dictitem_T * dictitem_alloc(key) char_u *key; { dictitem_T *di; di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key))); if (di != NULL) { STRCPY(di->di_key, key); di->di_flags = 0; } return di; } /* * Make a copy of a Dictionary item. */ static dictitem_T * dictitem_copy(org) dictitem_T *org; { dictitem_T *di; di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(org->di_key))); if (di != NULL) { STRCPY(di->di_key, org->di_key); di->di_flags = 0; copy_tv(&org->di_tv, &di->di_tv); } return di; } /* * Remove item "item" from Dictionary "dict" and free it. */ static void dictitem_remove(dict, item) dict_T *dict; dictitem_T *item; { hashitem_T *hi; hi = hash_find(&dict->dv_hashtab, item->di_key); if (HASHITEM_EMPTY(hi)) EMSG2(_(e_intern2), "dictitem_remove()"); else hash_remove(&dict->dv_hashtab, hi); dictitem_free(item); } /* * Free a dict item. Also clears the value. */ void dictitem_free(item) dictitem_T *item; { clear_tv(&item->di_tv); vim_free(item); } /* * Make a copy of dict "d". Shallow if "deep" is FALSE. * The refcount of the new dict is set to 1. * See item_copy() for "copyID". * Returns NULL when out of memory. */ static dict_T * dict_copy(orig, deep, copyID) dict_T *orig; int deep; int copyID; { dict_T *copy; dictitem_T *di; int todo; hashitem_T *hi; if (orig == NULL) return NULL; copy = dict_alloc(); if (copy != NULL) { if (copyID != 0) { orig->dv_copyID = copyID; orig->dv_copydict = copy; } todo = (int)orig->dv_hashtab.ht_used; for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = dictitem_alloc(hi->hi_key); if (di == NULL) break; if (deep) { if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep, copyID) == FAIL) { vim_free(di); break; } } else copy_tv(&HI2DI(hi)->di_tv, &di->di_tv); if (dict_add(copy, di) == FAIL) { dictitem_free(di); break; } } } ++copy->dv_refcount; if (todo > 0) { dict_unref(copy); copy = NULL; } } return copy; } /* * Add item "item" to Dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add(d, item) dict_T *d; dictitem_T *item; { return hash_add(&d->dv_hashtab, item->di_key); } /* * Add a number or string entry to dictionary "d". * When "str" is NULL use number "nr", otherwise use "str". * Returns FAIL when out of memory and when key already exists. */ int dict_add_nr_str(d, key, nr, str) dict_T *d; char *key; long nr; char_u *str; { dictitem_T *item; item = dictitem_alloc((char_u *)key); if (item == NULL) return FAIL; item->di_tv.v_lock = 0; if (str == NULL) { item->di_tv.v_type = VAR_NUMBER; item->di_tv.vval.v_number = nr; } else { item->di_tv.v_type = VAR_STRING; item->di_tv.vval.v_string = vim_strsave(str); } if (dict_add(d, item) == FAIL) { dictitem_free(item); return FAIL; } return OK; } /* * Add a list entry to dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add_list(d, key, list) dict_T *d; char *key; list_T *list; { dictitem_T *item; item = dictitem_alloc((char_u *)key); if (item == NULL) return FAIL; item->di_tv.v_lock = 0; item->di_tv.v_type = VAR_LIST; item->di_tv.vval.v_list = list; if (dict_add(d, item) == FAIL) { dictitem_free(item); return FAIL; } ++list->lv_refcount; return OK; } /* * Get the number of items in a Dictionary. */ static long dict_len(d) dict_T *d; { if (d == NULL) return 0L; return (long)d->dv_hashtab.ht_used; } /* * Find item "key[len]" in Dictionary "d". * If "len" is negative use strlen(key). * Returns NULL when not found. */ dictitem_T * dict_find(d, key, len) dict_T *d; char_u *key; int len; { #define AKEYLEN 200 char_u buf[AKEYLEN]; char_u *akey; char_u *tofree = NULL; hashitem_T *hi; if (len < 0) akey = key; else if (len >= AKEYLEN) { tofree = akey = vim_strnsave(key, len); if (akey == NULL) return NULL; } else { /* Avoid a malloc/free by using buf[]. */ vim_strncpy(buf, key, len); akey = buf; } hi = hash_find(&d->dv_hashtab, akey); vim_free(tofree); if (HASHITEM_EMPTY(hi)) return NULL; return HI2DI(hi); } /* * Get a string item from a dictionary. * When "save" is TRUE allocate memory for it. * Returns NULL if the entry doesn't exist or out of memory. */ char_u * get_dict_string(d, key, save) dict_T *d; char_u *key; int save; { dictitem_T *di; char_u *s; di = dict_find(d, key, -1); if (di == NULL) return NULL; s = get_tv_string(&di->di_tv); if (save && s != NULL) s = vim_strsave(s); return s; } /* * Get a number item from a dictionary. * Returns 0 if the entry doesn't exist or out of memory. */ long get_dict_number(d, key) dict_T *d; char_u *key; { dictitem_T *di; di = dict_find(d, key, -1); if (di == NULL) return 0; return get_tv_number(&di->di_tv); } /* * Return an allocated string with the string representation of a Dictionary. * May return NULL. */ static char_u * dict2string(tv, copyID) typval_T *tv; int copyID; { garray_T ga; int first = TRUE; char_u *tofree; char_u numbuf[NUMBUFLEN]; hashitem_T *hi; char_u *s; dict_T *d; int todo; if ((d = tv->vval.v_dict) == NULL) return NULL; ga_init2(&ga, (int)sizeof(char), 80); ga_append(&ga, '{'); todo = (int)d->dv_hashtab.ht_used; for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; if (first) first = FALSE; else ga_concat(&ga, (char_u *)", "); tofree = string_quote(hi->hi_key, FALSE); if (tofree != NULL) { ga_concat(&ga, tofree); vim_free(tofree); } ga_concat(&ga, (char_u *)": "); s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID); if (s != NULL) ga_concat(&ga, s); vim_free(tofree); if (s == NULL) break; } } if (todo > 0) { vim_free(ga.ga_data); return NULL; } ga_append(&ga, '}'); ga_append(&ga, NUL); return (char_u *)ga.ga_data; } /* * Allocate a variable for a Dictionary and fill it from "*arg". * Return OK or FAIL. Returns NOTDONE for {expr}. */ static int get_dict_tv(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { dict_T *d = NULL; typval_T tvkey; typval_T tv; char_u *key = NULL; dictitem_T *item; char_u *start = skipwhite(*arg + 1); char_u buf[NUMBUFLEN]; /* * First check if it's not a curly-braces thing: {expr}. * Must do this without evaluating, otherwise a function may be called * twice. Unfortunately this means we need to call eval1() twice for the * first item. * But {} is an empty Dictionary. */ if (*start != '}') { if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */ return FAIL; if (*start == '}') return NOTDONE; } if (evaluate) { d = dict_alloc(); if (d == NULL) return FAIL; } tvkey.v_type = VAR_UNKNOWN; tv.v_type = VAR_UNKNOWN; *arg = skipwhite(*arg + 1); while (**arg != '}' && **arg != NUL) { if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */ goto failret; if (**arg != ':') { EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg); clear_tv(&tvkey); goto failret; } if (evaluate) { key = get_tv_string_buf_chk(&tvkey, buf); if (key == NULL || *key == NUL) { /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */ if (key != NULL) EMSG(_(e_emptykey)); clear_tv(&tvkey); goto failret; } } *arg = skipwhite(*arg + 1); if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */ { if (evaluate) clear_tv(&tvkey); goto failret; } if (evaluate) { item = dict_find(d, key, -1); if (item != NULL) { EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key); clear_tv(&tvkey); clear_tv(&tv); goto failret; } item = dictitem_alloc(key); clear_tv(&tvkey); if (item != NULL) { item->di_tv = tv; item->di_tv.v_lock = 0; if (dict_add(d, item) == FAIL) dictitem_free(item); } } if (**arg == '}') break; if (**arg != ',') { EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg); goto failret; } *arg = skipwhite(*arg + 1); } if (**arg != '}') { EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg); failret: if (evaluate) dict_free(d, TRUE); return FAIL; } *arg = skipwhite(*arg + 1); if (evaluate) { rettv->v_type = VAR_DICT; rettv->vval.v_dict = d; ++d->dv_refcount; } return OK; } /* * Return a string with the string representation of a variable. * If the memory is allocated "tofree" is set to it, otherwise NULL. * "numbuf" is used for a number. * Does not put quotes around strings, as ":echo" displays values. * When "copyID" is not NULL replace recursive lists and dicts with "...". * May return NULL. */ static char_u * echo_string(tv, tofree, numbuf, copyID) typval_T *tv; char_u **tofree; char_u *numbuf; int copyID; { static int recurse = 0; char_u *r = NULL; if (recurse >= DICT_MAXNEST) { EMSG(_("E724: variable nested too deep for displaying")); *tofree = NULL; return NULL; } ++recurse; switch (tv->v_type) { case VAR_FUNC: *tofree = NULL; r = tv->vval.v_string; break; case VAR_LIST: if (tv->vval.v_list == NULL) { *tofree = NULL; r = NULL; } else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID) { *tofree = NULL; r = (char_u *)"[...]"; } else { tv->vval.v_list->lv_copyID = copyID; *tofree = list2string(tv, copyID); r = *tofree; } break; case VAR_DICT: if (tv->vval.v_dict == NULL) { *tofree = NULL; r = NULL; } else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID) { *tofree = NULL; r = (char_u *)"{...}"; } else { tv->vval.v_dict->dv_copyID = copyID; *tofree = dict2string(tv, copyID); r = *tofree; } break; case VAR_STRING: case VAR_NUMBER: *tofree = NULL; r = get_tv_string_buf(tv, numbuf); break; #ifdef FEAT_FLOAT case VAR_FLOAT: *tofree = NULL; vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float); r = numbuf; break; #endif default: EMSG2(_(e_intern2), "echo_string()"); *tofree = NULL; } --recurse; return r; } /* * Return a string with the string representation of a variable. * If the memory is allocated "tofree" is set to it, otherwise NULL. * "numbuf" is used for a number. * Puts quotes around strings, so that they can be parsed back by eval(). * May return NULL. */ static char_u * tv2string(tv, tofree, numbuf, copyID) typval_T *tv; char_u **tofree; char_u *numbuf; int copyID; { switch (tv->v_type) { case VAR_FUNC: *tofree = string_quote(tv->vval.v_string, TRUE); return *tofree; case VAR_STRING: *tofree = string_quote(tv->vval.v_string, FALSE); return *tofree; #ifdef FEAT_FLOAT case VAR_FLOAT: *tofree = NULL; vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float); return numbuf; #endif case VAR_NUMBER: case VAR_LIST: case VAR_DICT: break; default: EMSG2(_(e_intern2), "tv2string()"); } return echo_string(tv, tofree, numbuf, copyID); } /* * Return string "str" in ' quotes, doubling ' characters. * If "str" is NULL an empty string is assumed. * If "function" is TRUE make it function('string'). */ static char_u * string_quote(str, function) char_u *str; int function; { unsigned len; char_u *p, *r, *s; len = (function ? 13 : 3); if (str != NULL) { len += (unsigned)STRLEN(str); for (p = str; *p != NUL; mb_ptr_adv(p)) if (*p == '\'') ++len; } s = r = alloc(len); if (r != NULL) { if (function) { STRCPY(r, "function('"); r += 10; } else *r++ = '\''; if (str != NULL) for (p = str; *p != NUL; ) { if (*p == '\'') *r++ = '\''; MB_COPY_CHAR(p, r); } *r++ = '\''; if (function) *r++ = ')'; *r++ = NUL; } return s; } #ifdef FEAT_FLOAT /* * Convert the string "text" to a floating point number. * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure * this always uses a decimal point. * Returns the length of the text that was consumed. */ static int string2float(text, value) char_u *text; float_T *value; /* result stored here */ { char *s = (char *)text; float_T f; f = strtod(s, &s); *value = f; return (int)((char_u *)s - text); } #endif /* * Get the value of an environment variable. * "arg" is pointing to the '$'. It is advanced to after the name. * If the environment variable was not set, silently assume it is empty. * Always return OK. */ static int get_env_tv(arg, rettv, evaluate) char_u **arg; typval_T *rettv; int evaluate; { char_u *string = NULL; int len; int cc; char_u *name; int mustfree = FALSE; ++*arg; name = *arg; len = get_env_len(arg); if (evaluate) { if (len != 0) { cc = name[len]; name[len] = NUL; /* first try vim_getenv(), fast for normal environment vars */ string = vim_getenv(name, &mustfree); if (string != NULL && *string != NUL) { if (!mustfree) string = vim_strsave(string); } else { if (mustfree) vim_free(string); /* next try expanding things like $VIM and ${HOME} */ string = expand_env_save(name - 1); if (string != NULL && *string == '$') { vim_free(string); string = NULL; } } name[len] = cc; } rettv->v_type = VAR_STRING; rettv->vval.v_string = string; } return OK; } /* * Array with names and number of arguments of all internal functions * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH! */ static struct fst { char *f_name; /* function name */ char f_min_argc; /* minimal number of arguments */ char f_max_argc; /* maximal number of arguments */ void (*f_func) __ARGS((typval_T *args, typval_T *rvar)); /* implementation of function */ } functions[] = { #ifdef FEAT_FLOAT {"abs", 1, 1, f_abs}, {"acos", 1, 1, f_acos}, /* WJMc */ #endif {"add", 2, 2, f_add}, {"and", 2, 2, f_and}, {"append", 2, 2, f_append}, {"argc", 0, 0, f_argc}, {"argidx", 0, 0, f_argidx}, {"argv", 0, 1, f_argv}, #ifdef FEAT_FLOAT {"asin", 1, 1, f_asin}, /* WJMc */ {"atan", 1, 1, f_atan}, {"atan2", 2, 2, f_atan2}, #endif {"browse", 4, 4, f_browse}, {"browsedir", 2, 2, f_browsedir}, {"bufexists", 1, 1, f_bufexists}, {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */ {"buffer_name", 1, 1, f_bufname}, /* obsolete */ {"buffer_number", 1, 1, f_bufnr}, /* obsolete */ {"buflisted", 1, 1, f_buflisted}, {"bufloaded", 1, 1, f_bufloaded}, {"bufname", 1, 1, f_bufname}, {"bufnr", 1, 2, f_bufnr}, {"bufwinnr", 1, 1, f_bufwinnr}, {"byte2line", 1, 1, f_byte2line}, {"byteidx", 2, 2, f_byteidx}, {"call", 2, 3, f_call}, #ifdef FEAT_FLOAT {"ceil", 1, 1, f_ceil}, #endif {"changenr", 0, 0, f_changenr}, {"char2nr", 1, 1, f_char2nr}, {"cindent", 1, 1, f_cindent}, {"clearmatches", 0, 0, f_clearmatches}, {"col", 1, 1, f_col}, #if defined(FEAT_INS_EXPAND) {"complete", 2, 2, f_complete}, {"complete_add", 1, 1, f_complete_add}, {"complete_check", 0, 0, f_complete_check}, #endif {"confirm", 1, 4, f_confirm}, {"copy", 1, 1, f_copy}, #ifdef FEAT_FLOAT {"cos", 1, 1, f_cos}, {"cosh", 1, 1, f_cosh}, #endif {"count", 2, 4, f_count}, {"cscope_connection",0,3, f_cscope_connection}, {"cursor", 1, 3, f_cursor}, {"deepcopy", 1, 2, f_deepcopy}, {"delete", 1, 1, f_delete}, {"did_filetype", 0, 0, f_did_filetype}, {"diff_filler", 1, 1, f_diff_filler}, {"diff_hlID", 2, 2, f_diff_hlID}, {"empty", 1, 1, f_empty}, {"escape", 2, 2, f_escape}, {"eval", 1, 1, f_eval}, {"eventhandler", 0, 0, f_eventhandler}, {"executable", 1, 1, f_executable}, {"exists", 1, 1, f_exists}, #ifdef FEAT_FLOAT {"exp", 1, 1, f_exp}, #endif {"expand", 1, 3, f_expand}, {"extend", 2, 3, f_extend}, {"feedkeys", 1, 2, f_feedkeys}, {"file_readable", 1, 1, f_filereadable}, /* obsolete */ {"filereadable", 1, 1, f_filereadable}, {"filewritable", 1, 1, f_filewritable}, {"filter", 2, 2, f_filter}, {"finddir", 1, 3, f_finddir}, {"findfile", 1, 3, f_findfile}, #ifdef FEAT_FLOAT {"float2nr", 1, 1, f_float2nr}, {"floor", 1, 1, f_floor}, {"fmod", 2, 2, f_fmod}, #endif {"fnameescape", 1, 1, f_fnameescape}, {"fnamemodify", 2, 2, f_fnamemodify}, {"foldclosed", 1, 1, f_foldclosed}, {"foldclosedend", 1, 1, f_foldclosedend}, {"foldlevel", 1, 1, f_foldlevel}, {"foldtext", 0, 0, f_foldtext}, {"foldtextresult", 1, 1, f_foldtextresult}, {"foreground", 0, 0, f_foreground}, {"function", 1, 1, f_function}, {"garbagecollect", 0, 1, f_garbagecollect}, {"get", 2, 3, f_get}, {"getbufline", 2, 3, f_getbufline}, {"getbufvar", 2, 2, f_getbufvar}, {"getchar", 0, 1, f_getchar}, {"getcharmod", 0, 0, f_getcharmod}, {"getcmdline", 0, 0, f_getcmdline}, {"getcmdpos", 0, 0, f_getcmdpos}, {"getcmdtype", 0, 0, f_getcmdtype}, {"getcwd", 0, 0, f_getcwd}, {"getfontname", 0, 1, f_getfontname}, {"getfperm", 1, 1, f_getfperm}, {"getfsize", 1, 1, f_getfsize}, {"getftime", 1, 1, f_getftime}, {"getftype", 1, 1, f_getftype}, {"getline", 1, 2, f_getline}, {"getloclist", 1, 1, f_getqflist}, {"getmatches", 0, 0, f_getmatches}, {"getpid", 0, 0, f_getpid}, {"getpos", 1, 1, f_getpos}, {"getqflist", 0, 0, f_getqflist}, {"getreg", 0, 2, f_getreg}, {"getregtype", 0, 1, f_getregtype}, {"gettabvar", 2, 2, f_gettabvar}, {"gettabwinvar", 3, 3, f_gettabwinvar}, {"getwinposx", 0, 0, f_getwinposx}, {"getwinposy", 0, 0, f_getwinposy}, {"getwinvar", 2, 2, f_getwinvar}, {"glob", 1, 3, f_glob}, {"globpath", 2, 3, f_globpath}, {"has", 1, 1, f_has}, {"has_key", 2, 2, f_has_key}, {"haslocaldir", 0, 0, f_haslocaldir}, {"hasmapto", 1, 3, f_hasmapto}, {"highlightID", 1, 1, f_hlID}, /* obsolete */ {"highlight_exists",1, 1, f_hlexists}, /* obsolete */ {"histadd", 2, 2, f_histadd}, {"histdel", 1, 2, f_histdel}, {"histget", 1, 2, f_histget}, {"histnr", 1, 1, f_histnr}, {"hlID", 1, 1, f_hlID}, {"hlexists", 1, 1, f_hlexists}, {"hostname", 0, 0, f_hostname}, {"iconv", 3, 3, f_iconv}, {"indent", 1, 1, f_indent}, {"index", 2, 4, f_index}, {"input", 1, 3, f_input}, {"inputdialog", 1, 3, f_inputdialog}, {"inputlist", 1, 1, f_inputlist}, {"inputrestore", 0, 0, f_inputrestore}, {"inputsave", 0, 0, f_inputsave}, {"inputsecret", 1, 2, f_inputsecret}, {"insert", 2, 3, f_insert}, {"invert", 1, 1, f_invert}, {"isdirectory", 1, 1, f_isdirectory}, {"islocked", 1, 1, f_islocked}, {"items", 1, 1, f_items}, {"join", 1, 2, f_join}, {"keys", 1, 1, f_keys}, {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */ {"len", 1, 1, f_len}, {"libcall", 3, 3, f_libcall}, {"libcallnr", 3, 3, f_libcallnr}, {"line", 1, 1, f_line}, {"line2byte", 1, 1, f_line2byte}, {"lispindent", 1, 1, f_lispindent}, {"localtime", 0, 0, f_localtime}, #ifdef FEAT_FLOAT {"log", 1, 1, f_log}, {"log10", 1, 1, f_log10}, #endif #ifdef FEAT_LUA {"luaeval", 1, 2, f_luaeval}, #endif {"map", 2, 2, f_map}, {"maparg", 1, 4, f_maparg}, {"mapcheck", 1, 3, f_mapcheck}, {"match", 2, 4, f_match}, {"matchadd", 2, 4, f_matchadd}, {"matcharg", 1, 1, f_matcharg}, {"matchdelete", 1, 1, f_matchdelete}, {"matchend", 2, 4, f_matchend}, {"matchlist", 2, 4, f_matchlist}, {"matchstr", 2, 4, f_matchstr}, {"max", 1, 1, f_max}, {"min", 1, 1, f_min}, #ifdef vim_mkdir {"mkdir", 1, 3, f_mkdir}, #endif {"mode", 0, 1, f_mode}, #ifdef FEAT_MZSCHEME {"mzeval", 1, 1, f_mzeval}, #endif {"nextnonblank", 1, 1, f_nextnonblank}, {"nr2char", 1, 1, f_nr2char}, {"or", 2, 2, f_or}, {"pathshorten", 1, 1, f_pathshorten}, #ifdef FEAT_FLOAT {"pow", 2, 2, f_pow}, #endif {"prevnonblank", 1, 1, f_prevnonblank}, {"printf", 2, 19, f_printf}, {"pumvisible", 0, 0, f_pumvisible}, {"range", 1, 3, f_range}, {"readfile", 1, 3, f_readfile}, {"reltime", 0, 2, f_reltime}, {"reltimestr", 1, 1, f_reltimestr}, {"remote_expr", 2, 3, f_remote_expr}, {"remote_foreground", 1, 1, f_remote_foreground}, {"remote_peek", 1, 2, f_remote_peek}, {"remote_read", 1, 1, f_remote_read}, {"remote_send", 2, 3, f_remote_send}, {"remove", 2, 3, f_remove}, {"rename", 2, 2, f_rename}, {"repeat", 2, 2, f_repeat}, {"resolve", 1, 1, f_resolve}, {"reverse", 1, 1, f_reverse}, #ifdef FEAT_FLOAT {"round", 1, 1, f_round}, #endif {"search", 1, 4, f_search}, {"searchdecl", 1, 3, f_searchdecl}, {"searchpair", 3, 7, f_searchpair}, {"searchpairpos", 3, 7, f_searchpairpos}, {"searchpos", 1, 4, f_searchpos}, {"server2client", 2, 2, f_server2client}, {"serverlist", 0, 0, f_serverlist}, {"setbufvar", 3, 3, f_setbufvar}, {"setcmdpos", 1, 1, f_setcmdpos}, {"setline", 2, 2, f_setline}, {"setloclist", 2, 3, f_setloclist}, {"setmatches", 1, 1, f_setmatches}, {"setpos", 2, 2, f_setpos}, {"setqflist", 1, 2, f_setqflist}, {"setreg", 2, 3, f_setreg}, {"settabvar", 3, 3, f_settabvar}, {"settabwinvar", 4, 4, f_settabwinvar}, {"setwinvar", 3, 3, f_setwinvar}, {"shellescape", 1, 2, f_shellescape}, {"simplify", 1, 1, f_simplify}, #ifdef FEAT_FLOAT {"sin", 1, 1, f_sin}, {"sinh", 1, 1, f_sinh}, #endif {"sort", 1, 3, f_sort}, {"soundfold", 1, 1, f_soundfold}, {"spellbadword", 0, 1, f_spellbadword}, {"spellsuggest", 1, 3, f_spellsuggest}, {"split", 1, 3, f_split}, #ifdef FEAT_FLOAT {"sqrt", 1, 1, f_sqrt}, {"str2float", 1, 1, f_str2float}, #endif {"str2nr", 1, 2, f_str2nr}, {"strchars", 1, 1, f_strchars}, {"strdisplaywidth", 1, 2, f_strdisplaywidth}, #ifdef HAVE_STRFTIME {"strftime", 1, 2, f_strftime}, #endif {"stridx", 2, 3, f_stridx}, {"string", 1, 1, f_string}, {"strlen", 1, 1, f_strlen}, {"strpart", 2, 3, f_strpart}, {"strridx", 2, 3, f_strridx}, {"strtrans", 1, 1, f_strtrans}, {"strwidth", 1, 1, f_strwidth}, {"submatch", 1, 1, f_submatch}, {"substitute", 4, 4, f_substitute}, {"synID", 3, 3, f_synID}, {"synIDattr", 2, 3, f_synIDattr}, {"synIDtrans", 1, 1, f_synIDtrans}, {"synconcealed", 2, 2, f_synconcealed}, {"synstack", 2, 2, f_synstack}, {"system", 1, 2, f_system}, {"tabpagebuflist", 0, 1, f_tabpagebuflist}, {"tabpagenr", 0, 1, f_tabpagenr}, {"tabpagewinnr", 1, 2, f_tabpagewinnr}, {"tagfiles", 0, 0, f_tagfiles}, {"taglist", 1, 1, f_taglist}, #ifdef FEAT_FLOAT {"tan", 1, 1, f_tan}, {"tanh", 1, 1, f_tanh}, #endif {"tempname", 0, 0, f_tempname}, {"test", 1, 1, f_test}, {"tolower", 1, 1, f_tolower}, {"toupper", 1, 1, f_toupper}, {"tr", 3, 3, f_tr}, #ifdef FEAT_FLOAT {"trunc", 1, 1, f_trunc}, #endif {"type", 1, 1, f_type}, {"undofile", 1, 1, f_undofile}, {"undotree", 0, 0, f_undotree}, {"values", 1, 1, f_values}, {"virtcol", 1, 1, f_virtcol}, {"visualmode", 0, 1, f_visualmode}, {"winbufnr", 1, 1, f_winbufnr}, {"wincol", 0, 0, f_wincol}, {"winheight", 1, 1, f_winheight}, {"winline", 0, 0, f_winline}, {"winnr", 0, 1, f_winnr}, {"winrestcmd", 0, 0, f_winrestcmd}, {"winrestview", 1, 1, f_winrestview}, {"winsaveview", 0, 0, f_winsaveview}, {"winwidth", 1, 1, f_winwidth}, {"writefile", 2, 3, f_writefile}, {"xor", 2, 2, f_xor}, }; #if defined(FEAT_CMDL_COMPL) || defined(PROTO) /* * Function given to ExpandGeneric() to obtain the list of internal * or user defined function names. */ char_u * get_function_name(xp, idx) expand_T *xp; int idx; { static int intidx = -1; char_u *name; if (idx == 0) intidx = -1; if (intidx < 0) { name = get_user_func_name(xp, idx); if (name != NULL) return name; } if (++intidx < (int)(sizeof(functions) / sizeof(struct fst))) { STRCPY(IObuff, functions[intidx].f_name); STRCAT(IObuff, "("); if (functions[intidx].f_max_argc == 0) STRCAT(IObuff, ")"); return IObuff; } return NULL; } /* * Function given to ExpandGeneric() to obtain the list of internal or * user defined variable or function names. */ char_u * get_expr_name(xp, idx) expand_T *xp; int idx; { static int intidx = -1; char_u *name; if (idx == 0) intidx = -1; if (intidx < 0) { name = get_function_name(xp, idx); if (name != NULL) return name; } return get_user_var_name(xp, ++intidx); } #endif /* FEAT_CMDL_COMPL */ #if defined(EBCDIC) || defined(PROTO) /* * Compare struct fst by function name. */ static int compare_func_name(s1, s2) const void *s1; const void *s2; { struct fst *p1 = (struct fst *)s1; struct fst *p2 = (struct fst *)s2; return STRCMP(p1->f_name, p2->f_name); } /* * Sort the function table by function name. * The sorting of the table above is ASCII dependant. * On machines using EBCDIC we have to sort it. */ static void sortFunctions() { int funcCnt = (int)(sizeof(functions) / sizeof(struct fst)) - 1; qsort(functions, (size_t)funcCnt, sizeof(struct fst), compare_func_name); } #endif /* * Find internal function in table above. * Return index, or -1 if not found */ static int find_internal_func(name) char_u *name; /* name of the function */ { int first = 0; int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1; int cmp; int x; /* * Find the function name in the table. Binary search. */ while (first <= last) { x = first + ((unsigned)(last - first) >> 1); cmp = STRCMP(name, functions[x].f_name); if (cmp < 0) last = x - 1; else if (cmp > 0) first = x + 1; else return x; } return -1; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". */ static char_u * deref_func_name(name, lenp) char_u *name; int *lenp; { dictitem_T *v; int cc; cc = name[*lenp]; name[*lenp] = NUL; v = find_var(name, NULL); name[*lenp] = cc; if (v != NULL && v->di_tv.v_type == VAR_FUNC) { if (v->di_tv.vval.v_string == NULL) { *lenp = 0; return (char_u *)""; /* just in case */ } *lenp = (int)STRLEN(v->di_tv.vval.v_string); return v->di_tv.vval.v_string; } return name; } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ static int get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange, evaluate, selfdict) char_u *name; /* name of the function */ int len; /* length of "name" */ typval_T *rettv; char_u **arg; /* argument, pointing to the '(' */ linenr_T firstline; /* first line of range */ linenr_T lastline; /* last line of range */ int *doesrange; /* return: function handled range */ int evaluate; dict_T *selfdict; /* Dictionary for "self" */ { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */ int argcount = 0; /* number of arguments found */ /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS) { argp = skipwhite(argp + 1); /* skip the '(' or ',' */ if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evaluate) == FAIL) { ret = FAIL; break; } ++argcount; if (*argp != ',') break; } if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) ret = call_func(name, len, rettv, argcount, argvars, firstline, lastline, doesrange, evaluate, selfdict); else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(N_("E740: Too many arguments for function %s"), name); else emsg_funcname(N_("E116: Invalid arguments for function %s"), name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); *arg = skipwhite(argp); return ret; } /* * Call a function with its resolved parameters * Return OK when the function can't be called, FAIL otherwise. * Also returns OK when an error was encountered while executing the function. */ static int call_func(funcname, len, rettv, argcount, argvars, firstline, lastline, doesrange, evaluate, selfdict) char_u *funcname; /* name of the function */ int len; /* length of "name" */ typval_T *rettv; /* return value goes here */ int argcount; /* number of "argvars" */ typval_T *argvars; /* vars for arguments, must have "argcount" PLUS ONE elements! */ linenr_T firstline; /* first line of range */ linenr_T lastline; /* last line of range */ int *doesrange; /* return: function handled range */ int evaluate; dict_T *selfdict; /* Dictionary for "self" */ { int ret = FAIL; #define ERROR_UNKNOWN 0 #define ERROR_TOOMANY 1 #define ERROR_TOOFEW 2 #define ERROR_SCRIPT 3 #define ERROR_DICT 4 #define ERROR_NONE 5 #define ERROR_OTHER 6 int error = ERROR_NONE; int i; int llen; ufunc_T *fp; #define FLEN_FIXED 40 char_u fname_buf[FLEN_FIXED + 1]; char_u *fname; char_u *name; /* Make a copy of the name, if it comes from a funcref variable it could * be changed or deleted in the called function. */ name = vim_strnsave(funcname, len); if (name == NULL) return ret; /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use fname_buf[] when it fits, otherwise allocate memory (slow). */ llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) /* "<SID>" or "s:" */ { if (current_SID <= 0) error = ERROR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc((unsigned)(i + STRLEN(name + llen) + 1)); if (fname == NULL) error = ERROR_OTHER; else { mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; *doesrange = FALSE; /* execute the function if no errors detected and executing */ if (evaluate && error == ERROR_NONE) { rettv->v_type = VAR_NUMBER; /* default rettv is number zero */ rettv->vval.v_number = 0; error = ERROR_UNKNOWN; if (!builtin_function(fname)) { /* * User defined function. */ fp = find_func(fname); #ifdef FEAT_AUTOCMD /* Trigger FuncUndefined event, may load the function. */ if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, fname, fname, TRUE, NULL) && !aborting()) { /* executed an autocommand, search for the function again */ fp = find_func(fname); } #endif /* Try loading a package. */ if (fp == NULL && script_autoload(fname, TRUE) && !aborting()) { /* loaded a package, search for the function again */ fp = find_func(fname); } if (fp != NULL) { if (fp->uf_flags & FC_RANGE) *doesrange = TRUE; if (argcount < fp->uf_args.ga_len) error = ERROR_TOOFEW; else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len) error = ERROR_TOOMANY; else if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = ERROR_DICT; else { /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); saveRedobuff(); ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, firstline, lastline, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name) && fp->uf_refcount <= 0) /* Function was unreferenced while being used, free it * now. */ func_free(fp); restoreRedobuff(); restore_search_patterns(); error = ERROR_NONE; } } } else { /* * Find the function name in the table, call its implementation. */ i = find_internal_func(fname); if (i >= 0) { if (argcount < functions[i].f_min_argc) error = ERROR_TOOFEW; else if (argcount > functions[i].f_max_argc) error = ERROR_TOOMANY; else { argvars[argcount].v_type = VAR_UNKNOWN; functions[i].f_func(argvars, rettv); error = ERROR_NONE; } } } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == ERROR_NONE) ret = OK; /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { switch (error) { case ERROR_UNKNOWN: emsg_funcname(N_("E117: Unknown function: %s"), name); break; case ERROR_TOOMANY: emsg_funcname(e_toomanyarg, name); break; case ERROR_TOOFEW: emsg_funcname(N_("E119: Not enough arguments for function: %s"), name); break; case ERROR_SCRIPT: emsg_funcname(N_("E120: Using <SID> not in a script context: %s"), name); break; case ERROR_DICT: emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"), name); break; } } if (fname != name && fname != fname_buf) vim_free(fname); vim_free(name); return ret; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ static void emsg_funcname(ermsg, name) char *ermsg; char_u *name; { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; EMSG2(_(ermsg), p); if (p != name) vim_free(p); } /* * Return TRUE for a non-zero Number and a non-empty String. */ static int non_zero_arg(argvars) typval_T *argvars; { return ((argvars[0].v_type == VAR_NUMBER && argvars[0].vval.v_number != 0) || (argvars[0].v_type == VAR_STRING && argvars[0].vval.v_string != NULL && *argvars[0].vval.v_string != NUL)); } /********************************************* * Implementation of the built-in functions */ #ifdef FEAT_FLOAT static int get_float_arg __ARGS((typval_T *argvars, float_T *f)); /* * Get the float value of "argvars[0]" into "f". * Returns FAIL when the argument is not a Number or Float. */ static int get_float_arg(argvars, f) typval_T *argvars; float_T *f; { if (argvars[0].v_type == VAR_FLOAT) { *f = argvars[0].vval.v_float; return OK; } if (argvars[0].v_type == VAR_NUMBER) { *f = (float_T)argvars[0].vval.v_number; return OK; } EMSG(_("E808: Number or Float required")); return FAIL; } /* * "abs(expr)" function */ static void f_abs(argvars, rettv) typval_T *argvars; typval_T *rettv; { if (argvars[0].v_type == VAR_FLOAT) { rettv->v_type = VAR_FLOAT; rettv->vval.v_float = fabs(argvars[0].vval.v_float); } else { varnumber_T n; int error = FALSE; n = get_tv_number_chk(&argvars[0], &error); if (error) rettv->vval.v_number = -1; else if (n > 0) rettv->vval.v_number = n; else rettv->vval.v_number = -n; } } /* * "acos()" function */ static void f_acos(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = acos(f); else rettv->vval.v_float = 0.0; } #endif /* * "add(list, item)" function */ static void f_add(argvars, rettv) typval_T *argvars; typval_T *rettv; { list_T *l; rettv->vval.v_number = 1; /* Default: Failed */ if (argvars[0].v_type == VAR_LIST) { if ((l = argvars[0].vval.v_list) != NULL && !tv_check_lock(l->lv_lock, (char_u *)_("add() argument")) && list_append_tv(l, &argvars[1]) == OK) copy_tv(&argvars[0], rettv); } else EMSG(_(e_listreq)); } /* * "and(expr, expr)" function */ static void f_and(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL) & get_tv_number_chk(&argvars[1], NULL); } /* * "append(lnum, string/list)" function */ static void f_append(argvars, rettv) typval_T *argvars; typval_T *rettv; { long lnum; char_u *line; list_T *l = NULL; listitem_T *li = NULL; typval_T *tv; long added = 0; lnum = get_tv_lnum(argvars); if (lnum >= 0 && lnum <= curbuf->b_ml.ml_line_count && u_save(lnum, lnum + 1) == OK) { if (argvars[1].v_type == VAR_LIST) { l = argvars[1].vval.v_list; if (l == NULL) return; li = l->lv_first; } for (;;) { if (l == NULL) tv = &argvars[1]; /* append a string */ else if (li == NULL) break; /* end of list */ else tv = &li->li_tv; /* append item from list */ line = get_tv_string_chk(tv); if (line == NULL) /* type error */ { rettv->vval.v_number = 1; /* Failed */ break; } ml_append(lnum + added, line, (colnr_T)0, FALSE); ++added; if (l == NULL) break; li = li->li_next; } appended_lines_mark(lnum, added); if (curwin->w_cursor.lnum > lnum) curwin->w_cursor.lnum += added; } else rettv->vval.v_number = 1; /* Failed */ } /* * "argc()" function */ static void f_argc(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = ARGCOUNT; } /* * "argidx()" function */ static void f_argidx(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = curwin->w_arg_idx; } /* * "argv(nr)" function */ static void f_argv(argvars, rettv) typval_T *argvars; typval_T *rettv; { int idx; if (argvars[0].v_type != VAR_UNKNOWN) { idx = get_tv_number_chk(&argvars[0], NULL); if (idx >= 0 && idx < ARGCOUNT) rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx])); else rettv->vval.v_string = NULL; rettv->v_type = VAR_STRING; } else if (rettv_list_alloc(rettv) == OK) for (idx = 0; idx < ARGCOUNT; ++idx) list_append_string(rettv->vval.v_list, alist_name(&ARGLIST[idx]), -1); } #ifdef FEAT_FLOAT /* * "asin()" function */ static void f_asin(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = asin(f); else rettv->vval.v_float = 0.0; } /* * "atan()" function */ static void f_atan(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = atan(f); else rettv->vval.v_float = 0.0; } /* * "atan2()" function */ static void f_atan2(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T fx, fy; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &fx) == OK && get_float_arg(&argvars[1], &fy) == OK) rettv->vval.v_float = atan2(fx, fy); else rettv->vval.v_float = 0.0; } #endif /* * "browse(save, title, initdir, default)" function */ static void f_browse(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_BROWSE int save; char_u *title; char_u *initdir; char_u *defname; char_u buf[NUMBUFLEN]; char_u buf2[NUMBUFLEN]; int error = FALSE; save = get_tv_number_chk(&argvars[0], &error); title = get_tv_string_chk(&argvars[1]); initdir = get_tv_string_buf_chk(&argvars[2], buf); defname = get_tv_string_buf_chk(&argvars[3], buf2); if (error || title == NULL || initdir == NULL || defname == NULL) rettv->vval.v_string = NULL; else rettv->vval.v_string = do_browse(save ? BROWSE_SAVE : 0, title, defname, NULL, initdir, NULL, curbuf); #else rettv->vval.v_string = NULL; #endif rettv->v_type = VAR_STRING; } /* * "browsedir(title, initdir)" function */ static void f_browsedir(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_BROWSE char_u *title; char_u *initdir; char_u buf[NUMBUFLEN]; title = get_tv_string_chk(&argvars[0]); initdir = get_tv_string_buf_chk(&argvars[1], buf); if (title == NULL || initdir == NULL) rettv->vval.v_string = NULL; else rettv->vval.v_string = do_browse(BROWSE_DIR, title, NULL, NULL, initdir, NULL, curbuf); #else rettv->vval.v_string = NULL; #endif rettv->v_type = VAR_STRING; } static buf_T *find_buffer __ARGS((typval_T *avar)); /* * Find a buffer by number or exact name. */ static buf_T * find_buffer(avar) typval_T *avar; { buf_T *buf = NULL; if (avar->v_type == VAR_NUMBER) buf = buflist_findnr((int)avar->vval.v_number); else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL) { buf = buflist_findname_exp(avar->vval.v_string); if (buf == NULL) { /* No full path name match, try a match with a URL or a "nofile" * buffer, these don't use the full path. */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (buf->b_fname != NULL && (path_with_url(buf->b_fname) #ifdef FEAT_QUICKFIX || bt_nofile(buf) #endif ) && STRCMP(buf->b_fname, avar->vval.v_string) == 0) break; } } return buf; } /* * "bufexists(expr)" function */ static void f_bufexists(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL); } /* * "buflisted(expr)" function */ static void f_buflisted(argvars, rettv) typval_T *argvars; typval_T *rettv; { buf_T *buf; buf = find_buffer(&argvars[0]); rettv->vval.v_number = (buf != NULL && buf->b_p_bl); } /* * "bufloaded(expr)" function */ static void f_bufloaded(argvars, rettv) typval_T *argvars; typval_T *rettv; { buf_T *buf; buf = find_buffer(&argvars[0]); rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL); } static buf_T *get_buf_tv __ARGS((typval_T *tv)); /* * Get buffer by number or pattern. */ static buf_T * get_buf_tv(tv) typval_T *tv; { char_u *name = tv->vval.v_string; int save_magic; char_u *save_cpo; buf_T *buf; if (tv->v_type == VAR_NUMBER) return buflist_findnr((int)tv->vval.v_number); if (tv->v_type != VAR_STRING) return NULL; if (name == NULL || *name == NUL) return curbuf; if (name[0] == '$' && name[1] == NUL) return lastbuf; /* Ignore 'magic' and 'cpoptions' here to make scripts portable */ save_magic = p_magic; p_magic = TRUE; save_cpo = p_cpo; p_cpo = (char_u *)""; buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name), TRUE, FALSE)); p_magic = save_magic; p_cpo = save_cpo; /* If not found, try expanding the name, like done for bufexists(). */ if (buf == NULL) buf = find_buffer(tv); return buf; } /* * "bufname(expr)" function */ static void f_bufname(argvars, rettv) typval_T *argvars; typval_T *rettv; { buf_T *buf; (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */ ++emsg_off; buf = get_buf_tv(&argvars[0]); rettv->v_type = VAR_STRING; if (buf != NULL && buf->b_fname != NULL) rettv->vval.v_string = vim_strsave(buf->b_fname); else rettv->vval.v_string = NULL; --emsg_off; } /* * "bufnr(expr)" function */ static void f_bufnr(argvars, rettv) typval_T *argvars; typval_T *rettv; { buf_T *buf; int error = FALSE; char_u *name; (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */ ++emsg_off; buf = get_buf_tv(&argvars[0]); --emsg_off; /* If the buffer isn't found and the second argument is not zero create a * new buffer. */ if (buf == NULL && argvars[1].v_type != VAR_UNKNOWN && get_tv_number_chk(&argvars[1], &error) != 0 && !error && (name = get_tv_string_chk(&argvars[0])) != NULL && !error) buf = buflist_new(name, NULL, (linenr_T)1, 0); if (buf != NULL) rettv->vval.v_number = buf->b_fnum; else rettv->vval.v_number = -1; } /* * "bufwinnr(nr)" function */ static void f_bufwinnr(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_WINDOWS win_T *wp; int winnr = 0; #endif buf_T *buf; (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */ ++emsg_off; buf = get_buf_tv(&argvars[0]); #ifdef FEAT_WINDOWS for (wp = firstwin; wp; wp = wp->w_next) { ++winnr; if (wp->w_buffer == buf) break; } rettv->vval.v_number = (wp != NULL ? winnr : -1); #else rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1); #endif --emsg_off; } /* * "byte2line(byte)" function */ static void f_byte2line(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifndef FEAT_BYTEOFF rettv->vval.v_number = -1; #else long boff = 0; boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */ if (boff < 0) rettv->vval.v_number = -1; else rettv->vval.v_number = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff); #endif } /* * "byteidx()" function */ static void f_byteidx(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_MBYTE char_u *t; #endif char_u *str; long idx; str = get_tv_string_chk(&argvars[0]); idx = get_tv_number_chk(&argvars[1], NULL); rettv->vval.v_number = -1; if (str == NULL || idx < 0) return; #ifdef FEAT_MBYTE t = str; for ( ; idx > 0; idx--) { if (*t == NUL) /* EOL reached */ return; t += (*mb_ptr2len)(t); } rettv->vval.v_number = (varnumber_T)(t - str); #else if ((size_t)idx <= STRLEN(str)) rettv->vval.v_number = idx; #endif } /* * "call(func, arglist)" function */ static void f_call(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *func; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; listitem_T *item; int dummy; dict_T *selfdict = NULL; if (argvars[1].v_type != VAR_LIST) { EMSG(_(e_listreq)); return; } if (argvars[1].vval.v_list == NULL) return; if (argvars[0].v_type == VAR_FUNC) func = argvars[0].vval.v_string; else func = get_tv_string(&argvars[0]); if (*func == NUL) return; /* type error or empty name */ if (argvars[2].v_type != VAR_UNKNOWN) { if (argvars[2].v_type != VAR_DICT) { EMSG(_(e_dictreq)); return; } selfdict = argvars[2].vval.v_dict; } for (item = argvars[1].vval.v_list->lv_first; item != NULL; item = item->li_next) { if (argc == MAX_FUNC_ARGS) { EMSG(_("E699: Too many arguments")); break; } /* Make a copy of each argument. This is needed to be able to set * v_lock to VAR_FIXED in the copy without changing the original list. */ copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) (void)call_func(func, (int)STRLEN(func), rettv, argc, argv, curwin->w_cursor.lnum, curwin->w_cursor.lnum, &dummy, TRUE, selfdict); /* Free the arguments. */ while (argc > 0) clear_tv(&argv[--argc]); } #ifdef FEAT_FLOAT /* * "ceil({float})" function */ static void f_ceil(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = ceil(f); else rettv->vval.v_float = 0.0; } #endif /* * "changenr()" function */ static void f_changenr(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = curbuf->b_u_seq_cur; } /* * "char2nr(string)" function */ static void f_char2nr(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_MBYTE if (has_mbyte) rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0])); else #endif rettv->vval.v_number = get_tv_string(&argvars[0])[0]; } /* * "cindent(lnum)" function */ static void f_cindent(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_CINDENT pos_T pos; linenr_T lnum; pos = curwin->w_cursor; lnum = get_tv_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = lnum; rettv->vval.v_number = get_c_indent(); curwin->w_cursor = pos; } else #endif rettv->vval.v_number = -1; } /* * "clearmatches()" function */ static void f_clearmatches(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_SEARCH_EXTRA clear_matches(curwin); #endif } /* * "col(string)" function */ static void f_col(argvars, rettv) typval_T *argvars; typval_T *rettv; { colnr_T col = 0; pos_T *fp; int fnum = curbuf->b_fnum; fp = var2fpos(&argvars[0], FALSE, &fnum); if (fp != NULL && fnum == curbuf->b_fnum) { if (fp->col == MAXCOL) { /* '> can be MAXCOL, get the length of the line then */ if (fp->lnum <= curbuf->b_ml.ml_line_count) col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1; else col = MAXCOL; } else { col = fp->col + 1; #ifdef FEAT_VIRTUALEDIT /* col(".") when the cursor is on the NUL at the end of the line * because of "coladd" can be seen as an extra column. */ if (virtual_active() && fp == &curwin->w_cursor) { char_u *p = ml_get_cursor(); if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p, curwin->w_virtcol - curwin->w_cursor.coladd)) { # ifdef FEAT_MBYTE int l; if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL) col += l; # else if (*p != NUL && p[1] == NUL) ++col; # endif } } #endif } } rettv->vval.v_number = col; } #if defined(FEAT_INS_EXPAND) /* * "complete()" function */ static void f_complete(argvars, rettv) typval_T *argvars; typval_T *rettv UNUSED; { int startcol; if ((State & INSERT) == 0) { EMSG(_("E785: complete() can only be used in Insert mode")); return; } /* Check for undo allowed here, because if something was already inserted * the line was already saved for undo and this check isn't done. */ if (!undo_allowed()) return; if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL) { EMSG(_(e_invarg)); return; } startcol = get_tv_number_chk(&argvars[0], NULL); if (startcol <= 0) return; set_completion(startcol - 1, argvars[1].vval.v_list); } /* * "complete_add()" function */ static void f_complete_add(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0); } /* * "complete_check()" function */ static void f_complete_check(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { int saved = RedrawingDisabled; RedrawingDisabled = 0; ins_compl_check_keys(0); rettv->vval.v_number = compl_interrupted; RedrawingDisabled = saved; } #endif /* * "confirm(message, buttons[, default [, type]])" function */ static void f_confirm(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) char_u *message; char_u *buttons = NULL; char_u buf[NUMBUFLEN]; char_u buf2[NUMBUFLEN]; int def = 1; int type = VIM_GENERIC; char_u *typestr; int error = FALSE; message = get_tv_string_chk(&argvars[0]); if (message == NULL) error = TRUE; if (argvars[1].v_type != VAR_UNKNOWN) { buttons = get_tv_string_buf_chk(&argvars[1], buf); if (buttons == NULL) error = TRUE; if (argvars[2].v_type != VAR_UNKNOWN) { def = get_tv_number_chk(&argvars[2], &error); if (argvars[3].v_type != VAR_UNKNOWN) { typestr = get_tv_string_buf_chk(&argvars[3], buf2); if (typestr == NULL) error = TRUE; else { switch (TOUPPER_ASC(*typestr)) { case 'E': type = VIM_ERROR; break; case 'Q': type = VIM_QUESTION; break; case 'I': type = VIM_INFO; break; case 'W': type = VIM_WARNING; break; case 'G': type = VIM_GENERIC; break; } } } } } if (buttons == NULL || *buttons == NUL) buttons = (char_u *)_("&Ok"); if (!error) rettv->vval.v_number = do_dialog(type, NULL, message, buttons, def, NULL, FALSE); #endif } /* * "copy()" function */ static void f_copy(argvars, rettv) typval_T *argvars; typval_T *rettv; { item_copy(&argvars[0], rettv, FALSE, 0); } #ifdef FEAT_FLOAT /* * "cos()" function */ static void f_cos(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = cos(f); else rettv->vval.v_float = 0.0; } /* * "cosh()" function */ static void f_cosh(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = cosh(f); else rettv->vval.v_float = 0.0; } #endif /* * "count()" function */ static void f_count(argvars, rettv) typval_T *argvars; typval_T *rettv; { long n = 0; int ic = FALSE; if (argvars[0].v_type == VAR_LIST) { listitem_T *li; list_T *l; long idx; if ((l = argvars[0].vval.v_list) != NULL) { li = l->lv_first; if (argvars[2].v_type != VAR_UNKNOWN) { int error = FALSE; ic = get_tv_number_chk(&argvars[2], &error); if (argvars[3].v_type != VAR_UNKNOWN) { idx = get_tv_number_chk(&argvars[3], &error); if (!error) { li = list_find(l, idx); if (li == NULL) EMSGN(_(e_listidx), idx); } } if (error) li = NULL; } for ( ; li != NULL; li = li->li_next) if (tv_equal(&li->li_tv, &argvars[1], ic, FALSE)) ++n; } } else if (argvars[0].v_type == VAR_DICT) { int todo; dict_T *d; hashitem_T *hi; if ((d = argvars[0].vval.v_dict) != NULL) { int error = FALSE; if (argvars[2].v_type != VAR_UNKNOWN) { ic = get_tv_number_chk(&argvars[2], &error); if (argvars[3].v_type != VAR_UNKNOWN) EMSG(_(e_invarg)); } todo = error ? 0 : (int)d->dv_hashtab.ht_used; for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic, FALSE)) ++n; } } } } else EMSG2(_(e_listdictarg), "count()"); rettv->vval.v_number = n; } /* * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function * * Checks the existence of a cscope connection. */ static void f_cscope_connection(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_CSCOPE int num = 0; char_u *dbpath = NULL; char_u *prepend = NULL; char_u buf[NUMBUFLEN]; if (argvars[0].v_type != VAR_UNKNOWN && argvars[1].v_type != VAR_UNKNOWN) { num = (int)get_tv_number(&argvars[0]); dbpath = get_tv_string(&argvars[1]); if (argvars[2].v_type != VAR_UNKNOWN) prepend = get_tv_string_buf(&argvars[2], buf); } rettv->vval.v_number = cs_connection(num, dbpath, prepend); #endif } /* * "cursor(lnum, col)" function * * Moves the cursor to the specified line and column. * Returns 0 when the position could be set, -1 otherwise. */ static void f_cursor(argvars, rettv) typval_T *argvars; typval_T *rettv; { long line, col; #ifdef FEAT_VIRTUALEDIT long coladd = 0; #endif rettv->vval.v_number = -1; if (argvars[1].v_type == VAR_UNKNOWN) { pos_T pos; if (list2fpos(argvars, &pos, NULL) == FAIL) return; line = pos.lnum; col = pos.col; #ifdef FEAT_VIRTUALEDIT coladd = pos.coladd; #endif } else { line = get_tv_lnum(argvars); col = get_tv_number_chk(&argvars[1], NULL); #ifdef FEAT_VIRTUALEDIT if (argvars[2].v_type != VAR_UNKNOWN) coladd = get_tv_number_chk(&argvars[2], NULL); #endif } if (line < 0 || col < 0 #ifdef FEAT_VIRTUALEDIT || coladd < 0 #endif ) return; /* type error; errmsg already given */ if (line > 0) curwin->w_cursor.lnum = line; if (col > 0) curwin->w_cursor.col = col - 1; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = coladd; #endif /* Make sure the cursor is in a valid position. */ check_cursor(); #ifdef FEAT_MBYTE /* Correct cursor for multi-byte character. */ if (has_mbyte) mb_adjust_cursor(); #endif curwin->w_set_curswant = TRUE; rettv->vval.v_number = 0; } /* * "deepcopy()" function */ static void f_deepcopy(argvars, rettv) typval_T *argvars; typval_T *rettv; { int noref = 0; if (argvars[1].v_type != VAR_UNKNOWN) noref = get_tv_number_chk(&argvars[1], NULL); if (noref < 0 || noref > 1) EMSG(_(e_invarg)); else { current_copyID += COPYID_INC; item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0); } } /* * "delete()" function */ static void f_delete(argvars, rettv) typval_T *argvars; typval_T *rettv; { if (check_restricted() || check_secure()) rettv->vval.v_number = -1; else rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0])); } /* * "did_filetype()" function */ static void f_did_filetype(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_AUTOCMD rettv->vval.v_number = did_filetype; #endif } /* * "diff_filler()" function */ static void f_diff_filler(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_DIFF rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars)); #endif } /* * "diff_hlID()" function */ static void f_diff_hlID(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_DIFF linenr_T lnum = get_tv_lnum(argvars); static linenr_T prev_lnum = 0; static int changedtick = 0; static int fnum = 0; static int change_start = 0; static int change_end = 0; static hlf_T hlID = (hlf_T)0; int filler_lines; int col; if (lnum < 0) /* ignore type error in {lnum} arg */ lnum = 0; if (lnum != prev_lnum || changedtick != curbuf->b_changedtick || fnum != curbuf->b_fnum) { /* New line, buffer, change: need to get the values. */ filler_lines = diff_check(curwin, lnum); if (filler_lines < 0) { if (filler_lines == -1) { change_start = MAXCOL; change_end = -1; if (diff_find_change(curwin, lnum, &change_start, &change_end)) hlID = HLF_ADD; /* added line */ else hlID = HLF_CHD; /* changed line */ } else hlID = HLF_ADD; /* added line */ } else hlID = (hlf_T)0; prev_lnum = lnum; changedtick = curbuf->b_changedtick; fnum = curbuf->b_fnum; } if (hlID == HLF_CHD || hlID == HLF_TXD) { col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */ if (col >= change_start && col <= change_end) hlID = HLF_TXD; /* changed text */ else hlID = HLF_CHD; /* changed line */ } rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID; #endif } /* * "empty({expr})" function */ static void f_empty(argvars, rettv) typval_T *argvars; typval_T *rettv; { int n; switch (argvars[0].v_type) { case VAR_STRING: case VAR_FUNC: n = argvars[0].vval.v_string == NULL || *argvars[0].vval.v_string == NUL; break; case VAR_NUMBER: n = argvars[0].vval.v_number == 0; break; #ifdef FEAT_FLOAT case VAR_FLOAT: n = argvars[0].vval.v_float == 0.0; break; #endif case VAR_LIST: n = argvars[0].vval.v_list == NULL || argvars[0].vval.v_list->lv_first == NULL; break; case VAR_DICT: n = argvars[0].vval.v_dict == NULL || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0; break; default: EMSG2(_(e_intern2), "f_empty()"); n = 0; } rettv->vval.v_number = n; } /* * "escape({string}, {chars})" function */ static void f_escape(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u buf[NUMBUFLEN]; rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]), get_tv_string_buf(&argvars[1], buf)); rettv->v_type = VAR_STRING; } /* * "eval()" function */ static void f_eval(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *s; s = get_tv_string_chk(&argvars[0]); if (s != NULL) s = skipwhite(s); if (s == NULL || eval1(&s, rettv, TRUE) == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; } else if (*s != NUL) EMSG(_(e_trailing)); } /* * "eventhandler()" function */ static void f_eventhandler(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = vgetc_busy; } /* * "executable()" function */ static void f_executable(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0])); } /* * "exists()" function */ static void f_exists(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *p; char_u *name; int n = FALSE; int len = 0; no_autoload = TRUE; p = get_tv_string(&argvars[0]); if (*p == '$') /* environment variable */ { /* first try "normal" environment variables (fast) */ if (mch_getenv(p + 1) != NULL) n = TRUE; else { /* try expanding things like $VIM and ${HOME} */ p = expand_env_save(p); if (p != NULL && *p != '$') n = TRUE; vim_free(p); } } else if (*p == '&' || *p == '+') /* option */ { n = (get_option_tv(&p, NULL, TRUE) == OK); if (*skipwhite(p) != NUL) n = FALSE; /* trailing garbage */ } else if (*p == '*') /* internal or user defined function */ { n = function_exists(p + 1); } else if (*p == ':') { n = cmd_exists(p + 1); } else if (*p == '#') { #ifdef FEAT_AUTOCMD if (p[1] == '#') n = autocmd_supported(p + 2); else n = au_exists(p + 1); #endif } else /* internal variable */ { char_u *tofree; typval_T tv; /* get_name_len() takes care of expanding curly braces */ name = p; len = get_name_len(&p, &tofree, TRUE, FALSE); if (len > 0) { if (tofree != NULL) name = tofree; n = (get_var_tv(name, len, &tv, FALSE) == OK); if (n) { /* handle d.key, l[idx], f(expr) */ n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK); if (n) clear_tv(&tv); } } if (*p != NUL) n = FALSE; vim_free(tofree); } rettv->vval.v_number = n; no_autoload = FALSE; } #ifdef FEAT_FLOAT /* * "exp()" function */ static void f_exp(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = exp(f); else rettv->vval.v_float = 0.0; } #endif /* * "expand()" function */ static void f_expand(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *s; int len; char_u *errormsg; int options = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND; expand_T xpc; int error = FALSE; char_u *result; rettv->v_type = VAR_STRING; if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN && get_tv_number_chk(&argvars[2], &error) && !error) { rettv->v_type = VAR_LIST; rettv->vval.v_list = NULL; } s = get_tv_string(&argvars[0]); if (*s == '%' || *s == '#' || *s == '<') { ++emsg_off; result = eval_vars(s, s, &len, NULL, &errormsg, NULL); --emsg_off; if (rettv->v_type == VAR_LIST) { if (rettv_list_alloc(rettv) != FAIL && result != NULL) list_append_string(rettv->vval.v_list, result, -1); else vim_free(result); } else rettv->vval.v_string = result; } else { /* When the optional second argument is non-zero, don't remove matches * for 'wildignore' and don't put matches for 'suffixes' at the end. */ if (argvars[1].v_type != VAR_UNKNOWN && get_tv_number_chk(&argvars[1], &error)) options |= WILD_KEEP_ALL; if (!error) { ExpandInit(&xpc); xpc.xp_context = EXPAND_FILES; if (p_wic) options += WILD_ICASE; if (rettv->v_type == VAR_STRING) rettv->vval.v_string = ExpandOne(&xpc, s, NULL, options, WILD_ALL); else if (rettv_list_alloc(rettv) != FAIL) { int i; ExpandOne(&xpc, s, NULL, options, WILD_ALL_KEEP); for (i = 0; i < xpc.xp_numfiles; i++) list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1); ExpandCleanup(&xpc); } } else rettv->vval.v_string = NULL; } } /* * "extend(list, list [, idx])" function * "extend(dict, dict [, action])" function */ static void f_extend(argvars, rettv) typval_T *argvars; typval_T *rettv; { char *arg_errmsg = N_("extend() argument"); if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST) { list_T *l1, *l2; listitem_T *item; long before; int error = FALSE; l1 = argvars[0].vval.v_list; l2 = argvars[1].vval.v_list; if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)_(arg_errmsg)) && l2 != NULL) { if (argvars[2].v_type != VAR_UNKNOWN) { before = get_tv_number_chk(&argvars[2], &error); if (error) return; /* type error; errmsg already given */ if (before == l1->lv_len) item = NULL; else { item = list_find(l1, before); if (item == NULL) { EMSGN(_(e_listidx), before); return; } } } else item = NULL; list_extend(l1, l2, item); copy_tv(&argvars[0], rettv); } } else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT) { dict_T *d1, *d2; dictitem_T *di1; char_u *action; int i; hashitem_T *hi2; int todo; d1 = argvars[0].vval.v_dict; d2 = argvars[1].vval.v_dict; if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)_(arg_errmsg)) && d2 != NULL) { /* Check the third argument. */ if (argvars[2].v_type != VAR_UNKNOWN) { static char *(av[]) = {"keep", "force", "error"}; action = get_tv_string_chk(&argvars[2]); if (action == NULL) return; /* type error; errmsg already given */ for (i = 0; i < 3; ++i) if (STRCMP(action, av[i]) == 0) break; if (i == 3) { EMSG2(_(e_invarg2), action); return; } } else action = (char_u *)"force"; /* Go over all entries in the second dict and add them to the * first dict. */ todo = (int)d2->dv_hashtab.ht_used; for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2) { if (!HASHITEM_EMPTY(hi2)) { --todo; di1 = dict_find(d1, hi2->hi_key, -1); if (di1 == NULL) { di1 = dictitem_copy(HI2DI(hi2)); if (di1 != NULL && dict_add(d1, di1) == FAIL) dictitem_free(di1); } else if (*action == 'e') { EMSG2(_("E737: Key already exists: %s"), hi2->hi_key); break; } else if (*action == 'f' && HI2DI(hi2) != di1) { clear_tv(&di1->di_tv); copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv); } } } copy_tv(&argvars[0], rettv); } } else EMSG2(_(e_listdictarg), "extend()"); } /* * "feedkeys()" function */ static void f_feedkeys(argvars, rettv) typval_T *argvars; typval_T *rettv UNUSED; { int remap = TRUE; char_u *keys, *flags; char_u nbuf[NUMBUFLEN]; int typed = FALSE; char_u *keys_esc; /* This is not allowed in the sandbox. If the commands would still be * executed in the sandbox it would be OK, but it probably happens later, * when "sandbox" is no longer set. */ if (check_secure()) return; keys = get_tv_string(&argvars[0]); if (*keys != NUL) { if (argvars[1].v_type != VAR_UNKNOWN) { flags = get_tv_string_buf(&argvars[1], nbuf); for ( ; *flags != NUL; ++flags) { switch (*flags) { case 'n': remap = FALSE; break; case 'm': remap = TRUE; break; case 't': typed = TRUE; break; } } } /* Need to escape K_SPECIAL and CSI before putting the string in the * typeahead buffer. */ keys_esc = vim_strsave_escape_csi(keys); if (keys_esc != NULL) { ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE), typebuf.tb_len, !typed, FALSE); vim_free(keys_esc); if (vgetc_busy) typebuf_was_filled = TRUE; } } } /* * "filereadable()" function */ static void f_filereadable(argvars, rettv) typval_T *argvars; typval_T *rettv; { int fd; char_u *p; int n; #ifndef O_NONBLOCK # define O_NONBLOCK 0 #endif p = get_tv_string(&argvars[0]); if (*p && !mch_isdir(p) && (fd = mch_open((char *)p, O_RDONLY | O_NONBLOCK, 0)) >= 0) { n = TRUE; close(fd); } else n = FALSE; rettv->vval.v_number = n; } /* * Return 0 for not writable, 1 for writable file, 2 for a dir which we have * rights to write into. */ static void f_filewritable(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = filewritable(get_tv_string(&argvars[0])); } static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what)); static void findfilendir(argvars, rettv, find_what) typval_T *argvars; typval_T *rettv; int find_what; { #ifdef FEAT_SEARCHPATH char_u *fname; char_u *fresult = NULL; char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path; char_u *p; char_u pathbuf[NUMBUFLEN]; int count = 1; int first = TRUE; int error = FALSE; #endif rettv->vval.v_string = NULL; rettv->v_type = VAR_STRING; #ifdef FEAT_SEARCHPATH fname = get_tv_string(&argvars[0]); if (argvars[1].v_type != VAR_UNKNOWN) { p = get_tv_string_buf_chk(&argvars[1], pathbuf); if (p == NULL) error = TRUE; else { if (*p != NUL) path = p; if (argvars[2].v_type != VAR_UNKNOWN) count = get_tv_number_chk(&argvars[2], &error); } } if (count < 0 && rettv_list_alloc(rettv) == FAIL) error = TRUE; if (*fname != NUL && !error) { do { if (rettv->v_type == VAR_STRING) vim_free(fresult); fresult = find_file_in_path_option(first ? fname : NULL, first ? (int)STRLEN(fname) : 0, 0, first, path, find_what, curbuf->b_ffname, find_what == FINDFILE_DIR ? (char_u *)"" : curbuf->b_p_sua); first = FALSE; if (fresult != NULL && rettv->v_type == VAR_LIST) list_append_string(rettv->vval.v_list, fresult, -1); } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL); } if (rettv->v_type == VAR_STRING) rettv->vval.v_string = fresult; #endif } static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map)); static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp)); /* * Implementation of map() and filter(). */ static void filter_map(argvars, rettv, map) typval_T *argvars; typval_T *rettv; int map; { char_u buf[NUMBUFLEN]; char_u *expr; listitem_T *li, *nli; list_T *l = NULL; dictitem_T *di; hashtab_T *ht; hashitem_T *hi; dict_T *d = NULL; typval_T save_val; typval_T save_key; int rem; int todo; char_u *ermsg = (char_u *)(map ? "map()" : "filter()"); char *arg_errmsg = (map ? N_("map() argument") : N_("filter() argument")); int save_did_emsg; int idx = 0; if (argvars[0].v_type == VAR_LIST) { if ((l = argvars[0].vval.v_list) == NULL || tv_check_lock(l->lv_lock, (char_u *)_(arg_errmsg))) return; } else if (argvars[0].v_type == VAR_DICT) { if ((d = argvars[0].vval.v_dict) == NULL || tv_check_lock(d->dv_lock, (char_u *)_(arg_errmsg))) return; } else { EMSG2(_(e_listdictarg), ermsg); return; } expr = get_tv_string_buf_chk(&argvars[1], buf); /* On type errors, the preceding call has already displayed an error * message. Avoid a misleading error message for an empty string that * was not passed as argument. */ if (expr != NULL) { prepare_vimvar(VV_VAL, &save_val); expr = skipwhite(expr); /* We reset "did_emsg" to be able to detect whether an error * occurred during evaluation of the expression. */ save_did_emsg = did_emsg; did_emsg = FALSE; prepare_vimvar(VV_KEY, &save_key); if (argvars[0].v_type == VAR_DICT) { vimvars[VV_KEY].vv_type = VAR_STRING; ht = &d->dv_hashtab; hash_lock(ht); todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); if (tv_check_lock(di->di_tv.v_lock, (char_u *)_(arg_errmsg))) break; vimvars[VV_KEY].vv_str = vim_strsave(di->di_key); if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL || did_emsg) break; if (!map && rem) dictitem_remove(d, di); clear_tv(&vimvars[VV_KEY].vv_tv); } } hash_unlock(ht); } else { vimvars[VV_KEY].vv_type = VAR_NUMBER; for (li = l->lv_first; li != NULL; li = nli) { if (tv_check_lock(li->li_tv.v_lock, (char_u *)_(arg_errmsg))) break; nli = li->li_next; vimvars[VV_KEY].vv_nr = idx; if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL || did_emsg) break; if (!map && rem) listitem_remove(l, li); ++idx; } } restore_vimvar(VV_KEY, &save_key); restore_vimvar(VV_VAL, &save_val); did_emsg |= save_did_emsg; } copy_tv(&argvars[0], rettv); } static int filter_map_one(tv, expr, map, remp) typval_T *tv; char_u *expr; int map; int *remp; { typval_T rettv; char_u *s; int retval = FAIL; copy_tv(tv, &vimvars[VV_VAL].vv_tv); s = expr; if (eval1(&s, &rettv, TRUE) == FAIL) goto theend; if (*s != NUL) /* check for trailing chars after expr */ { EMSG2(_(e_invexpr2), s); goto theend; } if (map) { /* map(): replace the list item value */ clear_tv(tv); rettv.v_lock = 0; *tv = rettv; } else { int error = FALSE; /* filter(): when expr is zero remove the item */ *remp = (get_tv_number_chk(&rettv, &error) == 0); clear_tv(&rettv); /* On type error, nothing has been removed; return FAIL to stop the * loop. The error message was given by get_tv_number_chk(). */ if (error) goto theend; } retval = OK; theend: clear_tv(&vimvars[VV_VAL].vv_tv); return retval; } /* * "filter()" function */ static void f_filter(argvars, rettv) typval_T *argvars; typval_T *rettv; { filter_map(argvars, rettv, FALSE); } /* * "finddir({fname}[, {path}[, {count}]])" function */ static void f_finddir(argvars, rettv) typval_T *argvars; typval_T *rettv; { findfilendir(argvars, rettv, FINDFILE_DIR); } /* * "findfile({fname}[, {path}[, {count}]])" function */ static void f_findfile(argvars, rettv) typval_T *argvars; typval_T *rettv; { findfilendir(argvars, rettv, FINDFILE_FILE); } #ifdef FEAT_FLOAT /* * "float2nr({float})" function */ static void f_float2nr(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; if (get_float_arg(argvars, &f) == OK) { if (f < -0x7fffffff) rettv->vval.v_number = -0x7fffffff; else if (f > 0x7fffffff) rettv->vval.v_number = 0x7fffffff; else rettv->vval.v_number = (varnumber_T)f; } } /* * "floor({float})" function */ static void f_floor(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = floor(f); else rettv->vval.v_float = 0.0; } /* * "fmod()" function */ static void f_fmod(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T fx, fy; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &fx) == OK && get_float_arg(&argvars[1], &fy) == OK) rettv->vval.v_float = fmod(fx, fy); else rettv->vval.v_float = 0.0; } #endif /* * "fnameescape({string})" function */ static void f_fnameescape(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_string = vim_strsave_fnameescape( get_tv_string(&argvars[0]), FALSE); rettv->v_type = VAR_STRING; } /* * "fnamemodify({fname}, {mods})" function */ static void f_fnamemodify(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *fname; char_u *mods; int usedlen = 0; int len; char_u *fbuf = NULL; char_u buf[NUMBUFLEN]; fname = get_tv_string_chk(&argvars[0]); mods = get_tv_string_buf_chk(&argvars[1], buf); if (fname == NULL || mods == NULL) fname = NULL; else { len = (int)STRLEN(fname); (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len); } rettv->v_type = VAR_STRING; if (fname == NULL) rettv->vval.v_string = NULL; else rettv->vval.v_string = vim_strnsave(fname, len); vim_free(fbuf); } static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end)); /* * "foldclosed()" function */ static void foldclosed_both(argvars, rettv, end) typval_T *argvars; typval_T *rettv; int end; { #ifdef FEAT_FOLDING linenr_T lnum; linenr_T first, last; lnum = get_tv_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL)) { if (end) rettv->vval.v_number = (varnumber_T)last; else rettv->vval.v_number = (varnumber_T)first; return; } } #endif rettv->vval.v_number = -1; } /* * "foldclosed()" function */ static void f_foldclosed(argvars, rettv) typval_T *argvars; typval_T *rettv; { foldclosed_both(argvars, rettv, FALSE); } /* * "foldclosedend()" function */ static void f_foldclosedend(argvars, rettv) typval_T *argvars; typval_T *rettv; { foldclosed_both(argvars, rettv, TRUE); } /* * "foldlevel()" function */ static void f_foldlevel(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_FOLDING linenr_T lnum; lnum = get_tv_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) rettv->vval.v_number = foldLevel(lnum); #endif } /* * "foldtext()" function */ static void f_foldtext(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_FOLDING linenr_T lnum; char_u *s; char_u *r; int len; char *txt; #endif rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; #ifdef FEAT_FOLDING if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0 && (linenr_T)vimvars[VV_FOLDEND].vv_nr <= curbuf->b_ml.ml_line_count && vimvars[VV_FOLDDASHES].vv_str != NULL) { /* Find first non-empty line in the fold. */ lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr; while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr) { if (!linewhite(lnum)) break; ++lnum; } /* Find interesting text in this line. */ s = skipwhite(ml_get(lnum)); /* skip C comment-start */ if (s[0] == '/' && (s[1] == '*' || s[1] == '/')) { s = skipwhite(s + 2); if (*skipwhite(s) == NUL && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr) { s = skipwhite(ml_get(lnum + 1)); if (*s == '*') s = skipwhite(s + 1); } } txt = _("+-%s%3ld lines: "); r = alloc((unsigned)(STRLEN(txt) + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */ + 20 /* for %3ld */ + STRLEN(s))); /* concatenated */ if (r != NULL) { sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str, (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1)); len = (int)STRLEN(r); STRCAT(r, s); /* remove 'foldmarker' and 'commentstring' */ foldtext_cleanup(r + len); rettv->vval.v_string = r; } } #endif } /* * "foldtextresult(lnum)" function */ static void f_foldtextresult(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_FOLDING linenr_T lnum; char_u *text; char_u buf[51]; foldinfo_T foldinfo; int fold_count; #endif rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; #ifdef FEAT_FOLDING lnum = get_tv_lnum(argvars); /* treat illegal types and illegal string values for {lnum} the same */ if (lnum < 0) lnum = 0; fold_count = foldedCount(curwin, lnum, &foldinfo); if (fold_count > 0) { text = get_foldtext(curwin, lnum, lnum + fold_count - 1, &foldinfo, buf); if (text == buf) text = vim_strsave(text); rettv->vval.v_string = text; } #endif } /* * "foreground()" function */ static void f_foreground(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_GUI if (gui.in_use) gui_mch_set_foreground(); #else # ifdef WIN32 win32_set_foreground(); # endif #endif } /* * "function()" function */ static void f_function(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *s; s = get_tv_string(&argvars[0]); if (s == NULL || *s == NUL || VIM_ISDIGIT(*s)) EMSG2(_(e_invarg2), s); /* Don't check an autoload name for existence here. */ else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s)) EMSG2(_("E700: Unknown function: %s"), s); else { rettv->vval.v_string = vim_strsave(s); rettv->v_type = VAR_FUNC; } } /* * "garbagecollect()" function */ static void f_garbagecollect(argvars, rettv) typval_T *argvars; typval_T *rettv UNUSED; { /* This is postponed until we are back at the toplevel, because we may be * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */ want_garbage_collect = TRUE; if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1) garbage_collect_at_exit = TRUE; } /* * "get()" function */ static void f_get(argvars, rettv) typval_T *argvars; typval_T *rettv; { listitem_T *li; list_T *l; dictitem_T *di; dict_T *d; typval_T *tv = NULL; if (argvars[0].v_type == VAR_LIST) { if ((l = argvars[0].vval.v_list) != NULL) { int error = FALSE; li = list_find(l, get_tv_number_chk(&argvars[1], &error)); if (!error && li != NULL) tv = &li->li_tv; } } else if (argvars[0].v_type == VAR_DICT) { if ((d = argvars[0].vval.v_dict) != NULL) { di = dict_find(d, get_tv_string(&argvars[1]), -1); if (di != NULL) tv = &di->di_tv; } } else EMSG2(_(e_listdictarg), "get()"); if (tv == NULL) { if (argvars[2].v_type != VAR_UNKNOWN) copy_tv(&argvars[2], rettv); } else copy_tv(tv, rettv); } static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv)); /* * Get line or list of lines from buffer "buf" into "rettv". * Return a range (from start to end) of lines in rettv from the specified * buffer. * If 'retlist' is TRUE, then the lines are returned as a Vim List. */ static void get_buffer_lines(buf, start, end, retlist, rettv) buf_T *buf; linenr_T start; linenr_T end; int retlist; typval_T *rettv; { char_u *p; if (retlist && rettv_list_alloc(rettv) == FAIL) return; if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0) return; if (!retlist) { if (start >= 1 && start <= buf->b_ml.ml_line_count) p = ml_get_buf(buf, start, FALSE); else p = (char_u *)""; rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_strsave(p); } else { if (end < start) return; if (start < 1) start = 1; if (end > buf->b_ml.ml_line_count) end = buf->b_ml.ml_line_count; while (start <= end) if (list_append_string(rettv->vval.v_list, ml_get_buf(buf, start++, FALSE), -1) == FAIL) break; } } /* * "getbufline()" function */ static void f_getbufline(argvars, rettv) typval_T *argvars; typval_T *rettv; { linenr_T lnum; linenr_T end; buf_T *buf; (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */ ++emsg_off; buf = get_buf_tv(&argvars[0]); --emsg_off; lnum = get_tv_lnum_buf(&argvars[1], buf); if (argvars[2].v_type == VAR_UNKNOWN) end = lnum; else end = get_tv_lnum_buf(&argvars[2], buf); get_buffer_lines(buf, lnum, end, TRUE, rettv); } /* * "getbufvar()" function */ static void f_getbufvar(argvars, rettv) typval_T *argvars; typval_T *rettv; { buf_T *buf; buf_T *save_curbuf; char_u *varname; dictitem_T *v; (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */ varname = get_tv_string_chk(&argvars[1]); ++emsg_off; buf = get_buf_tv(&argvars[0]); rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; if (buf != NULL && varname != NULL) { /* set curbuf to be our buf, temporarily */ save_curbuf = curbuf; curbuf = buf; if (*varname == '&') /* buffer-local-option */ get_option_tv(&varname, rettv, TRUE); else if (STRCMP(varname, "changedtick") == 0) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = curbuf->b_changedtick; } else { if (*varname == NUL) /* let getbufvar({nr}, "") return the "b:" dictionary. The * scope prefix before the NUL byte is required by * find_var_in_ht(). */ varname = (char_u *)"b:" + 2; /* look up the variable */ v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE); if (v != NULL) copy_tv(&v->di_tv, rettv); } /* restore previous notion of curbuf */ curbuf = save_curbuf; } --emsg_off; } /* * "getchar()" function */ static void f_getchar(argvars, rettv) typval_T *argvars; typval_T *rettv; { varnumber_T n; int error = FALSE; /* Position the cursor. Needed after a message that ends in a space. */ windgoto(msg_row, msg_col); ++no_mapping; ++allow_keys; for (;;) { if (argvars[0].v_type == VAR_UNKNOWN) /* getchar(): blocking wait. */ n = safe_vgetc(); else if (get_tv_number_chk(&argvars[0], &error) == 1) /* getchar(1): only check if char avail */ n = vpeekc(); else if (error || vpeekc() == NUL) /* illegal argument or getchar(0) and no char avail: return zero */ n = 0; else /* getchar(0) and char avail: return char */ n = safe_vgetc(); if (n == K_IGNORE) continue; break; } --no_mapping; --allow_keys; vimvars[VV_MOUSE_WIN].vv_nr = 0; vimvars[VV_MOUSE_LNUM].vv_nr = 0; vimvars[VV_MOUSE_COL].vv_nr = 0; rettv->vval.v_number = n; if (IS_SPECIAL(n) || mod_mask != 0) { char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */ int i = 0; /* Turn a special key into three bytes, plus modifier. */ if (mod_mask != 0) { temp[i++] = K_SPECIAL; temp[i++] = KS_MODIFIER; temp[i++] = mod_mask; } if (IS_SPECIAL(n)) { temp[i++] = K_SPECIAL; temp[i++] = K_SECOND(n); temp[i++] = K_THIRD(n); } #ifdef FEAT_MBYTE else if (has_mbyte) i += (*mb_char2bytes)(n, temp + i); #endif else temp[i++] = n; temp[i++] = NUL; rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_strsave(temp); #ifdef FEAT_MOUSE if (n == K_LEFTMOUSE || n == K_LEFTMOUSE_NM || n == K_LEFTDRAG || n == K_LEFTRELEASE || n == K_LEFTRELEASE_NM || n == K_MIDDLEMOUSE || n == K_MIDDLEDRAG || n == K_MIDDLERELEASE || n == K_RIGHTMOUSE || n == K_RIGHTDRAG || n == K_RIGHTRELEASE || n == K_X1MOUSE || n == K_X1DRAG || n == K_X1RELEASE || n == K_X2MOUSE || n == K_X2DRAG || n == K_X2RELEASE || n == K_MOUSELEFT || n == K_MOUSERIGHT || n == K_MOUSEDOWN || n == K_MOUSEUP) { int row = mouse_row; int col = mouse_col; win_T *win; linenr_T lnum; # ifdef FEAT_WINDOWS win_T *wp; # endif int winnr = 1; if (row >= 0 && col >= 0) { /* Find the window at the mouse coordinates and compute the * text position. */ win = mouse_find_win(&row, &col); (void)mouse_comp_pos(win, &row, &col, &lnum); # ifdef FEAT_WINDOWS for (wp = firstwin; wp != win; wp = wp->w_next) ++winnr; # endif vimvars[VV_MOUSE_WIN].vv_nr = winnr; vimvars[VV_MOUSE_LNUM].vv_nr = lnum; vimvars[VV_MOUSE_COL].vv_nr = col + 1; } } #endif } } /* * "getcharmod()" function */ static void f_getcharmod(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = mod_mask; } /* * "getcmdline()" function */ static void f_getcmdline(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->v_type = VAR_STRING; rettv->vval.v_string = get_cmdline_str(); } /* * "getcmdpos()" function */ static void f_getcmdpos(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = get_cmdline_pos() + 1; } /* * "getcmdtype()" function */ static void f_getcmdtype(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->v_type = VAR_STRING; rettv->vval.v_string = alloc(2); if (rettv->vval.v_string != NULL) { rettv->vval.v_string[0] = get_cmdline_type(); rettv->vval.v_string[1] = NUL; } } /* * "getcwd()" function */ static void f_getcwd(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { char_u *cwd; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; cwd = alloc(MAXPATHL); if (cwd != NULL) { if (mch_dirname(cwd, MAXPATHL) != FAIL) { rettv->vval.v_string = vim_strsave(cwd); #ifdef BACKSLASH_IN_FILENAME if (rettv->vval.v_string != NULL) slash_adjust(rettv->vval.v_string); #endif } vim_free(cwd); } } /* * "getfontname()" function */ static void f_getfontname(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; #ifdef FEAT_GUI if (gui.in_use) { GuiFont font; char_u *name = NULL; if (argvars[0].v_type == VAR_UNKNOWN) { /* Get the "Normal" font. Either the name saved by * hl_set_font_name() or from the font ID. */ font = gui.norm_font; name = hl_get_font_name(); } else { name = get_tv_string(&argvars[0]); if (STRCMP(name, "*") == 0) /* don't use font dialog */ return; font = gui_mch_get_font(name, FALSE); if (font == NOFONT) return; /* Invalid font name, return empty string. */ } rettv->vval.v_string = gui_mch_get_fontname(font, name); if (argvars[0].v_type != VAR_UNKNOWN) gui_mch_free_font(font); } #endif } /* * "getfperm({fname})" function */ static void f_getfperm(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *fname; struct stat st; char_u *perm = NULL; char_u flags[] = "rwx"; int i; fname = get_tv_string(&argvars[0]); rettv->v_type = VAR_STRING; if (mch_stat((char *)fname, &st) >= 0) { perm = vim_strsave((char_u *)"---------"); if (perm != NULL) { for (i = 0; i < 9; i++) { if (st.st_mode & (1 << (8 - i))) perm[i] = flags[i % 3]; } } } rettv->vval.v_string = perm; } /* * "getfsize({fname})" function */ static void f_getfsize(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *fname; struct stat st; fname = get_tv_string(&argvars[0]); rettv->v_type = VAR_NUMBER; if (mch_stat((char *)fname, &st) >= 0) { if (mch_isdir(fname)) rettv->vval.v_number = 0; else { rettv->vval.v_number = (varnumber_T)st.st_size; /* non-perfect check for overflow */ if ((off_t)rettv->vval.v_number != (off_t)st.st_size) rettv->vval.v_number = -2; } } else rettv->vval.v_number = -1; } /* * "getftime({fname})" function */ static void f_getftime(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *fname; struct stat st; fname = get_tv_string(&argvars[0]); if (mch_stat((char *)fname, &st) >= 0) rettv->vval.v_number = (varnumber_T)st.st_mtime; else rettv->vval.v_number = -1; } /* * "getftype({fname})" function */ static void f_getftype(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *fname; struct stat st; char_u *type = NULL; char *t; fname = get_tv_string(&argvars[0]); rettv->v_type = VAR_STRING; if (mch_lstat((char *)fname, &st) >= 0) { #ifdef S_ISREG if (S_ISREG(st.st_mode)) t = "file"; else if (S_ISDIR(st.st_mode)) t = "dir"; # ifdef S_ISLNK else if (S_ISLNK(st.st_mode)) t = "link"; # endif # ifdef S_ISBLK else if (S_ISBLK(st.st_mode)) t = "bdev"; # endif # ifdef S_ISCHR else if (S_ISCHR(st.st_mode)) t = "cdev"; # endif # ifdef S_ISFIFO else if (S_ISFIFO(st.st_mode)) t = "fifo"; # endif # ifdef S_ISSOCK else if (S_ISSOCK(st.st_mode)) t = "fifo"; # endif else t = "other"; #else # ifdef S_IFMT switch (st.st_mode & S_IFMT) { case S_IFREG: t = "file"; break; case S_IFDIR: t = "dir"; break; # ifdef S_IFLNK case S_IFLNK: t = "link"; break; # endif # ifdef S_IFBLK case S_IFBLK: t = "bdev"; break; # endif # ifdef S_IFCHR case S_IFCHR: t = "cdev"; break; # endif # ifdef S_IFIFO case S_IFIFO: t = "fifo"; break; # endif # ifdef S_IFSOCK case S_IFSOCK: t = "socket"; break; # endif default: t = "other"; } # else if (mch_isdir(fname)) t = "dir"; else t = "file"; # endif #endif type = vim_strsave((char_u *)t); } rettv->vval.v_string = type; } /* * "getline(lnum, [end])" function */ static void f_getline(argvars, rettv) typval_T *argvars; typval_T *rettv; { linenr_T lnum; linenr_T end; int retlist; lnum = get_tv_lnum(argvars); if (argvars[1].v_type == VAR_UNKNOWN) { end = 0; retlist = FALSE; } else { end = get_tv_lnum(&argvars[1]); retlist = TRUE; } get_buffer_lines(curbuf, lnum, end, retlist, rettv); } /* * "getmatches()" function */ static void f_getmatches(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_SEARCH_EXTRA dict_T *dict; matchitem_T *cur = curwin->w_match_head; if (rettv_list_alloc(rettv) == OK) { while (cur != NULL) { dict = dict_alloc(); if (dict == NULL) return; dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id)); dict_add_nr_str(dict, "pattern", 0L, cur->pattern); dict_add_nr_str(dict, "priority", (long)cur->priority, NULL); dict_add_nr_str(dict, "id", (long)cur->id, NULL); list_append_dict(rettv->vval.v_list, dict); cur = cur->next; } } #endif } /* * "getpid()" function */ static void f_getpid(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = mch_get_pid(); } /* * "getpos(string)" function */ static void f_getpos(argvars, rettv) typval_T *argvars; typval_T *rettv; { pos_T *fp; list_T *l; int fnum = -1; if (rettv_list_alloc(rettv) == OK) { l = rettv->vval.v_list; fp = var2fpos(&argvars[0], TRUE, &fnum); if (fnum != -1) list_append_number(l, (varnumber_T)fnum); else list_append_number(l, (varnumber_T)0); list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum : (varnumber_T)0); list_append_number(l, (fp != NULL) ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1) : (varnumber_T)0); list_append_number(l, #ifdef FEAT_VIRTUALEDIT (fp != NULL) ? (varnumber_T)fp->coladd : #endif (varnumber_T)0); } else rettv->vval.v_number = FALSE; } /* * "getqflist()" and "getloclist()" functions */ static void f_getqflist(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_QUICKFIX win_T *wp; #endif #ifdef FEAT_QUICKFIX if (rettv_list_alloc(rettv) == OK) { wp = NULL; if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */ { wp = find_win_by_nr(&argvars[0], NULL); if (wp == NULL) return; } (void)get_errorlist(wp, rettv->vval.v_list); } #endif } /* * "getreg()" function */ static void f_getreg(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *strregname; int regname; int arg2 = FALSE; int error = FALSE; if (argvars[0].v_type != VAR_UNKNOWN) { strregname = get_tv_string_chk(&argvars[0]); error = strregname == NULL; if (argvars[1].v_type != VAR_UNKNOWN) arg2 = get_tv_number_chk(&argvars[1], &error); } else strregname = vimvars[VV_REG].vv_str; regname = (strregname == NULL ? '"' : *strregname); if (regname == 0) regname = '"'; rettv->v_type = VAR_STRING; rettv->vval.v_string = error ? NULL : get_reg_contents(regname, TRUE, arg2); } /* * "getregtype()" function */ static void f_getregtype(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *strregname; int regname; char_u buf[NUMBUFLEN + 2]; long reglen = 0; if (argvars[0].v_type != VAR_UNKNOWN) { strregname = get_tv_string_chk(&argvars[0]); if (strregname == NULL) /* type error; errmsg already given */ { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; return; } } else /* Default to v:register */ strregname = vimvars[VV_REG].vv_str; regname = (strregname == NULL ? '"' : *strregname); if (regname == 0) regname = '"'; buf[0] = NUL; buf[1] = NUL; switch (get_reg_type(regname, &reglen)) { case MLINE: buf[0] = 'V'; break; case MCHAR: buf[0] = 'v'; break; #ifdef FEAT_VISUAL case MBLOCK: buf[0] = Ctrl_V; sprintf((char *)buf + 1, "%ld", reglen + 1); break; #endif } rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_strsave(buf); } /* * "gettabvar()" function */ static void f_gettabvar(argvars, rettv) typval_T *argvars; typval_T *rettv; { tabpage_T *tp; dictitem_T *v; char_u *varname; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; varname = get_tv_string_chk(&argvars[1]); tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL)); if (tp != NULL && varname != NULL) { /* look up the variable */ v = find_var_in_ht(&tp->tp_vars.dv_hashtab, varname, FALSE); if (v != NULL) copy_tv(&v->di_tv, rettv); } } /* * "gettabwinvar()" function */ static void f_gettabwinvar(argvars, rettv) typval_T *argvars; typval_T *rettv; { getwinvar(argvars, rettv, 1); } /* * "getwinposx()" function */ static void f_getwinposx(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = -1; #ifdef FEAT_GUI if (gui.in_use) { int x, y; if (gui_mch_get_winpos(&x, &y) == OK) rettv->vval.v_number = x; } #endif } /* * "getwinposy()" function */ static void f_getwinposy(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = -1; #ifdef FEAT_GUI if (gui.in_use) { int x, y; if (gui_mch_get_winpos(&x, &y) == OK) rettv->vval.v_number = y; } #endif } /* * Find window specified by "vp" in tabpage "tp". */ static win_T * find_win_by_nr(vp, tp) typval_T *vp; tabpage_T *tp; /* NULL for current tab page */ { #ifdef FEAT_WINDOWS win_T *wp; #endif int nr; nr = get_tv_number_chk(vp, NULL); #ifdef FEAT_WINDOWS if (nr < 0) return NULL; if (nr == 0) return curwin; for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin; wp != NULL; wp = wp->w_next) if (--nr <= 0) break; return wp; #else if (nr == 0 || nr == 1) return curwin; return NULL; #endif } /* * "getwinvar()" function */ static void f_getwinvar(argvars, rettv) typval_T *argvars; typval_T *rettv; { getwinvar(argvars, rettv, 0); } /* * getwinvar() and gettabwinvar() */ static void getwinvar(argvars, rettv, off) typval_T *argvars; typval_T *rettv; int off; /* 1 for gettabwinvar() */ { win_T *win, *oldcurwin; char_u *varname; dictitem_T *v; tabpage_T *tp; #ifdef FEAT_WINDOWS if (off == 1) tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL)); else tp = curtab; #endif win = find_win_by_nr(&argvars[off], tp); varname = get_tv_string_chk(&argvars[off + 1]); ++emsg_off; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; if (win != NULL && varname != NULL) { /* Set curwin to be our win, temporarily. Also set curbuf, so * that we can get buffer-local options. */ oldcurwin = curwin; curwin = win; curbuf = win->w_buffer; if (*varname == '&') /* window-local-option */ get_option_tv(&varname, rettv, 1); else { if (*varname == NUL) /* let getwinvar({nr}, "") return the "w:" dictionary. The * scope prefix before the NUL byte is required by * find_var_in_ht(). */ varname = (char_u *)"w:" + 2; /* look up the variable */ v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE); if (v != NULL) copy_tv(&v->di_tv, rettv); } /* restore previous notion of curwin */ curwin = oldcurwin; curbuf = curwin->w_buffer; } --emsg_off; } /* * "glob()" function */ static void f_glob(argvars, rettv) typval_T *argvars; typval_T *rettv; { int options = WILD_SILENT|WILD_USE_NL; expand_T xpc; int error = FALSE; /* When the optional second argument is non-zero, don't remove matches * for 'wildignore' and don't put matches for 'suffixes' at the end. */ rettv->v_type = VAR_STRING; if (argvars[1].v_type != VAR_UNKNOWN) { if (get_tv_number_chk(&argvars[1], &error)) options |= WILD_KEEP_ALL; if (argvars[2].v_type != VAR_UNKNOWN && get_tv_number_chk(&argvars[2], &error)) { rettv->v_type = VAR_LIST; rettv->vval.v_list = NULL; } } if (!error) { ExpandInit(&xpc); xpc.xp_context = EXPAND_FILES; if (p_wic) options += WILD_ICASE; if (rettv->v_type == VAR_STRING) rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]), NULL, options, WILD_ALL); else if (rettv_list_alloc(rettv) != FAIL) { int i; ExpandOne(&xpc, get_tv_string(&argvars[0]), NULL, options, WILD_ALL_KEEP); for (i = 0; i < xpc.xp_numfiles; i++) list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1); ExpandCleanup(&xpc); } } else rettv->vval.v_string = NULL; } /* * "globpath()" function */ static void f_globpath(argvars, rettv) typval_T *argvars; typval_T *rettv; { int flags = 0; char_u buf1[NUMBUFLEN]; char_u *file = get_tv_string_buf_chk(&argvars[1], buf1); int error = FALSE; /* When the optional second argument is non-zero, don't remove matches * for 'wildignore' and don't put matches for 'suffixes' at the end. */ if (argvars[2].v_type != VAR_UNKNOWN && get_tv_number_chk(&argvars[2], &error)) flags |= WILD_KEEP_ALL; rettv->v_type = VAR_STRING; if (file == NULL || error) rettv->vval.v_string = NULL; else rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file, flags); } /* * "has()" function */ static void f_has(argvars, rettv) typval_T *argvars; typval_T *rettv; { int i; char_u *name; int n = FALSE; static char *(has_list[]) = { #ifdef AMIGA "amiga", # ifdef FEAT_ARP "arp", # endif #endif #ifdef __BEOS__ "beos", #endif #ifdef MSDOS # ifdef DJGPP "dos32", # else "dos16", # endif #endif #ifdef MACOS "mac", #endif #if defined(MACOS_X_UNIX) "macunix", #endif #ifdef OS2 "os2", #endif #ifdef __QNX__ "qnx", #endif #ifdef UNIX "unix", #endif #ifdef VMS "vms", #endif #ifdef WIN16 "win16", #endif #ifdef WIN32 "win32", #endif #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__)) "win32unix", #endif #if defined(WIN64) || defined(_WIN64) "win64", #endif #ifdef EBCDIC "ebcdic", #endif #ifndef CASE_INSENSITIVE_FILENAME "fname_case", #endif #ifdef FEAT_ARABIC "arabic", #endif #ifdef FEAT_AUTOCMD "autocmd", #endif #ifdef FEAT_BEVAL "balloon_eval", # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */ "balloon_multiline", # endif #endif #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS) "builtin_terms", # ifdef ALL_BUILTIN_TCAPS "all_builtin_terms", # endif #endif #ifdef FEAT_BYTEOFF "byte_offset", #endif #ifdef FEAT_CINDENT "cindent", #endif #ifdef FEAT_CLIENTSERVER "clientserver", #endif #ifdef FEAT_CLIPBOARD "clipboard", #endif #ifdef FEAT_CMDL_COMPL "cmdline_compl", #endif #ifdef FEAT_CMDHIST "cmdline_hist", #endif #ifdef FEAT_COMMENTS "comments", #endif #ifdef FEAT_CONCEAL "conceal", #endif #ifdef FEAT_CRYPT "cryptv", #endif #ifdef FEAT_CSCOPE "cscope", #endif #ifdef FEAT_CURSORBIND "cursorbind", #endif #ifdef CURSOR_SHAPE "cursorshape", #endif #ifdef DEBUG "debug", #endif #ifdef FEAT_CON_DIALOG "dialog_con", #endif #ifdef FEAT_GUI_DIALOG "dialog_gui", #endif #ifdef FEAT_DIFF "diff", #endif #ifdef FEAT_DIGRAPHS "digraphs", #endif #ifdef FEAT_DND "dnd", #endif #ifdef FEAT_EMACS_TAGS "emacs_tags", #endif "eval", /* always present, of course! */ #ifdef FEAT_EX_EXTRA "ex_extra", #endif #ifdef FEAT_SEARCH_EXTRA "extra_search", #endif #ifdef FEAT_FKMAP "farsi", #endif #ifdef FEAT_SEARCHPATH "file_in_path", #endif #ifdef FEAT_FILTERPIPE "filterpipe", #endif #ifdef FEAT_FIND_ID "find_in_path", #endif #ifdef FEAT_FLOAT "float", #endif #ifdef FEAT_FOLDING "folding", #endif #ifdef FEAT_FOOTER "footer", #endif #if !defined(USE_SYSTEM) && defined(UNIX) "fork", #endif #ifdef FEAT_GETTEXT "gettext", #endif #ifdef FEAT_GUI "gui", #endif #ifdef FEAT_GUI_ATHENA # ifdef FEAT_GUI_NEXTAW "gui_neXtaw", # else "gui_athena", # endif #endif #ifdef FEAT_GUI_GTK "gui_gtk", "gui_gtk2", #endif #ifdef FEAT_GUI_GNOME "gui_gnome", #endif #ifdef FEAT_GUI_MAC "gui_mac", #endif #ifdef FEAT_GUI_MOTIF "gui_motif", #endif #ifdef FEAT_GUI_PHOTON "gui_photon", #endif #ifdef FEAT_GUI_W16 "gui_win16", #endif #ifdef FEAT_GUI_W32 "gui_win32", #endif #ifdef FEAT_HANGULIN "hangul_input", #endif #if defined(HAVE_ICONV_H) && defined(USE_ICONV) "iconv", #endif #ifdef FEAT_INS_EXPAND "insert_expand", #endif #ifdef FEAT_JUMPLIST "jumplist", #endif #ifdef FEAT_KEYMAP "keymap", #endif #ifdef FEAT_LANGMAP "langmap", #endif #ifdef FEAT_LIBCALL "libcall", #endif #ifdef FEAT_LINEBREAK "linebreak", #endif #ifdef FEAT_LISP "lispindent", #endif #ifdef FEAT_LISTCMDS "listcmds", #endif #ifdef FEAT_LOCALMAP "localmap", #endif #ifdef FEAT_LUA # ifndef DYNAMIC_LUA "lua", # endif #endif #ifdef FEAT_MENU "menu", #endif #ifdef FEAT_SESSION "mksession", #endif #ifdef FEAT_MODIFY_FNAME "modify_fname", #endif #ifdef FEAT_MOUSE "mouse", #endif #ifdef FEAT_MOUSESHAPE "mouseshape", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_DEC "mouse_dec", # endif # ifdef FEAT_MOUSE_GPM "mouse_gpm", # endif # ifdef FEAT_MOUSE_JSB "mouse_jsbterm", # endif # ifdef FEAT_MOUSE_NET "mouse_netterm", # endif # ifdef FEAT_MOUSE_PTERM "mouse_pterm", # endif # ifdef FEAT_SYSMOUSE "mouse_sysmouse", # endif # ifdef FEAT_MOUSE_XTERM "mouse_xterm", # endif #endif #ifdef FEAT_MBYTE "multi_byte", #endif #ifdef FEAT_MBYTE_IME "multi_byte_ime", #endif #ifdef FEAT_MULTI_LANG "multi_lang", #endif #ifdef FEAT_MZSCHEME #ifndef DYNAMIC_MZSCHEME "mzscheme", #endif #endif #ifdef FEAT_OLE "ole", #endif #ifdef FEAT_PATH_EXTRA "path_extra", #endif #ifdef FEAT_PERL #ifndef DYNAMIC_PERL "perl", #endif #endif #ifdef FEAT_PERSISTENT_UNDO "persistent_undo", #endif #ifdef FEAT_PYTHON #ifndef DYNAMIC_PYTHON "python", #endif #endif #ifdef FEAT_PYTHON3 #ifndef DYNAMIC_PYTHON3 "python3", #endif #endif #ifdef FEAT_POSTSCRIPT "postscript", #endif #ifdef FEAT_PRINTER "printer", #endif #ifdef FEAT_PROFILE "profile", #endif #ifdef FEAT_RELTIME "reltime", #endif #ifdef FEAT_QUICKFIX "quickfix", #endif #ifdef FEAT_RIGHTLEFT "rightleft", #endif #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY) "ruby", #endif #ifdef FEAT_SCROLLBIND "scrollbind", #endif #ifdef FEAT_CMDL_INFO "showcmd", "cmdline_info", #endif #ifdef FEAT_SIGNS "signs", #endif #ifdef FEAT_SMARTINDENT "smartindent", #endif #ifdef FEAT_SNIFF "sniff", #endif #ifdef STARTUPTIME "startuptime", #endif #ifdef FEAT_STL_OPT "statusline", #endif #ifdef FEAT_SUN_WORKSHOP "sun_workshop", #endif #ifdef FEAT_NETBEANS_INTG "netbeans_intg", #endif #ifdef FEAT_SPELL "spell", #endif #ifdef FEAT_SYN_HL "syntax", #endif #if defined(USE_SYSTEM) || !defined(UNIX) "system", #endif #ifdef FEAT_TAG_BINS "tag_binary", #endif #ifdef FEAT_TAG_OLDSTATIC "tag_old_static", #endif #ifdef FEAT_TAG_ANYWHITE "tag_any_white", #endif #ifdef FEAT_TCL # ifndef DYNAMIC_TCL "tcl", # endif #endif #ifdef TERMINFO "terminfo", #endif #ifdef FEAT_TERMRESPONSE "termresponse", #endif #ifdef FEAT_TEXTOBJ "textobjects", #endif #ifdef HAVE_TGETENT "tgetent", #endif #ifdef FEAT_TITLE "title", #endif #ifdef FEAT_TOOLBAR "toolbar", #endif #if defined(FEAT_CLIPBOARD) && defined(FEAT_X11) "unnamedplus", #endif #ifdef FEAT_USR_CMDS "user-commands", /* was accidentally included in 5.4 */ "user_commands", #endif #ifdef FEAT_VIMINFO "viminfo", #endif #ifdef FEAT_VERTSPLIT "vertsplit", #endif #ifdef FEAT_VIRTUALEDIT "virtualedit", #endif #ifdef FEAT_VISUAL "visual", #endif #ifdef FEAT_VISUALEXTRA "visualextra", #endif #ifdef FEAT_VREPLACE "vreplace", #endif #ifdef FEAT_WILDIGN "wildignore", #endif #ifdef FEAT_WILDMENU "wildmenu", #endif #ifdef FEAT_WINDOWS "windows", #endif #ifdef FEAT_WAK "winaltkeys", #endif #ifdef FEAT_WRITEBACKUP "writebackup", #endif #ifdef FEAT_XIM "xim", #endif #ifdef FEAT_XFONTSET "xfontset", #endif #ifdef FEAT_XPM_W32 "xpm_w32", #endif #ifdef USE_XSMP "xsmp", #endif #ifdef USE_XSMP_INTERACT "xsmp_interact", #endif #ifdef FEAT_XCLIPBOARD "xterm_clipboard", #endif #ifdef FEAT_XTERM_SAVE "xterm_save", #endif #if defined(UNIX) && defined(FEAT_X11) "X11", #endif NULL }; name = get_tv_string(&argvars[0]); for (i = 0; has_list[i] != NULL; ++i) if (STRICMP(name, has_list[i]) == 0) { n = TRUE; break; } if (n == FALSE) { if (STRNICMP(name, "patch", 5) == 0) n = has_patch(atoi((char *)name + 5)); else if (STRICMP(name, "vim_starting") == 0) n = (starting != 0); #ifdef FEAT_MBYTE else if (STRICMP(name, "multi_byte_encoding") == 0) n = has_mbyte; #endif #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32) else if (STRICMP(name, "balloon_multiline") == 0) n = multiline_balloon_available(); #endif #ifdef DYNAMIC_TCL else if (STRICMP(name, "tcl") == 0) n = tcl_enabled(FALSE); #endif #if defined(USE_ICONV) && defined(DYNAMIC_ICONV) else if (STRICMP(name, "iconv") == 0) n = iconv_enabled(FALSE); #endif #ifdef DYNAMIC_LUA else if (STRICMP(name, "lua") == 0) n = lua_enabled(FALSE); #endif #ifdef DYNAMIC_MZSCHEME else if (STRICMP(name, "mzscheme") == 0) n = mzscheme_enabled(FALSE); #endif #ifdef DYNAMIC_RUBY else if (STRICMP(name, "ruby") == 0) n = ruby_enabled(FALSE); #endif #ifdef FEAT_PYTHON #ifdef DYNAMIC_PYTHON else if (STRICMP(name, "python") == 0) n = python_enabled(FALSE); #endif #endif #ifdef FEAT_PYTHON3 #ifdef DYNAMIC_PYTHON3 else if (STRICMP(name, "python3") == 0) n = python3_enabled(FALSE); #endif #endif #ifdef DYNAMIC_PERL else if (STRICMP(name, "perl") == 0) n = perl_enabled(FALSE); #endif #ifdef FEAT_GUI else if (STRICMP(name, "gui_running") == 0) n = (gui.in_use || gui.starting); # ifdef FEAT_GUI_W32 else if (STRICMP(name, "gui_win32s") == 0) n = gui_is_win32s(); # endif # ifdef FEAT_BROWSE else if (STRICMP(name, "browse") == 0) n = gui.in_use; /* gui_mch_browse() works when GUI is running */ # endif #endif #ifdef FEAT_SYN_HL else if (STRICMP(name, "syntax_items") == 0) n = syntax_present(curwin); #endif #if defined(WIN3264) else if (STRICMP(name, "win95") == 0) n = mch_windows95(); #endif #ifdef FEAT_NETBEANS_INTG else if (STRICMP(name, "netbeans_enabled") == 0) n = netbeans_active(); #endif } rettv->vval.v_number = n; } /* * "has_key()" function */ static void f_has_key(argvars, rettv) typval_T *argvars; typval_T *rettv; { if (argvars[0].v_type != VAR_DICT) { EMSG(_(e_dictreq)); return; } if (argvars[0].vval.v_dict == NULL) return; rettv->vval.v_number = dict_find(argvars[0].vval.v_dict, get_tv_string(&argvars[1]), -1) != NULL; } /* * "haslocaldir()" function */ static void f_haslocaldir(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = (curwin->w_localdir != NULL); } /* * "hasmapto()" function */ static void f_hasmapto(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *name; char_u *mode; char_u buf[NUMBUFLEN]; int abbr = FALSE; name = get_tv_string(&argvars[0]); if (argvars[1].v_type == VAR_UNKNOWN) mode = (char_u *)"nvo"; else { mode = get_tv_string_buf(&argvars[1], buf); if (argvars[2].v_type != VAR_UNKNOWN) abbr = get_tv_number(&argvars[2]); } if (map_to_exists(name, mode, abbr)) rettv->vval.v_number = TRUE; else rettv->vval.v_number = FALSE; } /* * "histadd()" function */ static void f_histadd(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_CMDHIST int histype; char_u *str; char_u buf[NUMBUFLEN]; #endif rettv->vval.v_number = FALSE; if (check_restricted() || check_secure()) return; #ifdef FEAT_CMDHIST str = get_tv_string_chk(&argvars[0]); /* NULL on type error */ histype = str != NULL ? get_histtype(str) : -1; if (histype >= 0) { str = get_tv_string_buf(&argvars[1], buf); if (*str != NUL) { init_history(); add_to_history(histype, str, FALSE, NUL); rettv->vval.v_number = TRUE; return; } } #endif } /* * "histdel()" function */ static void f_histdel(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_CMDHIST int n; char_u buf[NUMBUFLEN]; char_u *str; str = get_tv_string_chk(&argvars[0]); /* NULL on type error */ if (str == NULL) n = 0; else if (argvars[1].v_type == VAR_UNKNOWN) /* only one argument: clear entire history */ n = clr_history(get_histtype(str)); else if (argvars[1].v_type == VAR_NUMBER) /* index given: remove that entry */ n = del_history_idx(get_histtype(str), (int)get_tv_number(&argvars[1])); else /* string given: remove all matching entries */ n = del_history_entry(get_histtype(str), get_tv_string_buf(&argvars[1], buf)); rettv->vval.v_number = n; #endif } /* * "histget()" function */ static void f_histget(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_CMDHIST int type; int idx; char_u *str; str = get_tv_string_chk(&argvars[0]); /* NULL on type error */ if (str == NULL) rettv->vval.v_string = NULL; else { type = get_histtype(str); if (argvars[1].v_type == VAR_UNKNOWN) idx = get_history_idx(type); else idx = (int)get_tv_number_chk(&argvars[1], NULL); /* -1 on type error */ rettv->vval.v_string = vim_strsave(get_history_entry(type, idx)); } #else rettv->vval.v_string = NULL; #endif rettv->v_type = VAR_STRING; } /* * "histnr()" function */ static void f_histnr(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { int i; #ifdef FEAT_CMDHIST char_u *history = get_tv_string_chk(&argvars[0]); i = history == NULL ? HIST_CMD - 1 : get_histtype(history); if (i >= HIST_CMD && i < HIST_COUNT) i = get_history_idx(i); else #endif i = -1; rettv->vval.v_number = i; } /* * "highlightID(name)" function */ static void f_hlID(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0])); } /* * "highlight_exists()" function */ static void f_hlexists(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0])); } /* * "hostname()" function */ static void f_hostname(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { char_u hostname[256]; mch_get_host_name(hostname, 256); rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_strsave(hostname); } /* * iconv() function */ static void f_iconv(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_MBYTE char_u buf1[NUMBUFLEN]; char_u buf2[NUMBUFLEN]; char_u *from, *to, *str; vimconv_T vimconv; #endif rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; #ifdef FEAT_MBYTE str = get_tv_string(&argvars[0]); from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1))); to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2))); vimconv.vc_type = CONV_NONE; convert_setup(&vimconv, from, to); /* If the encodings are equal, no conversion needed. */ if (vimconv.vc_type == CONV_NONE) rettv->vval.v_string = vim_strsave(str); else rettv->vval.v_string = string_convert(&vimconv, str, NULL); convert_setup(&vimconv, NULL, NULL); vim_free(from); vim_free(to); #endif } /* * "indent()" function */ static void f_indent(argvars, rettv) typval_T *argvars; typval_T *rettv; { linenr_T lnum; lnum = get_tv_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) rettv->vval.v_number = get_indent_lnum(lnum); else rettv->vval.v_number = -1; } /* * "index()" function */ static void f_index(argvars, rettv) typval_T *argvars; typval_T *rettv; { list_T *l; listitem_T *item; long idx = 0; int ic = FALSE; rettv->vval.v_number = -1; if (argvars[0].v_type != VAR_LIST) { EMSG(_(e_listreq)); return; } l = argvars[0].vval.v_list; if (l != NULL) { item = l->lv_first; if (argvars[2].v_type != VAR_UNKNOWN) { int error = FALSE; /* Start at specified item. Use the cached index that list_find() * sets, so that a negative number also works. */ item = list_find(l, get_tv_number_chk(&argvars[2], &error)); idx = l->lv_idx; if (argvars[3].v_type != VAR_UNKNOWN) ic = get_tv_number_chk(&argvars[3], &error); if (error) item = NULL; } for ( ; item != NULL; item = item->li_next, ++idx) if (tv_equal(&item->li_tv, &argvars[1], ic, FALSE)) { rettv->vval.v_number = idx; break; } } } static int inputsecret_flag = 0; static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog)); /* * This function is used by f_input() and f_inputdialog() functions. The third * argument to f_input() specifies the type of completion to use at the * prompt. The third argument to f_inputdialog() specifies the value to return * when the user cancels the prompt. */ static void get_user_input(argvars, rettv, inputdialog) typval_T *argvars; typval_T *rettv; int inputdialog; { char_u *prompt = get_tv_string_chk(&argvars[0]); char_u *p = NULL; int c; char_u buf[NUMBUFLEN]; int cmd_silent_save = cmd_silent; char_u *defstr = (char_u *)""; int xp_type = EXPAND_NOTHING; char_u *xp_arg = NULL; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; #ifdef NO_CONSOLE_INPUT /* While starting up, there is no place to enter text. */ if (no_console_input()) return; #endif cmd_silent = FALSE; /* Want to see the prompt. */ if (prompt != NULL) { /* Only the part of the message after the last NL is considered as * prompt for the command line */ p = vim_strrchr(prompt, '\n'); if (p == NULL) p = prompt; else { ++p; c = *p; *p = NUL; msg_start(); msg_clr_eos(); msg_puts_attr(prompt, echo_attr); msg_didout = FALSE; msg_starthere(); *p = c; } cmdline_row = msg_row; if (argvars[1].v_type != VAR_UNKNOWN) { defstr = get_tv_string_buf_chk(&argvars[1], buf); if (defstr != NULL) stuffReadbuffSpec(defstr); if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN) { char_u *xp_name; int xp_namelen; long argt; rettv->vval.v_string = NULL; xp_name = get_tv_string_buf_chk(&argvars[2], buf); if (xp_name == NULL) return; xp_namelen = (int)STRLEN(xp_name); if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt, &xp_arg) == FAIL) return; } } if (defstr != NULL) rettv->vval.v_string = getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr, xp_type, xp_arg); vim_free(xp_arg); /* since the user typed this, no need to wait for return */ need_wait_return = FALSE; msg_didout = FALSE; } cmd_silent = cmd_silent_save; } /* * "input()" function * Also handles inputsecret() when inputsecret is set. */ static void f_input(argvars, rettv) typval_T *argvars; typval_T *rettv; { get_user_input(argvars, rettv, FALSE); } /* * "inputdialog()" function */ static void f_inputdialog(argvars, rettv) typval_T *argvars; typval_T *rettv; { #if defined(FEAT_GUI_TEXTDIALOG) /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */ if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL) { char_u *message; char_u buf[NUMBUFLEN]; char_u *defstr = (char_u *)""; message = get_tv_string_chk(&argvars[0]); if (argvars[1].v_type != VAR_UNKNOWN && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL) vim_strncpy(IObuff, defstr, IOSIZE - 1); else IObuff[0] = NUL; if (message != NULL && defstr != NULL && do_dialog(VIM_QUESTION, NULL, message, (char_u *)_("&OK\n&Cancel"), 1, IObuff, FALSE) == 1) rettv->vval.v_string = vim_strsave(IObuff); else { if (message != NULL && defstr != NULL && argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN) rettv->vval.v_string = vim_strsave( get_tv_string_buf(&argvars[2], buf)); else rettv->vval.v_string = NULL; } rettv->v_type = VAR_STRING; } else #endif get_user_input(argvars, rettv, TRUE); } /* * "inputlist()" function */ static void f_inputlist(argvars, rettv) typval_T *argvars; typval_T *rettv; { listitem_T *li; int selected; int mouse_used; #ifdef NO_CONSOLE_INPUT /* While starting up, there is no place to enter text. */ if (no_console_input()) return; #endif if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL) { EMSG2(_(e_listarg), "inputlist()"); return; } msg_start(); msg_row = Rows - 1; /* for when 'cmdheight' > 1 */ lines_left = Rows; /* avoid more prompt */ msg_scroll = TRUE; msg_clr_eos(); for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next) { msg_puts(get_tv_string(&li->li_tv)); msg_putchar('\n'); } /* Ask for choice. */ selected = prompt_for_number(&mouse_used); if (mouse_used) selected -= lines_left; rettv->vval.v_number = selected; } static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL}; /* * "inputrestore()" function */ static void f_inputrestore(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { if (ga_userinput.ga_len > 0) { --ga_userinput.ga_len; restore_typeahead((tasave_T *)(ga_userinput.ga_data) + ga_userinput.ga_len); /* default return is zero == OK */ } else if (p_verbose > 1) { verb_msg((char_u *)_("called inputrestore() more often than inputsave()")); rettv->vval.v_number = 1; /* Failed */ } } /* * "inputsave()" function */ static void f_inputsave(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { /* Add an entry to the stack of typeahead storage. */ if (ga_grow(&ga_userinput, 1) == OK) { save_typeahead((tasave_T *)(ga_userinput.ga_data) + ga_userinput.ga_len); ++ga_userinput.ga_len; /* default return is zero == OK */ } else rettv->vval.v_number = 1; /* Failed */ } /* * "inputsecret()" function */ static void f_inputsecret(argvars, rettv) typval_T *argvars; typval_T *rettv; { ++cmdline_star; ++inputsecret_flag; f_input(argvars, rettv); --cmdline_star; --inputsecret_flag; } /* * "insert()" function */ static void f_insert(argvars, rettv) typval_T *argvars; typval_T *rettv; { long before = 0; listitem_T *item; list_T *l; int error = FALSE; if (argvars[0].v_type != VAR_LIST) EMSG2(_(e_listarg), "insert()"); else if ((l = argvars[0].vval.v_list) != NULL && !tv_check_lock(l->lv_lock, (char_u *)_("insert() argument"))) { if (argvars[2].v_type != VAR_UNKNOWN) before = get_tv_number_chk(&argvars[2], &error); if (error) return; /* type error; errmsg already given */ if (before == l->lv_len) item = NULL; else { item = list_find(l, before); if (item == NULL) { EMSGN(_(e_listidx), before); l = NULL; } } if (l != NULL) { list_insert_tv(l, &argvars[1], item); copy_tv(&argvars[0], rettv); } } } /* * "invert(expr)" function */ static void f_invert(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = ~get_tv_number_chk(&argvars[0], NULL); } /* * "isdirectory()" function */ static void f_isdirectory(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0])); } /* * "islocked()" function */ static void f_islocked(argvars, rettv) typval_T *argvars; typval_T *rettv; { lval_T lv; char_u *end; dictitem_T *di; rettv->vval.v_number = -1; end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START); if (end != NULL && lv.ll_name != NULL) { if (*end != NUL) EMSG(_(e_trailing)); else { if (lv.ll_tv == NULL) { if (check_changedtick(lv.ll_name)) rettv->vval.v_number = 1; /* always locked */ else { di = find_var(lv.ll_name, NULL); if (di != NULL) { /* Consider a variable locked when: * 1. the variable itself is locked * 2. the value of the variable is locked. * 3. the List or Dict value is locked. */ rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK) || tv_islocked(&di->di_tv)); } } } else if (lv.ll_range) EMSG(_("E786: Range not allowed")); else if (lv.ll_newkey != NULL) EMSG2(_(e_dictkey), lv.ll_newkey); else if (lv.ll_list != NULL) /* List item. */ rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv); else /* Dictionary item. */ rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv); } } clear_lval(&lv); } static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what)); /* * Turn a dict into a list: * "what" == 0: list of keys * "what" == 1: list of values * "what" == 2: list of items */ static void dict_list(argvars, rettv, what) typval_T *argvars; typval_T *rettv; int what; { list_T *l2; dictitem_T *di; hashitem_T *hi; listitem_T *li; listitem_T *li2; dict_T *d; int todo; if (argvars[0].v_type != VAR_DICT) { EMSG(_(e_dictreq)); return; } if ((d = argvars[0].vval.v_dict) == NULL) return; if (rettv_list_alloc(rettv) == FAIL) return; todo = (int)d->dv_hashtab.ht_used; for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); li = listitem_alloc(); if (li == NULL) break; list_append(rettv->vval.v_list, li); if (what == 0) { /* keys() */ li->li_tv.v_type = VAR_STRING; li->li_tv.v_lock = 0; li->li_tv.vval.v_string = vim_strsave(di->di_key); } else if (what == 1) { /* values() */ copy_tv(&di->di_tv, &li->li_tv); } else { /* items() */ l2 = list_alloc(); li->li_tv.v_type = VAR_LIST; li->li_tv.v_lock = 0; li->li_tv.vval.v_list = l2; if (l2 == NULL) break; ++l2->lv_refcount; li2 = listitem_alloc(); if (li2 == NULL) break; list_append(l2, li2); li2->li_tv.v_type = VAR_STRING; li2->li_tv.v_lock = 0; li2->li_tv.vval.v_string = vim_strsave(di->di_key); li2 = listitem_alloc(); if (li2 == NULL) break; list_append(l2, li2); copy_tv(&di->di_tv, &li2->li_tv); } } } } /* * "items(dict)" function */ static void f_items(argvars, rettv) typval_T *argvars; typval_T *rettv; { dict_list(argvars, rettv, 2); } /* * "join()" function */ static void f_join(argvars, rettv) typval_T *argvars; typval_T *rettv; { garray_T ga; char_u *sep; if (argvars[0].v_type != VAR_LIST) { EMSG(_(e_listreq)); return; } if (argvars[0].vval.v_list == NULL) return; if (argvars[1].v_type == VAR_UNKNOWN) sep = (char_u *)" "; else sep = get_tv_string_chk(&argvars[1]); rettv->v_type = VAR_STRING; if (sep != NULL) { ga_init2(&ga, (int)sizeof(char), 80); list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0); ga_append(&ga, NUL); rettv->vval.v_string = (char_u *)ga.ga_data; } else rettv->vval.v_string = NULL; } /* * "keys()" function */ static void f_keys(argvars, rettv) typval_T *argvars; typval_T *rettv; { dict_list(argvars, rettv, 0); } /* * "last_buffer_nr()" function. */ static void f_last_buffer_nr(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { int n = 0; buf_T *buf; for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (n < buf->b_fnum) n = buf->b_fnum; rettv->vval.v_number = n; } /* * "len()" function */ static void f_len(argvars, rettv) typval_T *argvars; typval_T *rettv; { switch (argvars[0].v_type) { case VAR_STRING: case VAR_NUMBER: rettv->vval.v_number = (varnumber_T)STRLEN( get_tv_string(&argvars[0])); break; case VAR_LIST: rettv->vval.v_number = list_len(argvars[0].vval.v_list); break; case VAR_DICT: rettv->vval.v_number = dict_len(argvars[0].vval.v_dict); break; default: EMSG(_("E701: Invalid type for len()")); break; } } static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type)); static void libcall_common(argvars, rettv, type) typval_T *argvars; typval_T *rettv; int type; { #ifdef FEAT_LIBCALL char_u *string_in; char_u **string_result; int nr_result; #endif rettv->v_type = type; if (type != VAR_NUMBER) rettv->vval.v_string = NULL; if (check_restricted() || check_secure()) return; #ifdef FEAT_LIBCALL /* The first two args must be strings, otherwise its meaningless */ if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING) { string_in = NULL; if (argvars[2].v_type == VAR_STRING) string_in = argvars[2].vval.v_string; if (type == VAR_NUMBER) string_result = NULL; else string_result = &rettv->vval.v_string; if (mch_libcall(argvars[0].vval.v_string, argvars[1].vval.v_string, string_in, argvars[2].vval.v_number, string_result, &nr_result) == OK && type == VAR_NUMBER) rettv->vval.v_number = nr_result; } #endif } /* * "libcall()" function */ static void f_libcall(argvars, rettv) typval_T *argvars; typval_T *rettv; { libcall_common(argvars, rettv, VAR_STRING); } /* * "libcallnr()" function */ static void f_libcallnr(argvars, rettv) typval_T *argvars; typval_T *rettv; { libcall_common(argvars, rettv, VAR_NUMBER); } /* * "line(string)" function */ static void f_line(argvars, rettv) typval_T *argvars; typval_T *rettv; { linenr_T lnum = 0; pos_T *fp; int fnum; fp = var2fpos(&argvars[0], TRUE, &fnum); if (fp != NULL) lnum = fp->lnum; rettv->vval.v_number = lnum; } /* * "line2byte(lnum)" function */ static void f_line2byte(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifndef FEAT_BYTEOFF rettv->vval.v_number = -1; #else linenr_T lnum; lnum = get_tv_lnum(argvars); if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1) rettv->vval.v_number = -1; else rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL); if (rettv->vval.v_number >= 0) ++rettv->vval.v_number; #endif } /* * "lispindent(lnum)" function */ static void f_lispindent(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_LISP pos_T pos; linenr_T lnum; pos = curwin->w_cursor; lnum = get_tv_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = lnum; rettv->vval.v_number = get_lisp_indent(); curwin->w_cursor = pos; } else #endif rettv->vval.v_number = -1; } /* * "localtime()" function */ static void f_localtime(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->vval.v_number = (varnumber_T)time(NULL); } static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact)); static void get_maparg(argvars, rettv, exact) typval_T *argvars; typval_T *rettv; int exact; { char_u *keys; char_u *which; char_u buf[NUMBUFLEN]; char_u *keys_buf = NULL; char_u *rhs; int mode; int abbr = FALSE; int get_dict = FALSE; mapblock_T *mp; int buffer_local; /* return empty string for failure */ rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; keys = get_tv_string(&argvars[0]); if (*keys == NUL) return; if (argvars[1].v_type != VAR_UNKNOWN) { which = get_tv_string_buf_chk(&argvars[1], buf); if (argvars[2].v_type != VAR_UNKNOWN) { abbr = get_tv_number(&argvars[2]); if (argvars[3].v_type != VAR_UNKNOWN) get_dict = get_tv_number(&argvars[3]); } } else which = (char_u *)""; if (which == NULL) return; mode = get_map_mode(&which, 0); keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE); rhs = check_map(keys, mode, exact, FALSE, abbr, &mp, &buffer_local); vim_free(keys_buf); if (!get_dict) { /* Return a string. */ if (rhs != NULL) rettv->vval.v_string = str2special_save(rhs, FALSE); } else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL) { /* Return a dictionary. */ char_u *lhs = str2special_save(mp->m_keys, TRUE); char_u *mapmode = map_mode_to_chars(mp->m_mode); dict_T *dict = rettv->vval.v_dict; dict_add_nr_str(dict, "lhs", 0L, lhs); dict_add_nr_str(dict, "rhs", 0L, mp->m_orig_str); dict_add_nr_str(dict, "noremap", mp->m_noremap ? 1L : 0L , NULL); dict_add_nr_str(dict, "expr", mp->m_expr ? 1L : 0L, NULL); dict_add_nr_str(dict, "silent", mp->m_silent ? 1L : 0L, NULL); dict_add_nr_str(dict, "sid", (long)mp->m_script_ID, NULL); dict_add_nr_str(dict, "buffer", (long)buffer_local, NULL); dict_add_nr_str(dict, "mode", 0L, mapmode); vim_free(lhs); vim_free(mapmode); } } #ifdef FEAT_FLOAT /* * "log()" function */ static void f_log(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = log(f); else rettv->vval.v_float = 0.0; } /* * "log10()" function */ static void f_log10(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = log10(f); else rettv->vval.v_float = 0.0; } #endif #ifdef FEAT_LUA /* * "luaeval()" function */ static void f_luaeval(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *str; char_u buf[NUMBUFLEN]; str = get_tv_string_buf(&argvars[0], buf); do_luaeval(str, argvars + 1, rettv); } #endif /* * "map()" function */ static void f_map(argvars, rettv) typval_T *argvars; typval_T *rettv; { filter_map(argvars, rettv, TRUE); } /* * "maparg()" function */ static void f_maparg(argvars, rettv) typval_T *argvars; typval_T *rettv; { get_maparg(argvars, rettv, TRUE); } /* * "mapcheck()" function */ static void f_mapcheck(argvars, rettv) typval_T *argvars; typval_T *rettv; { get_maparg(argvars, rettv, FALSE); } static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start)); static void find_some_match(argvars, rettv, type) typval_T *argvars; typval_T *rettv; int type; { char_u *str = NULL; char_u *expr = NULL; char_u *pat; regmatch_T regmatch; char_u patbuf[NUMBUFLEN]; char_u strbuf[NUMBUFLEN]; char_u *save_cpo; long start = 0; long nth = 1; colnr_T startcol = 0; int match = 0; list_T *l = NULL; listitem_T *li = NULL; long idx = 0; char_u *tofree = NULL; /* Make 'cpoptions' empty, the 'l' flag should not be used here. */ save_cpo = p_cpo; p_cpo = (char_u *)""; rettv->vval.v_number = -1; if (type == 3) { /* return empty list when there are no matches */ if (rettv_list_alloc(rettv) == FAIL) goto theend; } else if (type == 2) { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; } if (argvars[0].v_type == VAR_LIST) { if ((l = argvars[0].vval.v_list) == NULL) goto theend; li = l->lv_first; } else expr = str = get_tv_string(&argvars[0]); pat = get_tv_string_buf_chk(&argvars[1], patbuf); if (pat == NULL) goto theend; if (argvars[2].v_type != VAR_UNKNOWN) { int error = FALSE; start = get_tv_number_chk(&argvars[2], &error); if (error) goto theend; if (l != NULL) { li = list_find(l, start); if (li == NULL) goto theend; idx = l->lv_idx; /* use the cached index */ } else { if (start < 0) start = 0; if (start > (long)STRLEN(str)) goto theend; /* When "count" argument is there ignore matches before "start", * otherwise skip part of the string. Differs when pattern is "^" * or "\<". */ if (argvars[3].v_type != VAR_UNKNOWN) startcol = start; else str += start; } if (argvars[3].v_type != VAR_UNKNOWN) nth = get_tv_number_chk(&argvars[3], &error); if (error) goto theend; } regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING); if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; for (;;) { if (l != NULL) { if (li == NULL) { match = FALSE; break; } vim_free(tofree); str = echo_string(&li->li_tv, &tofree, strbuf, 0); if (str == NULL) break; } match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol); if (match && --nth <= 0) break; if (l == NULL && !match) break; /* Advance to just after the match. */ if (l != NULL) { li = li->li_next; ++idx; } else { #ifdef FEAT_MBYTE startcol = (colnr_T)(regmatch.startp[0] + (*mb_ptr2len)(regmatch.startp[0]) - str); #else startcol = (colnr_T)(regmatch.startp[0] + 1 - str); #endif } } if (match) { if (type == 3) { int i; /* return list with matched string and submatches */ for (i = 0; i < NSUBEXP; ++i) { if (regmatch.endp[i] == NULL) { if (list_append_string(rettv->vval.v_list, (char_u *)"", 0) == FAIL) break; } else if (list_append_string(rettv->vval.v_list, regmatch.startp[i], (int)(regmatch.endp[i] - regmatch.startp[i])) == FAIL) break; } } else if (type == 2) { /* return matched string */ if (l != NULL) copy_tv(&li->li_tv, rettv); else rettv->vval.v_string = vim_strnsave(regmatch.startp[0], (int)(regmatch.endp[0] - regmatch.startp[0])); } else if (l != NULL) rettv->vval.v_number = idx; else { if (type != 0) rettv->vval.v_number = (varnumber_T)(regmatch.startp[0] - str); else rettv->vval.v_number = (varnumber_T)(regmatch.endp[0] - str); rettv->vval.v_number += (varnumber_T)(str - expr); } } vim_free(regmatch.regprog); } theend: vim_free(tofree); p_cpo = save_cpo; } /* * "match()" function */ static void f_match(argvars, rettv) typval_T *argvars; typval_T *rettv; { find_some_match(argvars, rettv, 1); } /* * "matchadd()" function */ static void f_matchadd(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_SEARCH_EXTRA char_u buf[NUMBUFLEN]; char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */ char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */ int prio = 10; /* default priority */ int id = -1; int error = FALSE; rettv->vval.v_number = -1; if (grp == NULL || pat == NULL) return; if (argvars[2].v_type != VAR_UNKNOWN) { prio = get_tv_number_chk(&argvars[2], &error); if (argvars[3].v_type != VAR_UNKNOWN) id = get_tv_number_chk(&argvars[3], &error); } if (error == TRUE) return; if (id >= 1 && id <= 3) { EMSGN("E798: ID is reserved for \":match\": %ld", id); return; } rettv->vval.v_number = match_add(curwin, grp, pat, prio, id); #endif } /* * "matcharg()" function */ static void f_matcharg(argvars, rettv) typval_T *argvars; typval_T *rettv; { if (rettv_list_alloc(rettv) == OK) { #ifdef FEAT_SEARCH_EXTRA int id = get_tv_number(&argvars[0]); matchitem_T *m; if (id >= 1 && id <= 3) { if ((m = (matchitem_T *)get_match(curwin, id)) != NULL) { list_append_string(rettv->vval.v_list, syn_id2name(m->hlg_id), -1); list_append_string(rettv->vval.v_list, m->pattern, -1); } else { list_append_string(rettv->vval.v_list, NUL, -1); list_append_string(rettv->vval.v_list, NUL, -1); } } #endif } } /* * "matchdelete()" function */ static void f_matchdelete(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_SEARCH_EXTRA rettv->vval.v_number = match_delete(curwin, (int)get_tv_number(&argvars[0]), TRUE); #endif } /* * "matchend()" function */ static void f_matchend(argvars, rettv) typval_T *argvars; typval_T *rettv; { find_some_match(argvars, rettv, 0); } /* * "matchlist()" function */ static void f_matchlist(argvars, rettv) typval_T *argvars; typval_T *rettv; { find_some_match(argvars, rettv, 3); } /* * "matchstr()" function */ static void f_matchstr(argvars, rettv) typval_T *argvars; typval_T *rettv; { find_some_match(argvars, rettv, 2); } static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax)); static void max_min(argvars, rettv, domax) typval_T *argvars; typval_T *rettv; int domax; { long n = 0; long i; int error = FALSE; if (argvars[0].v_type == VAR_LIST) { list_T *l; listitem_T *li; l = argvars[0].vval.v_list; if (l != NULL) { li = l->lv_first; if (li != NULL) { n = get_tv_number_chk(&li->li_tv, &error); for (;;) { li = li->li_next; if (li == NULL) break; i = get_tv_number_chk(&li->li_tv, &error); if (domax ? i > n : i < n) n = i; } } } } else if (argvars[0].v_type == VAR_DICT) { dict_T *d; int first = TRUE; hashitem_T *hi; int todo; d = argvars[0].vval.v_dict; if (d != NULL) { todo = (int)d->dv_hashtab.ht_used; for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error); if (first) { n = i; first = FALSE; } else if (domax ? i > n : i < n) n = i; } } } } else EMSG(_(e_listdictarg)); rettv->vval.v_number = error ? 0 : n; } /* * "max()" function */ static void f_max(argvars, rettv) typval_T *argvars; typval_T *rettv; { max_min(argvars, rettv, TRUE); } /* * "min()" function */ static void f_min(argvars, rettv) typval_T *argvars; typval_T *rettv; { max_min(argvars, rettv, FALSE); } static int mkdir_recurse __ARGS((char_u *dir, int prot)); /* * Create the directory in which "dir" is located, and higher levels when * needed. */ static int mkdir_recurse(dir, prot) char_u *dir; int prot; { char_u *p; char_u *updir; int r = FAIL; /* Get end of directory name in "dir". * We're done when it's "/" or "c:/". */ p = gettail_sep(dir); if (p <= get_past_head(dir)) return OK; /* If the directory exists we're done. Otherwise: create it.*/ updir = vim_strnsave(dir, (int)(p - dir)); if (updir == NULL) return FAIL; if (mch_isdir(updir)) r = OK; else if (mkdir_recurse(updir, prot) == OK) r = vim_mkdir_emsg(updir, prot); vim_free(updir); return r; } #ifdef vim_mkdir /* * "mkdir()" function */ static void f_mkdir(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *dir; char_u buf[NUMBUFLEN]; int prot = 0755; rettv->vval.v_number = FAIL; if (check_restricted() || check_secure()) return; dir = get_tv_string_buf(&argvars[0], buf); if (argvars[1].v_type != VAR_UNKNOWN) { if (argvars[2].v_type != VAR_UNKNOWN) prot = get_tv_number_chk(&argvars[2], NULL); if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0) mkdir_recurse(dir, prot); } rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0; } #endif /* * "mode()" function */ static void f_mode(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u buf[3]; buf[1] = NUL; buf[2] = NUL; #ifdef FEAT_VISUAL if (VIsual_active) { if (VIsual_select) buf[0] = VIsual_mode + 's' - 'v'; else buf[0] = VIsual_mode; } else #endif if (State == HITRETURN || State == ASKMORE || State == SETWSIZE || State == CONFIRM) { buf[0] = 'r'; if (State == ASKMORE) buf[1] = 'm'; else if (State == CONFIRM) buf[1] = '?'; } else if (State == EXTERNCMD) buf[0] = '!'; else if (State & INSERT) { #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) { buf[0] = 'R'; buf[1] = 'v'; } else #endif if (State & REPLACE_FLAG) buf[0] = 'R'; else buf[0] = 'i'; } else if (State & CMDLINE) { buf[0] = 'c'; if (exmode_active) buf[1] = 'v'; } else if (exmode_active) { buf[0] = 'c'; buf[1] = 'e'; } else { buf[0] = 'n'; if (finish_op) buf[1] = 'o'; } /* Clear out the minor mode when the argument is not a non-zero number or * non-empty string. */ if (!non_zero_arg(&argvars[0])) buf[1] = NUL; rettv->vval.v_string = vim_strsave(buf); rettv->v_type = VAR_STRING; } #ifdef FEAT_MZSCHEME /* * "mzeval()" function */ static void f_mzeval(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *str; char_u buf[NUMBUFLEN]; str = get_tv_string_buf(&argvars[0], buf); do_mzeval(str, rettv); } #endif /* * "nextnonblank()" function */ static void f_nextnonblank(argvars, rettv) typval_T *argvars; typval_T *rettv; { linenr_T lnum; for (lnum = get_tv_lnum(argvars); ; ++lnum) { if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count) { lnum = 0; break; } if (*skipwhite(ml_get(lnum)) != NUL) break; } rettv->vval.v_number = lnum; } /* * "nr2char()" function */ static void f_nr2char(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u buf[NUMBUFLEN]; #ifdef FEAT_MBYTE if (has_mbyte) buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL; else #endif { buf[0] = (char_u)get_tv_number(&argvars[0]); buf[1] = NUL; } rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_strsave(buf); } /* * "or(expr, expr)" function */ static void f_or(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL) | get_tv_number_chk(&argvars[1], NULL); } /* * "pathshorten()" function */ static void f_pathshorten(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *p; rettv->v_type = VAR_STRING; p = get_tv_string_chk(&argvars[0]); if (p == NULL) rettv->vval.v_string = NULL; else { p = vim_strsave(p); rettv->vval.v_string = p; if (p != NULL) shorten_dir(p); } } #ifdef FEAT_FLOAT /* * "pow()" function */ static void f_pow(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T fx, fy; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &fx) == OK && get_float_arg(&argvars[1], &fy) == OK) rettv->vval.v_float = pow(fx, fy); else rettv->vval.v_float = 0.0; } #endif /* * "prevnonblank()" function */ static void f_prevnonblank(argvars, rettv) typval_T *argvars; typval_T *rettv; { linenr_T lnum; lnum = get_tv_lnum(argvars); if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) lnum = 0; else while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL) --lnum; rettv->vval.v_number = lnum; } #ifdef HAVE_STDARG_H /* This dummy va_list is here because: * - passing a NULL pointer doesn't work when va_list isn't a pointer * - locally in the function results in a "used before set" warning * - using va_start() to initialize it gives "function with fixed args" error */ static va_list ap; #endif /* * "printf()" function */ static void f_printf(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; #ifdef HAVE_STDARG_H /* only very old compilers can't do this */ { char_u buf[NUMBUFLEN]; int len; char_u *s; int saved_did_emsg = did_emsg; char *fmt; /* Get the required length, allocate the buffer and do it for real. */ did_emsg = FALSE; fmt = (char *)get_tv_string_buf(&argvars[0], buf); len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1); if (!did_emsg) { s = alloc(len + 1); if (s != NULL) { rettv->vval.v_string = s; (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1); } } did_emsg |= saved_did_emsg; } #endif } /* * "pumvisible()" function */ static void f_pumvisible(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_INS_EXPAND if (pum_visible()) rettv->vval.v_number = 1; #endif } /* * "range()" function */ static void f_range(argvars, rettv) typval_T *argvars; typval_T *rettv; { long start; long end; long stride = 1; long i; int error = FALSE; start = get_tv_number_chk(&argvars[0], &error); if (argvars[1].v_type == VAR_UNKNOWN) { end = start - 1; start = 0; } else { end = get_tv_number_chk(&argvars[1], &error); if (argvars[2].v_type != VAR_UNKNOWN) stride = get_tv_number_chk(&argvars[2], &error); } if (error) return; /* type error; errmsg already given */ if (stride == 0) EMSG(_("E726: Stride is zero")); else if (stride > 0 ? end + 1 < start : end - 1 > start) EMSG(_("E727: Start past end")); else { if (rettv_list_alloc(rettv) == OK) for (i = start; stride > 0 ? i <= end : i >= end; i += stride) if (list_append_number(rettv->vval.v_list, (varnumber_T)i) == FAIL) break; } } /* * "readfile()" function */ static void f_readfile(argvars, rettv) typval_T *argvars; typval_T *rettv; { int binary = FALSE; int failed = FALSE; char_u *fname; FILE *fd; char_u buf[(IOSIZE/256)*256]; /* rounded to avoid odd + 1 */ int io_size = sizeof(buf); int readlen; /* size of last fread() */ char_u *prev = NULL; /* previously read bytes, if any */ long prevlen = 0; /* length of data in prev */ long prevsize = 0; /* size of prev buffer */ long maxline = MAXLNUM; long cnt = 0; char_u *p; /* position in buf */ char_u *start; /* start of current line */ if (argvars[1].v_type != VAR_UNKNOWN) { if (STRCMP(get_tv_string(&argvars[1]), "b") == 0) binary = TRUE; if (argvars[2].v_type != VAR_UNKNOWN) maxline = get_tv_number(&argvars[2]); } if (rettv_list_alloc(rettv) == FAIL) return; /* Always open the file in binary mode, library functions have a mind of * their own about CR-LF conversion. */ fname = get_tv_string(&argvars[0]); if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL) { EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname); return; } while (cnt < maxline || maxline < 0) { readlen = (int)fread(buf, 1, io_size, fd); /* This for loop processes what was read, but is also entered at end * of file so that either: * - an incomplete line gets written * - a "binary" file gets an empty line at the end if it ends in a * newline. */ for (p = buf, start = buf; p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary)); ++p) { if (*p == '\n' || readlen <= 0) { listitem_T *li; char_u *s = NULL; long_u len = p - start; /* Finished a line. Remove CRs before NL. */ if (readlen > 0 && !binary) { while (len > 0 && start[len - 1] == '\r') --len; /* removal may cross back to the "prev" string */ if (len == 0) while (prevlen > 0 && prev[prevlen - 1] == '\r') --prevlen; } if (prevlen == 0) s = vim_strnsave(start, (int)len); else { /* Change "prev" buffer to be the right size. This way * the bytes are only copied once, and very long lines are * allocated only once. */ if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL) { mch_memmove(s + prevlen, start, len); s[prevlen + len] = NUL; prev = NULL; /* the list will own the string */ prevlen = prevsize = 0; } } if (s == NULL) { do_outofmem_msg((long_u) prevlen + len + 1); failed = TRUE; break; } if ((li = listitem_alloc()) == NULL) { vim_free(s); failed = TRUE; break; } li->li_tv.v_type = VAR_STRING; li->li_tv.v_lock = 0; li->li_tv.vval.v_string = s; list_append(rettv->vval.v_list, li); start = p + 1; /* step over newline */ if ((++cnt >= maxline && maxline >= 0) || readlen <= 0) break; } else if (*p == NUL) *p = '\n'; #ifdef FEAT_MBYTE /* Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this * when finding the BF and check the previous two bytes. */ else if (*p == 0xbf && enc_utf8 && !binary) { /* Find the two bytes before the 0xbf. If p is at buf, or buf * + 1, these may be in the "prev" string. */ char_u back1 = p >= buf + 1 ? p[-1] : prevlen >= 1 ? prev[prevlen - 1] : NUL; char_u back2 = p >= buf + 2 ? p[-2] : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1] : prevlen >= 2 ? prev[prevlen - 2] : NUL; if (back2 == 0xef && back1 == 0xbb) { char_u *dest = p - 2; /* Usually a BOM is at the beginning of a file, and so at * the beginning of a line; then we can just step over it. */ if (start == dest) start = p + 1; else { /* have to shuffle buf to close gap */ int adjust_prevlen = 0; if (dest < buf) { adjust_prevlen = (int)(buf - dest); /* must be 1 or 2 */ dest = buf; } if (readlen > p - buf + 1) mch_memmove(dest, p + 1, readlen - (p - buf) - 1); readlen -= 3 - adjust_prevlen; prevlen -= adjust_prevlen; p = dest - 1; } } } #endif } /* for */ if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0) break; if (start < p) { /* There's part of a line in buf, store it in "prev". */ if (p - start + prevlen >= prevsize) { /* need bigger "prev" buffer */ char_u *newprev; /* A common use case is ordinary text files and "prev" gets a * fragment of a line, so the first allocation is made * small, to avoid repeatedly 'allocing' large and * 'reallocing' small. */ if (prevsize == 0) prevsize = (long)(p - start); else { long grow50pc = (prevsize * 3) / 2; long growmin = (long)((p - start) * 2 + prevlen); prevsize = grow50pc > growmin ? grow50pc : growmin; } newprev = prev == NULL ? alloc(prevsize) : vim_realloc(prev, prevsize); if (newprev == NULL) { do_outofmem_msg((long_u)prevsize); failed = TRUE; break; } prev = newprev; } /* Add the line part to end of "prev". */ mch_memmove(prev + prevlen, start, p - start); prevlen += (long)(p - start); } } /* while */ /* * For a negative line count use only the lines at the end of the file, * free the rest. */ if (!failed && maxline < 0) while (cnt > -maxline) { listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first); --cnt; } if (failed) { list_free(rettv->vval.v_list, TRUE); /* readfile doc says an empty list is returned on error */ rettv->vval.v_list = list_alloc(); } vim_free(prev); fclose(fd); } #if defined(FEAT_RELTIME) static int list2proftime __ARGS((typval_T *arg, proftime_T *tm)); /* * Convert a List to proftime_T. * Return FAIL when there is something wrong. */ static int list2proftime(arg, tm) typval_T *arg; proftime_T *tm; { long n1, n2; int error = FALSE; if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL || arg->vval.v_list->lv_len != 2) return FAIL; n1 = list_find_nr(arg->vval.v_list, 0L, &error); n2 = list_find_nr(arg->vval.v_list, 1L, &error); # ifdef WIN3264 tm->HighPart = n1; tm->LowPart = n2; # else tm->tv_sec = n1; tm->tv_usec = n2; # endif return error ? FAIL : OK; } #endif /* FEAT_RELTIME */ /* * "reltime()" function */ static void f_reltime(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_RELTIME proftime_T res; proftime_T start; if (argvars[0].v_type == VAR_UNKNOWN) { /* No arguments: get current time. */ profile_start(&res); } else if (argvars[1].v_type == VAR_UNKNOWN) { if (list2proftime(&argvars[0], &res) == FAIL) return; profile_end(&res); } else { /* Two arguments: compute the difference. */ if (list2proftime(&argvars[0], &start) == FAIL || list2proftime(&argvars[1], &res) == FAIL) return; profile_sub(&res, &start); } if (rettv_list_alloc(rettv) == OK) { long n1, n2; # ifdef WIN3264 n1 = res.HighPart; n2 = res.LowPart; # else n1 = res.tv_sec; n2 = res.tv_usec; # endif list_append_number(rettv->vval.v_list, (varnumber_T)n1); list_append_number(rettv->vval.v_list, (varnumber_T)n2); } #endif } /* * "reltimestr()" function */ static void f_reltimestr(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_RELTIME proftime_T tm; #endif rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; #ifdef FEAT_RELTIME if (list2proftime(&argvars[0], &tm) == OK) rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm)); #endif } #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11) static void make_connection __ARGS((void)); static int check_connection __ARGS((void)); static void make_connection() { if (X_DISPLAY == NULL # ifdef FEAT_GUI && !gui.in_use # endif ) { x_force_connect = TRUE; setup_term_clip(); x_force_connect = FALSE; } } static int check_connection() { make_connection(); if (X_DISPLAY == NULL) { EMSG(_("E240: No connection to Vim server")); return FAIL; } return OK; } #endif #ifdef FEAT_CLIENTSERVER static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr)); static void remote_common(argvars, rettv, expr) typval_T *argvars; typval_T *rettv; int expr; { char_u *server_name; char_u *keys; char_u *r = NULL; char_u buf[NUMBUFLEN]; # ifdef WIN32 HWND w; # else Window w; # endif if (check_restricted() || check_secure()) return; # ifdef FEAT_X11 if (check_connection() == FAIL) return; # endif server_name = get_tv_string_chk(&argvars[0]); if (server_name == NULL) return; /* type error; errmsg already given */ keys = get_tv_string_buf(&argvars[1], buf); # ifdef WIN32 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0) # else if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE) < 0) # endif { if (r != NULL) EMSG(r); /* sending worked but evaluation failed */ else EMSG2(_("E241: Unable to send to %s"), server_name); return; } rettv->vval.v_string = r; if (argvars[2].v_type != VAR_UNKNOWN) { dictitem_T v; char_u str[30]; char_u *idvar; sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w); v.di_tv.v_type = VAR_STRING; v.di_tv.vval.v_string = vim_strsave(str); idvar = get_tv_string_chk(&argvars[2]); if (idvar != NULL) set_var(idvar, &v.di_tv, FALSE); vim_free(v.di_tv.vval.v_string); } } #endif /* * "remote_expr()" function */ static void f_remote_expr(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; #ifdef FEAT_CLIENTSERVER remote_common(argvars, rettv, TRUE); #endif } /* * "remote_foreground()" function */ static void f_remote_foreground(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_CLIENTSERVER # ifdef WIN32 /* On Win32 it's done in this application. */ { char_u *server_name = get_tv_string_chk(&argvars[0]); if (server_name != NULL) serverForeground(server_name); } # else /* Send a foreground() expression to the server. */ argvars[1].v_type = VAR_STRING; argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()"); argvars[2].v_type = VAR_UNKNOWN; remote_common(argvars, rettv, TRUE); vim_free(argvars[1].vval.v_string); # endif #endif } static void f_remote_peek(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_CLIENTSERVER dictitem_T v; char_u *s = NULL; # ifdef WIN32 long_u n = 0; # endif char_u *serverid; if (check_restricted() || check_secure()) { rettv->vval.v_number = -1; return; } serverid = get_tv_string_chk(&argvars[0]); if (serverid == NULL) { rettv->vval.v_number = -1; return; /* type error; errmsg already given */ } # ifdef WIN32 sscanf(serverid, SCANF_HEX_LONG_U, &n); if (n == 0) rettv->vval.v_number = -1; else { s = serverGetReply((HWND)n, FALSE, FALSE, FALSE); rettv->vval.v_number = (s != NULL); } # else if (check_connection() == FAIL) return; rettv->vval.v_number = serverPeekReply(X_DISPLAY, serverStrToWin(serverid), &s); # endif if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0) { char_u *retvar; v.di_tv.v_type = VAR_STRING; v.di_tv.vval.v_string = vim_strsave(s); retvar = get_tv_string_chk(&argvars[1]); if (retvar != NULL) set_var(retvar, &v.di_tv, FALSE); vim_free(v.di_tv.vval.v_string); } #else rettv->vval.v_number = -1; #endif } static void f_remote_read(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { char_u *r = NULL; #ifdef FEAT_CLIENTSERVER char_u *serverid = get_tv_string_chk(&argvars[0]); if (serverid != NULL && !check_restricted() && !check_secure()) { # ifdef WIN32 /* The server's HWND is encoded in the 'id' parameter */ long_u n = 0; sscanf(serverid, SCANF_HEX_LONG_U, &n); if (n != 0) r = serverGetReply((HWND)n, FALSE, TRUE, TRUE); if (r == NULL) # else if (check_connection() == FAIL || serverReadReply(X_DISPLAY, serverStrToWin(serverid), &r, FALSE) < 0) # endif EMSG(_("E277: Unable to read a server reply")); } #endif rettv->v_type = VAR_STRING; rettv->vval.v_string = r; } /* * "remote_send()" function */ static void f_remote_send(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; #ifdef FEAT_CLIENTSERVER remote_common(argvars, rettv, FALSE); #endif } /* * "remove()" function */ static void f_remove(argvars, rettv) typval_T *argvars; typval_T *rettv; { list_T *l; listitem_T *item, *item2; listitem_T *li; long idx; long end; char_u *key; dict_T *d; dictitem_T *di; char *arg_errmsg = N_("remove() argument"); if (argvars[0].v_type == VAR_DICT) { if (argvars[2].v_type != VAR_UNKNOWN) EMSG2(_(e_toomanyarg), "remove()"); else if ((d = argvars[0].vval.v_dict) != NULL && !tv_check_lock(d->dv_lock, (char_u *)_(arg_errmsg))) { key = get_tv_string_chk(&argvars[1]); if (key != NULL) { di = dict_find(d, key, -1); if (di == NULL) EMSG2(_(e_dictkey), key); else { *rettv = di->di_tv; init_tv(&di->di_tv); dictitem_remove(d, di); } } } } else if (argvars[0].v_type != VAR_LIST) EMSG2(_(e_listdictarg), "remove()"); else if ((l = argvars[0].vval.v_list) != NULL && !tv_check_lock(l->lv_lock, (char_u *)_(arg_errmsg))) { int error = FALSE; idx = get_tv_number_chk(&argvars[1], &error); if (error) ; /* type error: do nothing, errmsg already given */ else if ((item = list_find(l, idx)) == NULL) EMSGN(_(e_listidx), idx); else { if (argvars[2].v_type == VAR_UNKNOWN) { /* Remove one item, return its value. */ list_remove(l, item, item); *rettv = item->li_tv; vim_free(item); } else { /* Remove range of items, return list with values. */ end = get_tv_number_chk(&argvars[2], &error); if (error) ; /* type error: do nothing */ else if ((item2 = list_find(l, end)) == NULL) EMSGN(_(e_listidx), end); else { int cnt = 0; for (li = item; li != NULL; li = li->li_next) { ++cnt; if (li == item2) break; } if (li == NULL) /* didn't find "item2" after "item" */ EMSG(_(e_invrange)); else { list_remove(l, item, item2); if (rettv_list_alloc(rettv) == OK) { l = rettv->vval.v_list; l->lv_first = item; l->lv_last = item2; item->li_prev = NULL; item2->li_next = NULL; l->lv_len = cnt; } } } } } } } /* * "rename({from}, {to})" function */ static void f_rename(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u buf[NUMBUFLEN]; if (check_restricted() || check_secure()) rettv->vval.v_number = -1; else rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]), get_tv_string_buf(&argvars[1], buf)); } /* * "repeat()" function */ static void f_repeat(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *p; int n; int slen; int len; char_u *r; int i; n = get_tv_number(&argvars[1]); if (argvars[0].v_type == VAR_LIST) { if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL) while (n-- > 0) if (list_extend(rettv->vval.v_list, argvars[0].vval.v_list, NULL) == FAIL) break; } else { p = get_tv_string(&argvars[0]); rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; slen = (int)STRLEN(p); len = slen * n; if (len <= 0) return; r = alloc(len + 1); if (r != NULL) { for (i = 0; i < n; i++) mch_memmove(r + i * slen, p, (size_t)slen); r[len] = NUL; } rettv->vval.v_string = r; } } /* * "resolve()" function */ static void f_resolve(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *p; #ifdef HAVE_READLINK char_u *buf = NULL; #endif p = get_tv_string(&argvars[0]); #ifdef FEAT_SHORTCUT { char_u *v = NULL; v = mch_resolve_shortcut(p); if (v != NULL) rettv->vval.v_string = v; else rettv->vval.v_string = vim_strsave(p); } #else # ifdef HAVE_READLINK { char_u *cpy; int len; char_u *remain = NULL; char_u *q; int is_relative_to_current = FALSE; int has_trailing_pathsep = FALSE; int limit = 100; p = vim_strsave(p); if (p[0] == '.' && (vim_ispathsep(p[1]) || (p[1] == '.' && (vim_ispathsep(p[2]))))) is_relative_to_current = TRUE; len = STRLEN(p); if (len > 0 && after_pathsep(p, p + len)) { has_trailing_pathsep = TRUE; p[len - 1] = NUL; /* the trailing slash breaks readlink() */ } q = getnextcomp(p); if (*q != NUL) { /* Separate the first path component in "p", and keep the * remainder (beginning with the path separator). */ remain = vim_strsave(q - 1); q[-1] = NUL; } buf = alloc(MAXPATHL + 1); if (buf == NULL) goto fail; for (;;) { for (;;) { len = readlink((char *)p, (char *)buf, MAXPATHL); if (len <= 0) break; buf[len] = NUL; if (limit-- == 0) { vim_free(p); vim_free(remain); EMSG(_("E655: Too many symbolic links (cycle?)")); rettv->vval.v_string = NULL; goto fail; } /* Ensure that the result will have a trailing path separator * if the argument has one. */ if (remain == NULL && has_trailing_pathsep) add_pathsep(buf); /* Separate the first path component in the link value and * concatenate the remainders. */ q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf); if (*q != NUL) { if (remain == NULL) remain = vim_strsave(q - 1); else { cpy = concat_str(q - 1, remain); if (cpy != NULL) { vim_free(remain); remain = cpy; } } q[-1] = NUL; } q = gettail(p); if (q > p && *q == NUL) { /* Ignore trailing path separator. */ q[-1] = NUL; q = gettail(p); } if (q > p && !mch_isFullName(buf)) { /* symlink is relative to directory of argument */ cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1)); if (cpy != NULL) { STRCPY(cpy, p); STRCPY(gettail(cpy), buf); vim_free(p); p = cpy; } } else { vim_free(p); p = vim_strsave(buf); } } if (remain == NULL) break; /* Append the first path component of "remain" to "p". */ q = getnextcomp(remain + 1); len = q - remain - (*q != NUL); cpy = vim_strnsave(p, STRLEN(p) + len); if (cpy != NULL) { STRNCAT(cpy, remain, len); vim_free(p); p = cpy; } /* Shorten "remain". */ if (*q != NUL) STRMOVE(remain, q - 1); else { vim_free(remain); remain = NULL; } } /* If the result is a relative path name, make it explicitly relative to * the current directory if and only if the argument had this form. */ if (!vim_ispathsep(*p)) { if (is_relative_to_current && *p != NUL && !(p[0] == '.' && (p[1] == NUL || vim_ispathsep(p[1]) || (p[1] == '.' && (p[2] == NUL || vim_ispathsep(p[2])))))) { /* Prepend "./". */ cpy = concat_str((char_u *)"./", p); if (cpy != NULL) { vim_free(p); p = cpy; } } else if (!is_relative_to_current) { /* Strip leading "./". */ q = p; while (q[0] == '.' && vim_ispathsep(q[1])) q += 2; if (q > p) STRMOVE(p, p + 2); } } /* Ensure that the result will have no trailing path separator * if the argument had none. But keep "/" or "//". */ if (!has_trailing_pathsep) { q = p + STRLEN(p); if (after_pathsep(p, q)) *gettail_sep(p) = NUL; } rettv->vval.v_string = p; } # else rettv->vval.v_string = vim_strsave(p); # endif #endif simplify_filename(rettv->vval.v_string); #ifdef HAVE_READLINK fail: vim_free(buf); #endif rettv->v_type = VAR_STRING; } /* * "reverse({list})" function */ static void f_reverse(argvars, rettv) typval_T *argvars; typval_T *rettv; { list_T *l; listitem_T *li, *ni; if (argvars[0].v_type != VAR_LIST) EMSG2(_(e_listarg), "reverse()"); else if ((l = argvars[0].vval.v_list) != NULL && !tv_check_lock(l->lv_lock, (char_u *)_("reverse() argument"))) { li = l->lv_last; l->lv_first = l->lv_last = NULL; l->lv_len = 0; while (li != NULL) { ni = li->li_prev; list_append(l, li); li = ni; } rettv->vval.v_list = l; rettv->v_type = VAR_LIST; ++l->lv_refcount; l->lv_idx = l->lv_len - l->lv_idx - 1; } } #define SP_NOMOVE 0x01 /* don't move cursor */ #define SP_REPEAT 0x02 /* repeat to find outer pair */ #define SP_RETCOUNT 0x04 /* return matchcount */ #define SP_SETPCMARK 0x08 /* set previous context mark */ #define SP_START 0x10 /* accept match at start position */ #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */ #define SP_END 0x40 /* leave cursor at end of match */ static int get_search_arg __ARGS((typval_T *varp, int *flagsp)); /* * Get flags for a search function. * Possibly sets "p_ws". * Returns BACKWARD, FORWARD or zero (for an error). */ static int get_search_arg(varp, flagsp) typval_T *varp; int *flagsp; { int dir = FORWARD; char_u *flags; char_u nbuf[NUMBUFLEN]; int mask; if (varp->v_type != VAR_UNKNOWN) { flags = get_tv_string_buf_chk(varp, nbuf); if (flags == NULL) return 0; /* type error; errmsg already given */ while (*flags != NUL) { switch (*flags) { case 'b': dir = BACKWARD; break; case 'w': p_ws = TRUE; break; case 'W': p_ws = FALSE; break; default: mask = 0; if (flagsp != NULL) switch (*flags) { case 'c': mask = SP_START; break; case 'e': mask = SP_END; break; case 'm': mask = SP_RETCOUNT; break; case 'n': mask = SP_NOMOVE; break; case 'p': mask = SP_SUBPAT; break; case 'r': mask = SP_REPEAT; break; case 's': mask = SP_SETPCMARK; break; } if (mask == 0) { EMSG2(_(e_invarg2), flags); dir = 0; } else *flagsp |= mask; } if (dir == 0) break; ++flags; } } return dir; } /* * Shared by search() and searchpos() functions */ static int search_cmn(argvars, match_pos, flagsp) typval_T *argvars; pos_T *match_pos; int *flagsp; { int flags; char_u *pat; pos_T pos; pos_T save_cursor; int save_p_ws = p_ws; int dir; int retval = 0; /* default: FAIL */ long lnum_stop = 0; proftime_T tm; #ifdef FEAT_RELTIME long time_limit = 0; #endif int options = SEARCH_KEEP; int subpatnum; pat = get_tv_string(&argvars[0]); dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */ if (dir == 0) goto theend; flags = *flagsp; if (flags & SP_START) options |= SEARCH_START; if (flags & SP_END) options |= SEARCH_END; /* Optional arguments: line number to stop searching and timeout. */ if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN) { lnum_stop = get_tv_number_chk(&argvars[2], NULL); if (lnum_stop < 0) goto theend; #ifdef FEAT_RELTIME if (argvars[3].v_type != VAR_UNKNOWN) { time_limit = get_tv_number_chk(&argvars[3], NULL); if (time_limit < 0) goto theend; } #endif } #ifdef FEAT_RELTIME /* Set the time limit, if there is one. */ profile_setlimit(time_limit, &tm); #endif /* * This function does not accept SP_REPEAT and SP_RETCOUNT flags. * Check to make sure only those flags are set. * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both * flags cannot be set. Check for that condition also. */ if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0) || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK))) { EMSG2(_(e_invarg2), get_tv_string(&argvars[1])); goto theend; } pos = save_cursor = curwin->w_cursor; subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L, options, RE_SEARCH, (linenr_T)lnum_stop, &tm); if (subpatnum != FAIL) { if (flags & SP_SUBPAT) retval = subpatnum; else retval = pos.lnum; if (flags & SP_SETPCMARK) setpcmark(); curwin->w_cursor = pos; if (match_pos != NULL) { /* Store the match cursor position */ match_pos->lnum = pos.lnum; match_pos->col = pos.col + 1; } /* "/$" will put the cursor after the end of the line, may need to * correct that here */ check_cursor(); } /* If 'n' flag is used: restore cursor position. */ if (flags & SP_NOMOVE) curwin->w_cursor = save_cursor; else curwin->w_set_curswant = TRUE; theend: p_ws = save_p_ws; return retval; } #ifdef FEAT_FLOAT /* * "round({float})" function */ static void f_round(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) /* round() is not in C90, use ceil() or floor() instead. */ rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5); else rettv->vval.v_float = 0.0; } #endif /* * "search()" function */ static void f_search(argvars, rettv) typval_T *argvars; typval_T *rettv; { int flags = 0; rettv->vval.v_number = search_cmn(argvars, NULL, &flags); } /* * "searchdecl()" function */ static void f_searchdecl(argvars, rettv) typval_T *argvars; typval_T *rettv; { int locally = 1; int thisblock = 0; int error = FALSE; char_u *name; rettv->vval.v_number = 1; /* default: FAIL */ name = get_tv_string_chk(&argvars[0]); if (argvars[1].v_type != VAR_UNKNOWN) { locally = get_tv_number_chk(&argvars[1], &error) == 0; if (!error && argvars[2].v_type != VAR_UNKNOWN) thisblock = get_tv_number_chk(&argvars[2], &error) != 0; } if (!error && name != NULL) rettv->vval.v_number = find_decl(name, (int)STRLEN(name), locally, thisblock, SEARCH_KEEP) == FAIL; } /* * Used by searchpair() and searchpairpos() */ static int searchpair_cmn(argvars, match_pos) typval_T *argvars; pos_T *match_pos; { char_u *spat, *mpat, *epat; char_u *skip; int save_p_ws = p_ws; int dir; int flags = 0; char_u nbuf1[NUMBUFLEN]; char_u nbuf2[NUMBUFLEN]; char_u nbuf3[NUMBUFLEN]; int retval = 0; /* default: FAIL */ long lnum_stop = 0; long time_limit = 0; /* Get the three pattern arguments: start, middle, end. */ spat = get_tv_string_chk(&argvars[0]); mpat = get_tv_string_buf_chk(&argvars[1], nbuf1); epat = get_tv_string_buf_chk(&argvars[2], nbuf2); if (spat == NULL || mpat == NULL || epat == NULL) goto theend; /* type error */ /* Handle the optional fourth argument: flags */ dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */ if (dir == 0) goto theend; /* Don't accept SP_END or SP_SUBPAT. * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set. */ if ((flags & (SP_END | SP_SUBPAT)) != 0 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK))) { EMSG2(_(e_invarg2), get_tv_string(&argvars[3])); goto theend; } /* Using 'r' implies 'W', otherwise it doesn't work. */ if (flags & SP_REPEAT) p_ws = FALSE; /* Optional fifth argument: skip expression */ if (argvars[3].v_type == VAR_UNKNOWN || argvars[4].v_type == VAR_UNKNOWN) skip = (char_u *)""; else { skip = get_tv_string_buf_chk(&argvars[4], nbuf3); if (argvars[5].v_type != VAR_UNKNOWN) { lnum_stop = get_tv_number_chk(&argvars[5], NULL); if (lnum_stop < 0) goto theend; #ifdef FEAT_RELTIME if (argvars[6].v_type != VAR_UNKNOWN) { time_limit = get_tv_number_chk(&argvars[6], NULL); if (time_limit < 0) goto theend; } #endif } } if (skip == NULL) goto theend; /* type error */ retval = do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos, lnum_stop, time_limit); theend: p_ws = save_p_ws; return retval; } /* * "searchpair()" function */ static void f_searchpair(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = searchpair_cmn(argvars, NULL); } /* * "searchpairpos()" function */ static void f_searchpairpos(argvars, rettv) typval_T *argvars; typval_T *rettv; { pos_T match_pos; int lnum = 0; int col = 0; if (rettv_list_alloc(rettv) == FAIL) return; if (searchpair_cmn(argvars, &match_pos) > 0) { lnum = match_pos.lnum; col = match_pos.col; } list_append_number(rettv->vval.v_list, (varnumber_T)lnum); list_append_number(rettv->vval.v_list, (varnumber_T)col); } /* * Search for a start/middle/end thing. * Used by searchpair(), see its documentation for the details. * Returns 0 or -1 for no match, */ long do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos, lnum_stop, time_limit) char_u *spat; /* start pattern */ char_u *mpat; /* middle pattern */ char_u *epat; /* end pattern */ int dir; /* BACKWARD or FORWARD */ char_u *skip; /* skip expression */ int flags; /* SP_SETPCMARK and other SP_ values */ pos_T *match_pos; linenr_T lnum_stop; /* stop at this line if not zero */ long time_limit; /* stop after this many msec */ { char_u *save_cpo; char_u *pat, *pat2 = NULL, *pat3 = NULL; long retval = 0; pos_T pos; pos_T firstpos; pos_T foundpos; pos_T save_cursor; pos_T save_pos; int n; int r; int nest = 1; int err; int options = SEARCH_KEEP; proftime_T tm; /* Make 'cpoptions' empty, the 'l' flag should not be used here. */ save_cpo = p_cpo; p_cpo = empty_option; #ifdef FEAT_RELTIME /* Set the time limit, if there is one. */ profile_setlimit(time_limit, &tm); #endif /* Make two search patterns: start/end (pat2, for in nested pairs) and * start/middle/end (pat3, for the top pair). */ pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15)); pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23)); if (pat2 == NULL || pat3 == NULL) goto theend; sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat); if (*mpat == NUL) STRCPY(pat3, pat2); else sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat, mpat); if (flags & SP_START) options |= SEARCH_START; save_cursor = curwin->w_cursor; pos = curwin->w_cursor; clearpos(&firstpos); clearpos(&foundpos); pat = pat3; for (;;) { n = searchit(curwin, curbuf, &pos, dir, pat, 1L, options, RE_SEARCH, lnum_stop, &tm); if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos))) /* didn't find it or found the first match again: FAIL */ break; if (firstpos.lnum == 0) firstpos = pos; if (equalpos(pos, foundpos)) { /* Found the same position again. Can happen with a pattern that * has "\zs" at the end and searching backwards. Advance one * character and try again. */ if (dir == BACKWARD) decl(&pos); else incl(&pos); } foundpos = pos; /* clear the start flag to avoid getting stuck here */ options &= ~SEARCH_START; /* If the skip pattern matches, ignore this match. */ if (*skip != NUL) { save_pos = curwin->w_cursor; curwin->w_cursor = pos; r = eval_to_bool(skip, &err, NULL, FALSE); curwin->w_cursor = save_pos; if (err) { /* Evaluating {skip} caused an error, break here. */ curwin->w_cursor = save_cursor; retval = -1; break; } if (r) continue; } if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2)) { /* Found end when searching backwards or start when searching * forward: nested pair. */ ++nest; pat = pat2; /* nested, don't search for middle */ } else { /* Found end when searching forward or start when searching * backward: end of (nested) pair; or found middle in outer pair. */ if (--nest == 1) pat = pat3; /* outer level, search for middle */ } if (nest == 0) { /* Found the match: return matchcount or line number. */ if (flags & SP_RETCOUNT) ++retval; else retval = pos.lnum; if (flags & SP_SETPCMARK) setpcmark(); curwin->w_cursor = pos; if (!(flags & SP_REPEAT)) break; nest = 1; /* search for next unmatched */ } } if (match_pos != NULL) { /* Store the match cursor position */ match_pos->lnum = curwin->w_cursor.lnum; match_pos->col = curwin->w_cursor.col + 1; } /* If 'n' flag is used or search failed: restore cursor position. */ if ((flags & SP_NOMOVE) || retval == 0) curwin->w_cursor = save_cursor; theend: vim_free(pat2); vim_free(pat3); if (p_cpo == empty_option) p_cpo = save_cpo; else /* Darn, evaluating the {skip} expression changed the value. */ free_string_option(save_cpo); return retval; } /* * "searchpos()" function */ static void f_searchpos(argvars, rettv) typval_T *argvars; typval_T *rettv; { pos_T match_pos; int lnum = 0; int col = 0; int n; int flags = 0; if (rettv_list_alloc(rettv) == FAIL) return; n = search_cmn(argvars, &match_pos, &flags); if (n > 0) { lnum = match_pos.lnum; col = match_pos.col; } list_append_number(rettv->vval.v_list, (varnumber_T)lnum); list_append_number(rettv->vval.v_list, (varnumber_T)col); if (flags & SP_SUBPAT) list_append_number(rettv->vval.v_list, (varnumber_T)n); } static void f_server2client(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_CLIENTSERVER char_u buf[NUMBUFLEN]; char_u *server = get_tv_string_chk(&argvars[0]); char_u *reply = get_tv_string_buf_chk(&argvars[1], buf); rettv->vval.v_number = -1; if (server == NULL || reply == NULL) return; if (check_restricted() || check_secure()) return; # ifdef FEAT_X11 if (check_connection() == FAIL) return; # endif if (serverSendReply(server, reply) < 0) { EMSG(_("E258: Unable to send to client")); return; } rettv->vval.v_number = 0; #else rettv->vval.v_number = -1; #endif } static void f_serverlist(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { char_u *r = NULL; #ifdef FEAT_CLIENTSERVER # ifdef WIN32 r = serverGetVimNames(); # else make_connection(); if (X_DISPLAY != NULL) r = serverGetVimNames(X_DISPLAY); # endif #endif rettv->v_type = VAR_STRING; rettv->vval.v_string = r; } /* * "setbufvar()" function */ static void f_setbufvar(argvars, rettv) typval_T *argvars; typval_T *rettv UNUSED; { buf_T *buf; aco_save_T aco; char_u *varname, *bufvarname; typval_T *varp; char_u nbuf[NUMBUFLEN]; if (check_restricted() || check_secure()) return; (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */ varname = get_tv_string_chk(&argvars[1]); buf = get_buf_tv(&argvars[0]); varp = &argvars[2]; if (buf != NULL && varname != NULL && varp != NULL) { /* set curbuf to be our buf, temporarily */ aucmd_prepbuf(&aco, buf); if (*varname == '&') { long numval; char_u *strval; int error = FALSE; ++varname; numval = get_tv_number_chk(varp, &error); strval = get_tv_string_buf_chk(varp, nbuf); if (!error && strval != NULL) set_option_value(varname, numval, strval, OPT_LOCAL); } else { bufvarname = alloc((unsigned)STRLEN(varname) + 3); if (bufvarname != NULL) { STRCPY(bufvarname, "b:"); STRCPY(bufvarname + 2, varname); set_var(bufvarname, varp, TRUE); vim_free(bufvarname); } } /* reset notion of buffer */ aucmd_restbuf(&aco); } } /* * "setcmdpos()" function */ static void f_setcmdpos(argvars, rettv) typval_T *argvars; typval_T *rettv; { int pos = (int)get_tv_number(&argvars[0]) - 1; if (pos >= 0) rettv->vval.v_number = set_cmdline_pos(pos); } /* * "setline()" function */ static void f_setline(argvars, rettv) typval_T *argvars; typval_T *rettv; { linenr_T lnum; char_u *line = NULL; list_T *l = NULL; listitem_T *li = NULL; long added = 0; linenr_T lcount = curbuf->b_ml.ml_line_count; lnum = get_tv_lnum(&argvars[0]); if (argvars[1].v_type == VAR_LIST) { l = argvars[1].vval.v_list; li = l->lv_first; } else line = get_tv_string_chk(&argvars[1]); /* default result is zero == OK */ for (;;) { if (l != NULL) { /* list argument, get next string */ if (li == NULL) break; line = get_tv_string_chk(&li->li_tv); li = li->li_next; } rettv->vval.v_number = 1; /* FAIL */ if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1) break; if (lnum <= curbuf->b_ml.ml_line_count) { /* existing line, replace it */ if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK) { changed_bytes(lnum, 0); if (lnum == curwin->w_cursor.lnum) check_cursor_col(); rettv->vval.v_number = 0; /* OK */ } } else if (added > 0 || u_save(lnum - 1, lnum) == OK) { /* lnum is one past the last line, append the line */ ++added; if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK) rettv->vval.v_number = 0; /* OK */ } if (l == NULL) /* only one string argument */ break; ++lnum; } if (added > 0) appended_lines_mark(lcount, added); } static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv)); /* * Used by "setqflist()" and "setloclist()" functions */ static void set_qf_ll_list(wp, list_arg, action_arg, rettv) win_T *wp UNUSED; typval_T *list_arg UNUSED; typval_T *action_arg UNUSED; typval_T *rettv; { #ifdef FEAT_QUICKFIX char_u *act; int action = ' '; #endif rettv->vval.v_number = -1; #ifdef FEAT_QUICKFIX if (list_arg->v_type != VAR_LIST) EMSG(_(e_listreq)); else { list_T *l = list_arg->vval.v_list; if (action_arg->v_type == VAR_STRING) { act = get_tv_string_chk(action_arg); if (act == NULL) return; /* type error; errmsg already given */ if (*act == 'a' || *act == 'r') action = *act; } if (l != NULL && set_errorlist(wp, l, action, NULL) == OK) rettv->vval.v_number = 0; } #endif } /* * "setloclist()" function */ static void f_setloclist(argvars, rettv) typval_T *argvars; typval_T *rettv; { win_T *win; rettv->vval.v_number = -1; win = find_win_by_nr(&argvars[0], NULL); if (win != NULL) set_qf_ll_list(win, &argvars[1], &argvars[2], rettv); } /* * "setmatches()" function */ static void f_setmatches(argvars, rettv) typval_T *argvars; typval_T *rettv; { #ifdef FEAT_SEARCH_EXTRA list_T *l; listitem_T *li; dict_T *d; rettv->vval.v_number = -1; if (argvars[0].v_type != VAR_LIST) { EMSG(_(e_listreq)); return; } if ((l = argvars[0].vval.v_list) != NULL) { /* To some extent make sure that we are dealing with a list from * "getmatches()". */ li = l->lv_first; while (li != NULL) { if (li->li_tv.v_type != VAR_DICT || (d = li->li_tv.vval.v_dict) == NULL) { EMSG(_(e_invarg)); return; } if (!(dict_find(d, (char_u *)"group", -1) != NULL && dict_find(d, (char_u *)"pattern", -1) != NULL && dict_find(d, (char_u *)"priority", -1) != NULL && dict_find(d, (char_u *)"id", -1) != NULL)) { EMSG(_(e_invarg)); return; } li = li->li_next; } clear_matches(curwin); li = l->lv_first; while (li != NULL) { d = li->li_tv.vval.v_dict; match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE), get_dict_string(d, (char_u *)"pattern", FALSE), (int)get_dict_number(d, (char_u *)"priority"), (int)get_dict_number(d, (char_u *)"id")); li = li->li_next; } rettv->vval.v_number = 0; } #endif } /* * "setpos()" function */ static void f_setpos(argvars, rettv) typval_T *argvars; typval_T *rettv; { pos_T pos; int fnum; char_u *name; rettv->vval.v_number = -1; name = get_tv_string_chk(argvars); if (name != NULL) { if (list2fpos(&argvars[1], &pos, &fnum) == OK) { if (--pos.col < 0) pos.col = 0; if (name[0] == '.' && name[1] == NUL) { /* set cursor */ if (fnum == curbuf->b_fnum) { curwin->w_cursor = pos; check_cursor(); rettv->vval.v_number = 0; } else EMSG(_(e_invarg)); } else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL) { /* set mark */ if (setmark_pos(name[1], &pos, fnum) == OK) rettv->vval.v_number = 0; } else EMSG(_(e_invarg)); } } } /* * "setqflist()" function */ static void f_setqflist(argvars, rettv) typval_T *argvars; typval_T *rettv; { set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv); } /* * "setreg()" function */ static void f_setreg(argvars, rettv) typval_T *argvars; typval_T *rettv; { int regname; char_u *strregname; char_u *stropt; char_u *strval; int append; char_u yank_type; long block_len; block_len = -1; yank_type = MAUTO; append = FALSE; strregname = get_tv_string_chk(argvars); rettv->vval.v_number = 1; /* FAIL is default */ if (strregname == NULL) return; /* type error; errmsg already given */ regname = *strregname; if (regname == 0 || regname == '@') regname = '"'; else if (regname == '=') return; if (argvars[2].v_type != VAR_UNKNOWN) { stropt = get_tv_string_chk(&argvars[2]); if (stropt == NULL) return; /* type error */ for (; *stropt != NUL; ++stropt) switch (*stropt) { case 'a': case 'A': /* append */ append = TRUE; break; case 'v': case 'c': /* character-wise selection */ yank_type = MCHAR; break; case 'V': case 'l': /* line-wise selection */ yank_type = MLINE; break; #ifdef FEAT_VISUAL case 'b': case Ctrl_V: /* block-wise selection */ yank_type = MBLOCK; if (VIM_ISDIGIT(stropt[1])) { ++stropt; block_len = getdigits(&stropt) - 1; --stropt; } break; #endif } } strval = get_tv_string_chk(&argvars[1]); if (strval != NULL) write_reg_contents_ex(regname, strval, -1, append, yank_type, block_len); rettv->vval.v_number = 0; } /* * "settabvar()" function */ static void f_settabvar(argvars, rettv) typval_T *argvars; typval_T *rettv; { tabpage_T *save_curtab; char_u *varname, *tabvarname; typval_T *varp; tabpage_T *tp; rettv->vval.v_number = 0; if (check_restricted() || check_secure()) return; tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL)); varname = get_tv_string_chk(&argvars[1]); varp = &argvars[2]; if (tp != NULL && varname != NULL && varp != NULL) { save_curtab = curtab; goto_tabpage_tp(tp, TRUE); tabvarname = alloc((unsigned)STRLEN(varname) + 3); if (tabvarname != NULL) { STRCPY(tabvarname, "t:"); STRCPY(tabvarname + 2, varname); set_var(tabvarname, varp, TRUE); vim_free(tabvarname); } /* Restore current tabpage */ if (valid_tabpage(save_curtab)) goto_tabpage_tp(save_curtab, TRUE); } } /* * "settabwinvar()" function */ static void f_settabwinvar(argvars, rettv) typval_T *argvars; typval_T *rettv; { setwinvar(argvars, rettv, 1); } /* * "setwinvar()" function */ static void f_setwinvar(argvars, rettv) typval_T *argvars; typval_T *rettv; { setwinvar(argvars, rettv, 0); } /* * "setwinvar()" and "settabwinvar()" functions */ static void setwinvar(argvars, rettv, off) typval_T *argvars; typval_T *rettv UNUSED; int off; { win_T *win; #ifdef FEAT_WINDOWS win_T *save_curwin; tabpage_T *save_curtab; #endif char_u *varname, *winvarname; typval_T *varp; char_u nbuf[NUMBUFLEN]; tabpage_T *tp; if (check_restricted() || check_secure()) return; #ifdef FEAT_WINDOWS if (off == 1) tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL)); else tp = curtab; #endif win = find_win_by_nr(&argvars[off], tp); varname = get_tv_string_chk(&argvars[off + 1]); varp = &argvars[off + 2]; if (win != NULL && varname != NULL && varp != NULL) { #ifdef FEAT_WINDOWS /* set curwin to be our win, temporarily */ save_curwin = curwin; save_curtab = curtab; goto_tabpage_tp(tp, TRUE); if (!win_valid(win)) return; curwin = win; curbuf = curwin->w_buffer; #endif if (*varname == '&') { long numval; char_u *strval; int error = FALSE; ++varname; numval = get_tv_number_chk(varp, &error); strval = get_tv_string_buf_chk(varp, nbuf); if (!error && strval != NULL) set_option_value(varname, numval, strval, OPT_LOCAL); } else { winvarname = alloc((unsigned)STRLEN(varname) + 3); if (winvarname != NULL) { STRCPY(winvarname, "w:"); STRCPY(winvarname + 2, varname); set_var(winvarname, varp, TRUE); vim_free(winvarname); } } #ifdef FEAT_WINDOWS /* Restore current tabpage and window, if still valid (autocomands can * make them invalid). */ if (valid_tabpage(save_curtab)) goto_tabpage_tp(save_curtab, TRUE); if (win_valid(save_curwin)) { curwin = save_curwin; curbuf = curwin->w_buffer; } #endif } } /* * "shellescape({string})" function */ static void f_shellescape(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_string = vim_strsave_shellescape( get_tv_string(&argvars[0]), non_zero_arg(&argvars[1])); rettv->v_type = VAR_STRING; } /* * "simplify()" function */ static void f_simplify(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *p; p = get_tv_string(&argvars[0]); rettv->vval.v_string = vim_strsave(p); simplify_filename(rettv->vval.v_string); /* simplify in place */ rettv->v_type = VAR_STRING; } #ifdef FEAT_FLOAT /* * "sin()" function */ static void f_sin(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = sin(f); else rettv->vval.v_float = 0.0; } /* * "sinh()" function */ static void f_sinh(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = sinh(f); else rettv->vval.v_float = 0.0; } #endif static int #ifdef __BORLANDC__ _RTLENTRYF #endif item_compare __ARGS((const void *s1, const void *s2)); static int #ifdef __BORLANDC__ _RTLENTRYF #endif item_compare2 __ARGS((const void *s1, const void *s2)); static int item_compare_ic; static char_u *item_compare_func; static dict_T *item_compare_selfdict; static int item_compare_func_err; #define ITEM_COMPARE_FAIL 999 /* * Compare functions for f_sort() below. */ static int #ifdef __BORLANDC__ _RTLENTRYF #endif item_compare(s1, s2) const void *s1; const void *s2; { char_u *p1, *p2; char_u *tofree1, *tofree2; int res; char_u numbuf1[NUMBUFLEN]; char_u numbuf2[NUMBUFLEN]; p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0); p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0); if (p1 == NULL) p1 = (char_u *)""; if (p2 == NULL) p2 = (char_u *)""; if (item_compare_ic) res = STRICMP(p1, p2); else res = STRCMP(p1, p2); vim_free(tofree1); vim_free(tofree2); return res; } static int #ifdef __BORLANDC__ _RTLENTRYF #endif item_compare2(s1, s2) const void *s1; const void *s2; { int res; typval_T rettv; typval_T argv[3]; int dummy; /* shortcut after failure in previous call; compare all items equal */ if (item_compare_func_err) return 0; /* copy the values. This is needed to be able to set v_lock to VAR_FIXED * in the copy without changing the original list items. */ copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]); copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]); rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */ res = call_func(item_compare_func, (int)STRLEN(item_compare_func), &rettv, 2, argv, 0L, 0L, &dummy, TRUE, item_compare_selfdict); clear_tv(&argv[0]); clear_tv(&argv[1]); if (res == FAIL) res = ITEM_COMPARE_FAIL; else res = get_tv_number_chk(&rettv, &item_compare_func_err); if (item_compare_func_err) res = ITEM_COMPARE_FAIL; /* return value has wrong type */ clear_tv(&rettv); return res; } /* * "sort({list})" function */ static void f_sort(argvars, rettv) typval_T *argvars; typval_T *rettv; { list_T *l; listitem_T *li; listitem_T **ptrs; long len; long i; if (argvars[0].v_type != VAR_LIST) EMSG2(_(e_listarg), "sort()"); else { l = argvars[0].vval.v_list; if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)_("sort() argument"))) return; rettv->vval.v_list = l; rettv->v_type = VAR_LIST; ++l->lv_refcount; len = list_len(l); if (len <= 1) return; /* short list sorts pretty quickly */ item_compare_ic = FALSE; item_compare_func = NULL; item_compare_selfdict = NULL; if (argvars[1].v_type != VAR_UNKNOWN) { /* optional second argument: {func} */ if (argvars[1].v_type == VAR_FUNC) item_compare_func = argvars[1].vval.v_string; else { int error = FALSE; i = get_tv_number_chk(&argvars[1], &error); if (error) return; /* type error; errmsg already given */ if (i == 1) item_compare_ic = TRUE; else item_compare_func = get_tv_string(&argvars[1]); } if (argvars[2].v_type != VAR_UNKNOWN) { /* optional third argument: {dict} */ if (argvars[2].v_type != VAR_DICT) { EMSG(_(e_dictreq)); return; } item_compare_selfdict = argvars[2].vval.v_dict; } } /* Make an array with each entry pointing to an item in the List. */ ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *))); if (ptrs == NULL) return; i = 0; for (li = l->lv_first; li != NULL; li = li->li_next) ptrs[i++] = li; item_compare_func_err = FALSE; /* test the compare function */ if (item_compare_func != NULL && item_compare2((void *)&ptrs[0], (void *)&ptrs[1]) == ITEM_COMPARE_FAIL) EMSG(_("E702: Sort compare function failed")); else { /* Sort the array with item pointers. */ qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *), item_compare_func == NULL ? item_compare : item_compare2); if (!item_compare_func_err) { /* Clear the List and append the items in the sorted order. */ l->lv_first = l->lv_last = l->lv_idx_item = NULL; l->lv_len = 0; for (i = 0; i < len; ++i) list_append(l, ptrs[i]); } } vim_free(ptrs); } } /* * "soundfold({word})" function */ static void f_soundfold(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *s; rettv->v_type = VAR_STRING; s = get_tv_string(&argvars[0]); #ifdef FEAT_SPELL rettv->vval.v_string = eval_soundfold(s); #else rettv->vval.v_string = vim_strsave(s); #endif } /* * "spellbadword()" function */ static void f_spellbadword(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { char_u *word = (char_u *)""; hlf_T attr = HLF_COUNT; int len = 0; if (rettv_list_alloc(rettv) == FAIL) return; #ifdef FEAT_SPELL if (argvars[0].v_type == VAR_UNKNOWN) { /* Find the start and length of the badly spelled word. */ len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr); if (len != 0) word = ml_get_cursor(); } else if (curwin->w_p_spell && *curbuf->b_s.b_p_spl != NUL) { char_u *str = get_tv_string_chk(&argvars[0]); int capcol = -1; if (str != NULL) { /* Check the argument for spelling. */ while (*str != NUL) { len = spell_check(curwin, str, &attr, &capcol, FALSE); if (attr != HLF_COUNT) { word = str; break; } str += len; } } } #endif list_append_string(rettv->vval.v_list, word, len); list_append_string(rettv->vval.v_list, (char_u *)( attr == HLF_SPB ? "bad" : attr == HLF_SPR ? "rare" : attr == HLF_SPL ? "local" : attr == HLF_SPC ? "caps" : ""), -1); } /* * "spellsuggest()" function */ static void f_spellsuggest(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_SPELL char_u *str; int typeerr = FALSE; int maxcount; garray_T ga; int i; listitem_T *li; int need_capital = FALSE; #endif if (rettv_list_alloc(rettv) == FAIL) return; #ifdef FEAT_SPELL if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) { str = get_tv_string(&argvars[0]); if (argvars[1].v_type != VAR_UNKNOWN) { maxcount = get_tv_number_chk(&argvars[1], &typeerr); if (maxcount <= 0) return; if (argvars[2].v_type != VAR_UNKNOWN) { need_capital = get_tv_number_chk(&argvars[2], &typeerr); if (typeerr) return; } } else maxcount = 25; spell_suggest_list(&ga, str, maxcount, need_capital, FALSE); for (i = 0; i < ga.ga_len; ++i) { str = ((char_u **)ga.ga_data)[i]; li = listitem_alloc(); if (li == NULL) vim_free(str); else { li->li_tv.v_type = VAR_STRING; li->li_tv.v_lock = 0; li->li_tv.vval.v_string = str; list_append(rettv->vval.v_list, li); } } ga_clear(&ga); } #endif } static void f_split(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *str; char_u *end; char_u *pat = NULL; regmatch_T regmatch; char_u patbuf[NUMBUFLEN]; char_u *save_cpo; int match; colnr_T col = 0; int keepempty = FALSE; int typeerr = FALSE; /* Make 'cpoptions' empty, the 'l' flag should not be used here. */ save_cpo = p_cpo; p_cpo = (char_u *)""; str = get_tv_string(&argvars[0]); if (argvars[1].v_type != VAR_UNKNOWN) { pat = get_tv_string_buf_chk(&argvars[1], patbuf); if (pat == NULL) typeerr = TRUE; if (argvars[2].v_type != VAR_UNKNOWN) keepempty = get_tv_number_chk(&argvars[2], &typeerr); } if (pat == NULL || *pat == NUL) pat = (char_u *)"[\\x01- ]\\+"; if (rettv_list_alloc(rettv) == FAIL) return; if (typeerr) return; regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING); if (regmatch.regprog != NULL) { regmatch.rm_ic = FALSE; while (*str != NUL || keepempty) { if (*str == NUL) match = FALSE; /* empty item at the end */ else match = vim_regexec_nl(&regmatch, str, col); if (match) end = regmatch.startp[0]; else end = str + STRLEN(str); if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0 && *str != NUL && match && end < regmatch.endp[0])) { if (list_append_string(rettv->vval.v_list, str, (int)(end - str)) == FAIL) break; } if (!match) break; /* Advance to just after the match. */ if (regmatch.endp[0] > str) col = 0; else { /* Don't get stuck at the same match. */ #ifdef FEAT_MBYTE col = (*mb_ptr2len)(regmatch.endp[0]); #else col = 1; #endif } str = regmatch.endp[0]; } vim_free(regmatch.regprog); } p_cpo = save_cpo; } #ifdef FEAT_FLOAT /* * "sqrt()" function */ static void f_sqrt(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = sqrt(f); else rettv->vval.v_float = 0.0; } /* * "str2float()" function */ static void f_str2float(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *p = skipwhite(get_tv_string(&argvars[0])); if (*p == '+') p = skipwhite(p + 1); (void)string2float(p, &rettv->vval.v_float); rettv->v_type = VAR_FLOAT; } #endif /* * "str2nr()" function */ static void f_str2nr(argvars, rettv) typval_T *argvars; typval_T *rettv; { int base = 10; char_u *p; long n; if (argvars[1].v_type != VAR_UNKNOWN) { base = get_tv_number(&argvars[1]); if (base != 8 && base != 10 && base != 16) { EMSG(_(e_invarg)); return; } } p = skipwhite(get_tv_string(&argvars[0])); if (*p == '+') p = skipwhite(p + 1); vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL); rettv->vval.v_number = n; } #ifdef HAVE_STRFTIME /* * "strftime({format}[, {time}])" function */ static void f_strftime(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u result_buf[256]; struct tm *curtime; time_t seconds; char_u *p; rettv->v_type = VAR_STRING; p = get_tv_string(&argvars[0]); if (argvars[1].v_type == VAR_UNKNOWN) seconds = time(NULL); else seconds = (time_t)get_tv_number(&argvars[1]); curtime = localtime(&seconds); /* MSVC returns NULL for an invalid value of seconds. */ if (curtime == NULL) rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)")); else { # ifdef FEAT_MBYTE vimconv_T conv; char_u *enc; conv.vc_type = CONV_NONE; enc = enc_locale(); convert_setup(&conv, p_enc, enc); if (conv.vc_type != CONV_NONE) p = string_convert(&conv, p, NULL); # endif if (p != NULL) (void)strftime((char *)result_buf, sizeof(result_buf), (char *)p, curtime); else result_buf[0] = NUL; # ifdef FEAT_MBYTE if (conv.vc_type != CONV_NONE) vim_free(p); convert_setup(&conv, enc, p_enc); if (conv.vc_type != CONV_NONE) rettv->vval.v_string = string_convert(&conv, result_buf, NULL); else # endif rettv->vval.v_string = vim_strsave(result_buf); # ifdef FEAT_MBYTE /* Release conversion descriptors */ convert_setup(&conv, NULL, NULL); vim_free(enc); # endif } } #endif /* * "stridx()" function */ static void f_stridx(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u buf[NUMBUFLEN]; char_u *needle; char_u *haystack; char_u *save_haystack; char_u *pos; int start_idx; needle = get_tv_string_chk(&argvars[1]); save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf); rettv->vval.v_number = -1; if (needle == NULL || haystack == NULL) return; /* type error; errmsg already given */ if (argvars[2].v_type != VAR_UNKNOWN) { int error = FALSE; start_idx = get_tv_number_chk(&argvars[2], &error); if (error || start_idx >= (int)STRLEN(haystack)) return; if (start_idx >= 0) haystack += start_idx; } pos = (char_u *)strstr((char *)haystack, (char *)needle); if (pos != NULL) rettv->vval.v_number = (varnumber_T)(pos - save_haystack); } /* * "string()" function */ static void f_string(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *tofree; char_u numbuf[NUMBUFLEN]; rettv->v_type = VAR_STRING; rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0); /* Make a copy if we have a value but it's not in allocated memory. */ if (rettv->vval.v_string != NULL && tofree == NULL) rettv->vval.v_string = vim_strsave(rettv->vval.v_string); } /* * "strlen()" function */ static void f_strlen(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = (varnumber_T)(STRLEN( get_tv_string(&argvars[0]))); } /* * "strchars()" function */ static void f_strchars(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *s = get_tv_string(&argvars[0]); #ifdef FEAT_MBYTE varnumber_T len = 0; while (*s != NUL) { mb_cptr2char_adv(&s); ++len; } rettv->vval.v_number = len; #else rettv->vval.v_number = (varnumber_T)(STRLEN(s)); #endif } /* * "strdisplaywidth()" function */ static void f_strdisplaywidth(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *s = get_tv_string(&argvars[0]); int col = 0; if (argvars[1].v_type != VAR_UNKNOWN) col = get_tv_number(&argvars[1]); rettv->vval.v_number = (varnumber_T)(linetabsize_col(col, s) - col); } /* * "strwidth()" function */ static void f_strwidth(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *s = get_tv_string(&argvars[0]); rettv->vval.v_number = (varnumber_T)( #ifdef FEAT_MBYTE mb_string2cells(s, -1) #else STRLEN(s) #endif ); } /* * "strpart()" function */ static void f_strpart(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *p; int n; int len; int slen; int error = FALSE; p = get_tv_string(&argvars[0]); slen = (int)STRLEN(p); n = get_tv_number_chk(&argvars[1], &error); if (error) len = 0; else if (argvars[2].v_type != VAR_UNKNOWN) len = get_tv_number(&argvars[2]); else len = slen - n; /* default len: all bytes that are available. */ /* * Only return the overlap between the specified part and the actual * string. */ if (n < 0) { len += n; n = 0; } else if (n > slen) n = slen; if (len < 0) len = 0; else if (n + len > slen) len = slen - n; rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_strnsave(p + n, len); } /* * "strridx()" function */ static void f_strridx(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u buf[NUMBUFLEN]; char_u *needle; char_u *haystack; char_u *rest; char_u *lastmatch = NULL; int haystack_len, end_idx; needle = get_tv_string_chk(&argvars[1]); haystack = get_tv_string_buf_chk(&argvars[0], buf); rettv->vval.v_number = -1; if (needle == NULL || haystack == NULL) return; /* type error; errmsg already given */ haystack_len = (int)STRLEN(haystack); if (argvars[2].v_type != VAR_UNKNOWN) { /* Third argument: upper limit for index */ end_idx = get_tv_number_chk(&argvars[2], NULL); if (end_idx < 0) return; /* can never find a match */ } else end_idx = haystack_len; if (*needle == NUL) { /* Empty string matches past the end. */ lastmatch = haystack + end_idx; } else { for (rest = haystack; *rest != '\0'; ++rest) { rest = (char_u *)strstr((char *)rest, (char *)needle); if (rest == NULL || rest > haystack + end_idx) break; lastmatch = rest; } } if (lastmatch == NULL) rettv->vval.v_number = -1; else rettv->vval.v_number = (varnumber_T)(lastmatch - haystack); } /* * "strtrans()" function */ static void f_strtrans(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->v_type = VAR_STRING; rettv->vval.v_string = transstr(get_tv_string(&argvars[0])); } /* * "submatch()" function */ static void f_submatch(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->v_type = VAR_STRING; rettv->vval.v_string = reg_submatch((int)get_tv_number_chk(&argvars[0], NULL)); } /* * "substitute()" function */ static void f_substitute(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u patbuf[NUMBUFLEN]; char_u subbuf[NUMBUFLEN]; char_u flagsbuf[NUMBUFLEN]; char_u *str = get_tv_string_chk(&argvars[0]); char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf); char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf); char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf); rettv->v_type = VAR_STRING; if (str == NULL || pat == NULL || sub == NULL || flg == NULL) rettv->vval.v_string = NULL; else rettv->vval.v_string = do_string_sub(str, pat, sub, flg); } /* * "synID(lnum, col, trans)" function */ static void f_synID(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { int id = 0; #ifdef FEAT_SYN_HL long lnum; long col; int trans; int transerr = FALSE; lnum = get_tv_lnum(argvars); /* -1 on type error */ col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */ trans = get_tv_number_chk(&argvars[2], &transerr); if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count && col >= 0 && col < (long)STRLEN(ml_get(lnum))) id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE); #endif rettv->vval.v_number = id; } /* * "synIDattr(id, what [, mode])" function */ static void f_synIDattr(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { char_u *p = NULL; #ifdef FEAT_SYN_HL int id; char_u *what; char_u *mode; char_u modebuf[NUMBUFLEN]; int modec; id = get_tv_number(&argvars[0]); what = get_tv_string(&argvars[1]); if (argvars[2].v_type != VAR_UNKNOWN) { mode = get_tv_string_buf(&argvars[2], modebuf); modec = TOLOWER_ASC(mode[0]); if (modec != 't' && modec != 'c' && modec != 'g') modec = 0; /* replace invalid with current */ } else { #ifdef FEAT_GUI if (gui.in_use) modec = 'g'; else #endif if (t_colors > 1) modec = 'c'; else modec = 't'; } switch (TOLOWER_ASC(what[0])) { case 'b': if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */ p = highlight_color(id, what, modec); else /* bold */ p = highlight_has_attr(id, HL_BOLD, modec); break; case 'f': /* fg[#] or font */ p = highlight_color(id, what, modec); break; case 'i': if (TOLOWER_ASC(what[1]) == 'n') /* inverse */ p = highlight_has_attr(id, HL_INVERSE, modec); else /* italic */ p = highlight_has_attr(id, HL_ITALIC, modec); break; case 'n': /* name */ p = get_highlight_name(NULL, id - 1); break; case 'r': /* reverse */ p = highlight_has_attr(id, HL_INVERSE, modec); break; case 's': if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */ p = highlight_color(id, what, modec); else /* standout */ p = highlight_has_attr(id, HL_STANDOUT, modec); break; case 'u': if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c') /* underline */ p = highlight_has_attr(id, HL_UNDERLINE, modec); else /* undercurl */ p = highlight_has_attr(id, HL_UNDERCURL, modec); break; } if (p != NULL) p = vim_strsave(p); #endif rettv->v_type = VAR_STRING; rettv->vval.v_string = p; } /* * "synIDtrans(id)" function */ static void f_synIDtrans(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { int id; #ifdef FEAT_SYN_HL id = get_tv_number(&argvars[0]); if (id > 0) id = syn_get_final_id(id); else #endif id = 0; rettv->vval.v_number = id; } /* * "synconcealed(lnum, col)" function */ static void f_synconcealed(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #if defined(FEAT_SYN_HL) && defined(FEAT_CONCEAL) long lnum; long col; int syntax_flags = 0; int cchar; int matchid = 0; char_u str[NUMBUFLEN]; #endif rettv->v_type = VAR_LIST; rettv->vval.v_list = NULL; #if defined(FEAT_SYN_HL) && defined(FEAT_CONCEAL) lnum = get_tv_lnum(argvars); /* -1 on type error */ col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */ vim_memset(str, NUL, sizeof(str)); if (rettv_list_alloc(rettv) != FAIL) { if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count && col >= 0 && col <= (long)STRLEN(ml_get(lnum)) && curwin->w_p_cole > 0) { (void)syn_get_id(curwin, lnum, col, FALSE, NULL, FALSE); syntax_flags = get_syntax_info(&matchid); /* get the conceal character */ if ((syntax_flags & HL_CONCEAL) && curwin->w_p_cole < 3) { cchar = syn_get_sub_char(); if (cchar == NUL && curwin->w_p_cole == 1 && lcs_conceal != NUL) cchar = lcs_conceal; if (cchar != NUL) { # ifdef FEAT_MBYTE if (has_mbyte) (*mb_char2bytes)(cchar, str); else # endif str[0] = cchar; } } } list_append_number(rettv->vval.v_list, (syntax_flags & HL_CONCEAL) != 0); /* -1 to auto-determine strlen */ list_append_string(rettv->vval.v_list, str, -1); list_append_number(rettv->vval.v_list, matchid); } #endif } /* * "synstack(lnum, col)" function */ static void f_synstack(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_SYN_HL long lnum; long col; int i; int id; #endif rettv->v_type = VAR_LIST; rettv->vval.v_list = NULL; #ifdef FEAT_SYN_HL lnum = get_tv_lnum(argvars); /* -1 on type error */ col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */ if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count && col >= 0 && col <= (long)STRLEN(ml_get(lnum)) && rettv_list_alloc(rettv) != FAIL) { (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE); for (i = 0; ; ++i) { id = syn_get_stack_item(i); if (id < 0) break; if (list_append_number(rettv->vval.v_list, id) == FAIL) break; } } #endif } /* * "system()" function */ static void f_system(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *res = NULL; char_u *p; char_u *infile = NULL; char_u buf[NUMBUFLEN]; int err = FALSE; FILE *fd; if (check_restricted() || check_secure()) goto done; if (argvars[1].v_type != VAR_UNKNOWN) { /* * Write the string to a temp file, to be used for input of the shell * command. */ if ((infile = vim_tempname('i')) == NULL) { EMSG(_(e_notmp)); goto done; } fd = mch_fopen((char *)infile, WRITEBIN); if (fd == NULL) { EMSG2(_(e_notopen), infile); goto done; } p = get_tv_string_buf_chk(&argvars[1], buf); if (p == NULL) { fclose(fd); goto done; /* type error; errmsg already given */ } if (fwrite(p, STRLEN(p), 1, fd) != 1) err = TRUE; if (fclose(fd) != 0) err = TRUE; if (err) { EMSG(_("E677: Error writing temp file")); goto done; } } res = get_cmd_output(get_tv_string(&argvars[0]), infile, SHELL_SILENT | SHELL_COOKED); #ifdef USE_CR /* translate <CR> into <NL> */ if (res != NULL) { char_u *s; for (s = res; *s; ++s) { if (*s == CAR) *s = NL; } } #else # ifdef USE_CRNL /* translate <CR><NL> into <NL> */ if (res != NULL) { char_u *s, *d; d = res; for (s = res; *s; ++s) { if (s[0] == CAR && s[1] == NL) ++s; *d++ = *s; } *d = NUL; } # endif #endif done: if (infile != NULL) { mch_remove(infile); vim_free(infile); } rettv->v_type = VAR_STRING; rettv->vval.v_string = res; } /* * "tabpagebuflist()" function */ static void f_tabpagebuflist(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_WINDOWS tabpage_T *tp; win_T *wp = NULL; if (argvars[0].v_type == VAR_UNKNOWN) wp = firstwin; else { tp = find_tabpage((int)get_tv_number(&argvars[0])); if (tp != NULL) wp = (tp == curtab) ? firstwin : tp->tp_firstwin; } if (wp != NULL && rettv_list_alloc(rettv) != FAIL) { for (; wp != NULL; wp = wp->w_next) if (list_append_number(rettv->vval.v_list, wp->w_buffer->b_fnum) == FAIL) break; } #endif } /* * "tabpagenr()" function */ static void f_tabpagenr(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { int nr = 1; #ifdef FEAT_WINDOWS char_u *arg; if (argvars[0].v_type != VAR_UNKNOWN) { arg = get_tv_string_chk(&argvars[0]); nr = 0; if (arg != NULL) { if (STRCMP(arg, "$") == 0) nr = tabpage_index(NULL) - 1; else EMSG2(_(e_invexpr2), arg); } } else nr = tabpage_index(curtab); #endif rettv->vval.v_number = nr; } #ifdef FEAT_WINDOWS static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar)); /* * Common code for tabpagewinnr() and winnr(). */ static int get_winnr(tp, argvar) tabpage_T *tp; typval_T *argvar; { win_T *twin; int nr = 1; win_T *wp; char_u *arg; twin = (tp == curtab) ? curwin : tp->tp_curwin; if (argvar->v_type != VAR_UNKNOWN) { arg = get_tv_string_chk(argvar); if (arg == NULL) nr = 0; /* type error; errmsg already given */ else if (STRCMP(arg, "$") == 0) twin = (tp == curtab) ? lastwin : tp->tp_lastwin; else if (STRCMP(arg, "#") == 0) { twin = (tp == curtab) ? prevwin : tp->tp_prevwin; if (twin == NULL) nr = 0; } else { EMSG2(_(e_invexpr2), arg); nr = 0; } } if (nr > 0) for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin; wp != twin; wp = wp->w_next) { if (wp == NULL) { /* didn't find it in this tabpage */ nr = 0; break; } ++nr; } return nr; } #endif /* * "tabpagewinnr()" function */ static void f_tabpagewinnr(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { int nr = 1; #ifdef FEAT_WINDOWS tabpage_T *tp; tp = find_tabpage((int)get_tv_number(&argvars[0])); if (tp == NULL) nr = 0; else nr = get_winnr(tp, &argvars[1]); #endif rettv->vval.v_number = nr; } /* * "tagfiles()" function */ static void f_tagfiles(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { char_u *fname; tagname_T tn; int first; if (rettv_list_alloc(rettv) == FAIL) return; fname = alloc(MAXPATHL); if (fname == NULL) return; for (first = TRUE; ; first = FALSE) if (get_tagfname(&tn, first, fname) == FAIL || list_append_string(rettv->vval.v_list, fname, -1) == FAIL) break; tagname_free(&tn); vim_free(fname); } /* * "taglist()" function */ static void f_taglist(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *tag_pattern; tag_pattern = get_tv_string(&argvars[0]); rettv->vval.v_number = FALSE; if (*tag_pattern == NUL) return; if (rettv_list_alloc(rettv) == OK) (void)get_tags(rettv->vval.v_list, tag_pattern); } /* * "tempname()" function */ static void f_tempname(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { static int x = 'A'; rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_tempname(x); /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different * names. Skip 'I' and 'O', they are used for shell redirection. */ do { if (x == 'Z') x = '0'; else if (x == '9') x = 'A'; else { #ifdef EBCDIC if (x == 'I') x = 'J'; else if (x == 'R') x = 'S'; else #endif ++x; } } while (x == 'I' || x == 'O'); } /* * "test(list)" function: Just checking the walls... */ static void f_test(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { /* Used for unit testing. Change the code below to your liking. */ #if 0 listitem_T *li; list_T *l; char_u *bad, *good; if (argvars[0].v_type != VAR_LIST) return; l = argvars[0].vval.v_list; if (l == NULL) return; li = l->lv_first; if (li == NULL) return; bad = get_tv_string(&li->li_tv); li = li->li_next; if (li == NULL) return; good = get_tv_string(&li->li_tv); rettv->vval.v_number = test_edit_score(bad, good); #endif } #ifdef FEAT_FLOAT /* * "tan()" function */ static void f_tan(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = tan(f); else rettv->vval.v_float = 0.0; } /* * "tanh()" function */ static void f_tanh(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) rettv->vval.v_float = tanh(f); else rettv->vval.v_float = 0.0; } #endif /* * "tolower(string)" function */ static void f_tolower(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *p; p = vim_strsave(get_tv_string(&argvars[0])); rettv->v_type = VAR_STRING; rettv->vval.v_string = p; if (p != NULL) while (*p != NUL) { #ifdef FEAT_MBYTE int l; if (enc_utf8) { int c, lc; c = utf_ptr2char(p); lc = utf_tolower(c); l = utf_ptr2len(p); /* TODO: reallocate string when byte count changes. */ if (utf_char2len(lc) == l) utf_char2bytes(lc, p); p += l; } else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1) p += l; /* skip multi-byte character */ else #endif { *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */ ++p; } } } /* * "toupper(string)" function */ static void f_toupper(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->v_type = VAR_STRING; rettv->vval.v_string = strup_save(get_tv_string(&argvars[0])); } /* * "tr(string, fromstr, tostr)" function */ static void f_tr(argvars, rettv) typval_T *argvars; typval_T *rettv; { char_u *in_str; char_u *fromstr; char_u *tostr; char_u *p; #ifdef FEAT_MBYTE int inlen; int fromlen; int tolen; int idx; char_u *cpstr; int cplen; int first = TRUE; #endif char_u buf[NUMBUFLEN]; char_u buf2[NUMBUFLEN]; garray_T ga; in_str = get_tv_string(&argvars[0]); fromstr = get_tv_string_buf_chk(&argvars[1], buf); tostr = get_tv_string_buf_chk(&argvars[2], buf2); /* Default return value: empty string. */ rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; if (fromstr == NULL || tostr == NULL) return; /* type error; errmsg already given */ ga_init2(&ga, (int)sizeof(char), 80); #ifdef FEAT_MBYTE if (!has_mbyte) #endif /* not multi-byte: fromstr and tostr must be the same length */ if (STRLEN(fromstr) != STRLEN(tostr)) { #ifdef FEAT_MBYTE error: #endif EMSG2(_(e_invarg2), fromstr); ga_clear(&ga); return; } /* fromstr and tostr have to contain the same number of chars */ while (*in_str != NUL) { #ifdef FEAT_MBYTE if (has_mbyte) { inlen = (*mb_ptr2len)(in_str); cpstr = in_str; cplen = inlen; idx = 0; for (p = fromstr; *p != NUL; p += fromlen) { fromlen = (*mb_ptr2len)(p); if (fromlen == inlen && STRNCMP(in_str, p, inlen) == 0) { for (p = tostr; *p != NUL; p += tolen) { tolen = (*mb_ptr2len)(p); if (idx-- == 0) { cplen = tolen; cpstr = p; break; } } if (*p == NUL) /* tostr is shorter than fromstr */ goto error; break; } ++idx; } if (first && cpstr == in_str) { /* Check that fromstr and tostr have the same number of * (multi-byte) characters. Done only once when a character * of in_str doesn't appear in fromstr. */ first = FALSE; for (p = tostr; *p != NUL; p += tolen) { tolen = (*mb_ptr2len)(p); --idx; } if (idx != 0) goto error; } ga_grow(&ga, cplen); mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen); ga.ga_len += cplen; in_str += inlen; } else #endif { /* When not using multi-byte chars we can do it faster. */ p = vim_strchr(fromstr, *in_str); if (p != NULL) ga_append(&ga, tostr[p - fromstr]); else ga_append(&ga, *in_str); ++in_str; } } /* add a terminating NUL */ ga_grow(&ga, 1); ga_append(&ga, NUL); rettv->vval.v_string = ga.ga_data; } #ifdef FEAT_FLOAT /* * "trunc({float})" function */ static void f_trunc(argvars, rettv) typval_T *argvars; typval_T *rettv; { float_T f; rettv->v_type = VAR_FLOAT; if (get_float_arg(argvars, &f) == OK) /* trunc() is not in C90, use floor() or ceil() instead. */ rettv->vval.v_float = f > 0 ? floor(f) : ceil(f); else rettv->vval.v_float = 0.0; } #endif /* * "type(expr)" function */ static void f_type(argvars, rettv) typval_T *argvars; typval_T *rettv; { int n; switch (argvars[0].v_type) { case VAR_NUMBER: n = 0; break; case VAR_STRING: n = 1; break; case VAR_FUNC: n = 2; break; case VAR_LIST: n = 3; break; case VAR_DICT: n = 4; break; #ifdef FEAT_FLOAT case VAR_FLOAT: n = 5; break; #endif default: EMSG2(_(e_intern2), "f_type()"); n = 0; break; } rettv->vval.v_number = n; } /* * "undofile(name)" function */ static void f_undofile(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->v_type = VAR_STRING; #ifdef FEAT_PERSISTENT_UNDO { char_u *fname = get_tv_string(&argvars[0]); if (*fname == NUL) { /* If there is no file name there will be no undo file. */ rettv->vval.v_string = NULL; } else { char_u *ffname = FullName_save(fname, FALSE); if (ffname != NULL) rettv->vval.v_string = u_get_undo_file_name(ffname, FALSE); vim_free(ffname); } } #else rettv->vval.v_string = NULL; #endif } /* * "undotree()" function */ static void f_undotree(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { if (rettv_dict_alloc(rettv) == OK) { dict_T *dict = rettv->vval.v_dict; list_T *list; dict_add_nr_str(dict, "synced", (long)curbuf->b_u_synced, NULL); dict_add_nr_str(dict, "seq_last", curbuf->b_u_seq_last, NULL); dict_add_nr_str(dict, "save_last", (long)curbuf->b_u_save_nr_last, NULL); dict_add_nr_str(dict, "seq_cur", curbuf->b_u_seq_cur, NULL); dict_add_nr_str(dict, "time_cur", (long)curbuf->b_u_time_cur, NULL); dict_add_nr_str(dict, "save_cur", (long)curbuf->b_u_save_nr_cur, NULL); list = list_alloc(); if (list != NULL) { u_eval_tree(curbuf->b_u_oldhead, list); dict_add_list(dict, "entries", list); } } } /* * "values(dict)" function */ static void f_values(argvars, rettv) typval_T *argvars; typval_T *rettv; { dict_list(argvars, rettv, 1); } /* * "virtcol(string)" function */ static void f_virtcol(argvars, rettv) typval_T *argvars; typval_T *rettv; { colnr_T vcol = 0; pos_T *fp; int fnum = curbuf->b_fnum; fp = var2fpos(&argvars[0], FALSE, &fnum); if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count && fnum == curbuf->b_fnum) { getvvcol(curwin, fp, NULL, NULL, &vcol); ++vcol; } rettv->vval.v_number = vcol; } /* * "visualmode()" function */ static void f_visualmode(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv UNUSED; { #ifdef FEAT_VISUAL char_u str[2]; rettv->v_type = VAR_STRING; str[0] = curbuf->b_visual_mode_eval; str[1] = NUL; rettv->vval.v_string = vim_strsave(str); /* A non-zero number or non-empty string argument: reset mode. */ if (non_zero_arg(&argvars[0])) curbuf->b_visual_mode_eval = NUL; #endif } /* * "winbufnr(nr)" function */ static void f_winbufnr(argvars, rettv) typval_T *argvars; typval_T *rettv; { win_T *wp; wp = find_win_by_nr(&argvars[0], NULL); if (wp == NULL) rettv->vval.v_number = -1; else rettv->vval.v_number = wp->w_buffer->b_fnum; } /* * "wincol()" function */ static void f_wincol(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { validate_cursor(); rettv->vval.v_number = curwin->w_wcol + 1; } /* * "winheight(nr)" function */ static void f_winheight(argvars, rettv) typval_T *argvars; typval_T *rettv; { win_T *wp; wp = find_win_by_nr(&argvars[0], NULL); if (wp == NULL) rettv->vval.v_number = -1; else rettv->vval.v_number = wp->w_height; } /* * "winline()" function */ static void f_winline(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { validate_cursor(); rettv->vval.v_number = curwin->w_wrow + 1; } /* * "winnr()" function */ static void f_winnr(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { int nr = 1; #ifdef FEAT_WINDOWS nr = get_winnr(curtab, &argvars[0]); #endif rettv->vval.v_number = nr; } /* * "winrestcmd()" function */ static void f_winrestcmd(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { #ifdef FEAT_WINDOWS win_T *wp; int winnr = 1; garray_T ga; char_u buf[50]; ga_init2(&ga, (int)sizeof(char), 70); for (wp = firstwin; wp != NULL; wp = wp->w_next) { sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height); ga_concat(&ga, buf); # ifdef FEAT_VERTSPLIT sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width); ga_concat(&ga, buf); # endif ++winnr; } ga_append(&ga, NUL); rettv->vval.v_string = ga.ga_data; #else rettv->vval.v_string = NULL; #endif rettv->v_type = VAR_STRING; } /* * "winrestview()" function */ static void f_winrestview(argvars, rettv) typval_T *argvars; typval_T *rettv UNUSED; { dict_T *dict; if (argvars[0].v_type != VAR_DICT || (dict = argvars[0].vval.v_dict) == NULL) EMSG(_(e_invarg)); else { curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum"); curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col"); #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd"); #endif curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant"); curwin->w_set_curswant = FALSE; set_topline(curwin, get_dict_number(dict, (char_u *)"topline")); #ifdef FEAT_DIFF curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill"); #endif curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol"); curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol"); check_cursor(); changed_window_setting(); if (curwin->w_topline == 0) curwin->w_topline = 1; if (curwin->w_topline > curbuf->b_ml.ml_line_count) curwin->w_topline = curbuf->b_ml.ml_line_count; #ifdef FEAT_DIFF check_topfill(curwin, TRUE); #endif } } /* * "winsaveview()" function */ static void f_winsaveview(argvars, rettv) typval_T *argvars UNUSED; typval_T *rettv; { dict_T *dict; if (rettv_dict_alloc(rettv) == FAIL) return; dict = rettv->vval.v_dict; dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL); dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL); #ifdef FEAT_VIRTUALEDIT dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL); #endif update_curswant(); dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL); dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL); #ifdef FEAT_DIFF dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL); #endif dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL); dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL); } /* * "winwidth(nr)" function */ static void f_winwidth(argvars, rettv) typval_T *argvars; typval_T *rettv; { win_T *wp; wp = find_win_by_nr(&argvars[0], NULL); if (wp == NULL) rettv->vval.v_number = -1; else #ifdef FEAT_VERTSPLIT rettv->vval.v_number = wp->w_width; #else rettv->vval.v_number = Columns; #endif } /* * "writefile()" function */ static void f_writefile(argvars, rettv) typval_T *argvars; typval_T *rettv; { int binary = FALSE; char_u *fname; FILE *fd; listitem_T *li; char_u *s; int ret = 0; int c; if (check_restricted() || check_secure()) return; if (argvars[0].v_type != VAR_LIST) { EMSG2(_(e_listarg), "writefile()"); return; } if (argvars[0].vval.v_list == NULL) return; if (argvars[2].v_type != VAR_UNKNOWN && STRCMP(get_tv_string(&argvars[2]), "b") == 0) binary = TRUE; /* Always open the file in binary mode, library functions have a mind of * their own about CR-LF conversion. */ fname = get_tv_string(&argvars[1]); if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL) { EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname); ret = -1; } else { for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next) { for (s = get_tv_string(&li->li_tv); *s != NUL; ++s) { if (*s == '\n') c = putc(NUL, fd); else c = putc(*s, fd); if (c == EOF) { ret = -1; break; } } if (!binary || li->li_next != NULL) if (putc('\n', fd) == EOF) { ret = -1; break; } if (ret < 0) { EMSG(_(e_write)); break; } } fclose(fd); } rettv->vval.v_number = ret; } /* * "xor(expr, expr)" function */ static void f_xor(argvars, rettv) typval_T *argvars; typval_T *rettv; { rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL) ^ get_tv_number_chk(&argvars[1], NULL); } /* * Translate a String variable into a position. * Returns NULL when there is an error. */ static pos_T * var2fpos(varp, dollar_lnum, fnum) typval_T *varp; int dollar_lnum; /* TRUE when $ is last line */ int *fnum; /* set to fnum for '0, 'A, etc. */ { char_u *name; static pos_T pos; pos_T *pp; /* Argument can be [lnum, col, coladd]. */ if (varp->v_type == VAR_LIST) { list_T *l; int len; int error = FALSE; listitem_T *li; l = varp->vval.v_list; if (l == NULL) return NULL; /* Get the line number */ pos.lnum = list_find_nr(l, 0L, &error); if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count) return NULL; /* invalid line number */ /* Get the column number */ pos.col = list_find_nr(l, 1L, &error); if (error) return NULL; len = (long)STRLEN(ml_get(pos.lnum)); /* We accept "$" for the column number: last column. */ li = list_find(l, 1L); if (li != NULL && li->li_tv.v_type == VAR_STRING && li->li_tv.vval.v_string != NULL && STRCMP(li->li_tv.vval.v_string, "$") == 0) pos.col = len + 1; /* Accept a position up to the NUL after the line. */ if (pos.col == 0 || (int)pos.col > len + 1) return NULL; /* invalid column number */ --pos.col; #ifdef FEAT_VIRTUALEDIT /* Get the virtual offset. Defaults to zero. */ pos.coladd = list_find_nr(l, 2L, &error); if (error) pos.coladd = 0; #endif return &pos; } name = get_tv_string_chk(varp); if (name == NULL) return NULL; if (name[0] == '.') /* cursor */ return &curwin->w_cursor; #ifdef FEAT_VISUAL if (name[0] == 'v' && name[1] == NUL) /* Visual start */ { if (VIsual_active) return &VIsual; return &curwin->w_cursor; } #endif if (name[0] == '\'') /* mark */ { pp = getmark_fnum(name[1], FALSE, fnum); if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0) return NULL; return pp; } #ifdef FEAT_VIRTUALEDIT pos.coladd = 0; #endif if (name[0] == 'w' && dollar_lnum) { pos.col = 0; if (name[1] == '0') /* "w0": first visible line */ { update_topline(); pos.lnum = curwin->w_topline; return &pos; } else if (name[1] == '$') /* "w$": last visible line */ { validate_botline(); pos.lnum = curwin->w_botline - 1; return &pos; } } else if (name[0] == '$') /* last column or line */ { if (dollar_lnum) { pos.lnum = curbuf->b_ml.ml_line_count; pos.col = 0; } else { pos.lnum = curwin->w_cursor.lnum; pos.col = (colnr_T)STRLEN(ml_get_curline()); } return &pos; } return NULL; } /* * Convert list in "arg" into a position and optional file number. * When "fnump" is NULL there is no file number, only 3 items. * Note that the column is passed on as-is, the caller may want to decrement * it to use 1 for the first column. * Return FAIL when conversion is not possible, doesn't check the position for * validity. */ static int list2fpos(arg, posp, fnump) typval_T *arg; pos_T *posp; int *fnump; { list_T *l = arg->vval.v_list; long i = 0; long n; /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there * when "fnump" isn't NULL and "coladd" is optional. */ if (arg->v_type != VAR_LIST || l == NULL || l->lv_len < (fnump == NULL ? 2 : 3) || l->lv_len > (fnump == NULL ? 3 : 4)) return FAIL; if (fnump != NULL) { n = list_find_nr(l, i++, NULL); /* fnum */ if (n < 0) return FAIL; if (n == 0) n = curbuf->b_fnum; /* current buffer */ *fnump = n; } n = list_find_nr(l, i++, NULL); /* lnum */ if (n < 0) return FAIL; posp->lnum = n; n = list_find_nr(l, i++, NULL); /* col */ if (n < 0) return FAIL; posp->col = n; #ifdef FEAT_VIRTUALEDIT n = list_find_nr(l, i, NULL); if (n < 0) posp->coladd = 0; else posp->coladd = n; #endif return OK; } /* * Get the length of an environment variable name. * Advance "arg" to the first character after the name. * Return 0 for error. */ static int get_env_len(arg) char_u **arg; { char_u *p; int len; for (p = *arg; vim_isIDc(*p); ++p) ; if (p == *arg) /* no name found */ return 0; len = (int)(p - *arg); *arg = p; return len; } /* * Get the length of the name of a function or internal variable. * "arg" is advanced to the first non-white character after the name. * Return 0 if something is wrong. */ static int get_id_len(arg) char_u **arg; { char_u *p; int len; /* Find the end of the name. */ for (p = *arg; eval_isnamec(*p); ++p) ; if (p == *arg) /* no name found */ return 0; len = (int)(p - *arg); *arg = skipwhite(p); return len; } /* * Get the length of the name of a variable or function. * Only the name is recognized, does not handle ".key" or "[idx]". * "arg" is advanced to the first non-white character after the name. * Return -1 if curly braces expansion failed. * Return 0 if something else is wrong. * If the name contains 'magic' {}'s, expand them and return the * expanded name in an allocated string via 'alias' - caller must free. */ static int get_name_len(arg, alias, evaluate, verbose) char_u **arg; char_u **alias; int evaluate; int verbose; { int len; char_u *p; char_u *expr_start; char_u *expr_end; *alias = NULL; /* default to no alias */ if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA && (*arg)[2] == (int)KE_SNR) { /* hard coded <SNR>, already translated */ *arg += 3; return get_id_len(arg) + 3; } len = eval_fname_script(*arg); if (len > 0) { /* literal "<SID>", "s:" or "<SNR>" */ *arg += len; } /* * Find the end of the name; check for {} construction. */ p = find_name_end(*arg, &expr_start, &expr_end, len > 0 ? 0 : FNE_CHECK_START); if (expr_start != NULL) { char_u *temp_string; if (!evaluate) { len += (int)(p - *arg); *arg = skipwhite(p); return len; } /* * Include any <SID> etc in the expanded string: * Thus the -len here. */ temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p); if (temp_string == NULL) return -1; *alias = temp_string; *arg = skipwhite(p); return (int)STRLEN(temp_string); } len += get_id_len(arg); if (len == 0 && verbose) EMSG2(_(e_invexpr2), *arg); return len; } /* * Find the end of a variable or function name, taking care of magic braces. * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the * start and end of the first magic braces item. * "flags" can have FNE_INCL_BR and FNE_CHECK_START. * Return a pointer to just after the name. Equal to "arg" if there is no * valid name. */ static char_u * find_name_end(arg, expr_start, expr_end, flags) char_u *arg; char_u **expr_start; char_u **expr_end; int flags; { int mb_nest = 0; int br_nest = 0; char_u *p; if (expr_start != NULL) { *expr_start = NULL; *expr_end = NULL; } /* Quick check for valid starting character. */ if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{') return arg; for (p = arg; *p != NUL && (eval_isnamec(*p) || *p == '{' || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.')) || mb_nest != 0 || br_nest != 0); mb_ptr_adv(p)) { if (*p == '\'') { /* skip over 'string' to avoid counting [ and ] inside it. */ for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p)) ; if (*p == NUL) break; } else if (*p == '"') { /* skip over "str\"ing" to avoid counting [ and ] inside it. */ for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p)) if (*p == '\\' && p[1] != NUL) ++p; if (*p == NUL) break; } if (mb_nest == 0) { if (*p == '[') ++br_nest; else if (*p == ']') --br_nest; } if (br_nest == 0) { if (*p == '{') { mb_nest++; if (expr_start != NULL && *expr_start == NULL) *expr_start = p; } else if (*p == '}') { mb_nest--; if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL) *expr_end = p; } } } return p; } /* * Expands out the 'magic' {}'s in a variable/function name. * Note that this can call itself recursively, to deal with * constructs like foo{bar}{baz}{bam} * The four pointer arguments point to "foo{expre}ss{ion}bar" * "in_start" ^ * "expr_start" ^ * "expr_end" ^ * "in_end" ^ * * Returns a new allocated string, which the caller must free. * Returns NULL for failure. */ static char_u * make_expanded_name(in_start, expr_start, expr_end, in_end) char_u *in_start; char_u *expr_start; char_u *expr_end; char_u *in_end; { char_u c1; char_u *retval = NULL; char_u *temp_result; char_u *nextcmd = NULL; if (expr_end == NULL || in_end == NULL) return NULL; *expr_start = NUL; *expr_end = NUL; c1 = *in_end; *in_end = NUL; temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE); if (temp_result != NULL && nextcmd == NULL) { retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start) + (in_end - expr_end) + 1)); if (retval != NULL) { STRCPY(retval, in_start); STRCAT(retval, temp_result); STRCAT(retval, expr_end + 1); } } vim_free(temp_result); *in_end = c1; /* put char back for error messages */ *expr_start = '{'; *expr_end = '}'; if (retval != NULL) { temp_result = find_name_end(retval, &expr_start, &expr_end, 0); if (expr_start != NULL) { /* Further expansion! */ temp_result = make_expanded_name(retval, expr_start, expr_end, temp_result); vim_free(retval); retval = temp_result; } } return retval; } /* * Return TRUE if character "c" can be used in a variable or function name. * Does not include '{' or '}' for magic braces. */ static int eval_isnamec(c) int c; { return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR); } /* * Return TRUE if character "c" can be used as the first character in a * variable or function name (excluding '{' and '}'). */ static int eval_isnamec1(c) int c; { return (ASCII_ISALPHA(c) || c == '_'); } /* * Set number v: variable to "val". */ void set_vim_var_nr(idx, val) int idx; long val; { vimvars[idx].vv_nr = val; } /* * Get number v: variable value. */ long get_vim_var_nr(idx) int idx; { return vimvars[idx].vv_nr; } /* * Get string v: variable value. Uses a static buffer, can only be used once. */ char_u * get_vim_var_str(idx) int idx; { return get_tv_string(&vimvars[idx].vv_tv); } /* * Get List v: variable value. Caller must take care of reference count when * needed. */ list_T * get_vim_var_list(idx) int idx; { return vimvars[idx].vv_list; } /* * Set v:char to character "c". */ void set_vim_var_char(c) int c; { char_u buf[MB_MAXBYTES + 1]; #ifdef FEAT_MBYTE if (has_mbyte) buf[(*mb_char2bytes)(c, buf)] = NUL; else #endif { buf[0] = c; buf[1] = NUL; } set_vim_var_string(VV_CHAR, buf, -1); } /* * Set v:count to "count" and v:count1 to "count1". * When "set_prevcount" is TRUE first set v:prevcount from v:count. */ void set_vcount(count, count1, set_prevcount) long count; long count1; int set_prevcount; { if (set_prevcount) vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr; vimvars[VV_COUNT].vv_nr = count; vimvars[VV_COUNT1].vv_nr = count1; } /* * Set string v: variable to a copy of "val". */ void set_vim_var_string(idx, val, len) int idx; char_u *val; int len; /* length of "val" to use or -1 (whole string) */ { /* Need to do this (at least) once, since we can't initialize a union. * Will always be invoked when "v:progname" is set. */ vimvars[VV_VERSION].vv_nr = VIM_VERSION_100; vim_free(vimvars[idx].vv_str); if (val == NULL) vimvars[idx].vv_str = NULL; else if (len == -1) vimvars[idx].vv_str = vim_strsave(val); else vimvars[idx].vv_str = vim_strnsave(val, len); } /* * Set List v: variable to "val". */ void set_vim_var_list(idx, val) int idx; list_T *val; { list_unref(vimvars[idx].vv_list); vimvars[idx].vv_list = val; if (val != NULL) ++val->lv_refcount; } /* * Set v:register if needed. */ void set_reg_var(c) int c; { char_u regname; if (c == 0 || c == ' ') regname = '"'; else regname = c; /* Avoid free/alloc when the value is already right. */ if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c) set_vim_var_string(VV_REG, &regname, 1); } /* * Get or set v:exception. If "oldval" == NULL, return the current value. * Otherwise, restore the value to "oldval" and return NULL. * Must always be called in pairs to save and restore v:exception! Does not * take care of memory allocations. */ char_u * v_exception(oldval) char_u *oldval; { if (oldval == NULL) return vimvars[VV_EXCEPTION].vv_str; vimvars[VV_EXCEPTION].vv_str = oldval; return NULL; } /* * Get or set v:throwpoint. If "oldval" == NULL, return the current value. * Otherwise, restore the value to "oldval" and return NULL. * Must always be called in pairs to save and restore v:throwpoint! Does not * take care of memory allocations. */ char_u * v_throwpoint(oldval) char_u *oldval; { if (oldval == NULL) return vimvars[VV_THROWPOINT].vv_str; vimvars[VV_THROWPOINT].vv_str = oldval; return NULL; } #if defined(FEAT_AUTOCMD) || defined(PROTO) /* * Set v:cmdarg. * If "eap" != NULL, use "eap" to generate the value and return the old value. * If "oldarg" != NULL, restore the value to "oldarg" and return NULL. * Must always be called in pairs! */ char_u * set_cmdarg(eap, oldarg) exarg_T *eap; char_u *oldarg; { char_u *oldval; char_u *newval; unsigned len; oldval = vimvars[VV_CMDARG].vv_str; if (eap == NULL) { vim_free(oldval); vimvars[VV_CMDARG].vv_str = oldarg; return NULL; } if (eap->force_bin == FORCE_BIN) len = 6; else if (eap->force_bin == FORCE_NOBIN) len = 8; else len = 0; if (eap->read_edit) len += 7; if (eap->force_ff != 0) len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6; # ifdef FEAT_MBYTE if (eap->force_enc != 0) len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7; if (eap->bad_char != 0) len += 7 + 4; /* " ++bad=" + "keep" or "drop" */ # endif newval = alloc(len + 1); if (newval == NULL) return NULL; if (eap->force_bin == FORCE_BIN) sprintf((char *)newval, " ++bin"); else if (eap->force_bin == FORCE_NOBIN) sprintf((char *)newval, " ++nobin"); else *newval = NUL; if (eap->read_edit) STRCAT(newval, " ++edit"); if (eap->force_ff != 0) sprintf((char *)newval + STRLEN(newval), " ++ff=%s", eap->cmd + eap->force_ff); # ifdef FEAT_MBYTE if (eap->force_enc != 0) sprintf((char *)newval + STRLEN(newval), " ++enc=%s", eap->cmd + eap->force_enc); if (eap->bad_char == BAD_KEEP) STRCPY(newval + STRLEN(newval), " ++bad=keep"); else if (eap->bad_char == BAD_DROP) STRCPY(newval + STRLEN(newval), " ++bad=drop"); else if (eap->bad_char != 0) sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char); # endif vimvars[VV_CMDARG].vv_str = newval; return oldval; } #endif /* * Get the value of internal variable "name". * Return OK or FAIL. */ static int get_var_tv(name, len, rettv, verbose) char_u *name; int len; /* length of "name" */ typval_T *rettv; /* NULL when only checking existence */ int verbose; /* may give error message */ { int ret = OK; typval_T *tv = NULL; typval_T atv; dictitem_T *v; int cc; /* truncate the name, so that we can use strcmp() */ cc = name[len]; name[len] = NUL; /* * Check for "b:changedtick". */ if (STRCMP(name, "b:changedtick") == 0) { atv.v_type = VAR_NUMBER; atv.vval.v_number = curbuf->b_changedtick; tv = &atv; } /* * Check for user-defined variables. */ else { v = find_var(name, NULL); if (v != NULL) tv = &v->di_tv; } if (tv == NULL) { if (rettv != NULL && verbose) EMSG2(_(e_undefvar), name); ret = FAIL; } else if (rettv != NULL) copy_tv(tv, rettv); name[len] = cc; return ret; } /* * Handle expr[expr], expr[expr:expr] subscript and .name lookup. * Also handle function call with Funcref variable: func(expr) * Can all be combined: dict.func(expr)[idx]['func'](expr) */ static int handle_subscript(arg, rettv, evaluate, verbose) char_u **arg; typval_T *rettv; int evaluate; /* do more than finding the end */ int verbose; /* give error messages */ { int ret = OK; dict_T *selfdict = NULL; char_u *s; int len; typval_T functv; while (ret == OK && (**arg == '[' || (**arg == '.' && rettv->v_type == VAR_DICT) || (**arg == '(' && rettv->v_type == VAR_FUNC)) && !vim_iswhite(*(*arg - 1))) { if (**arg == '(') { /* need to copy the funcref so that we can clear rettv */ functv = *rettv; rettv->v_type = VAR_UNKNOWN; /* Invoke the function. Recursive! */ s = functv.vval.v_string; ret = get_func_tv(s, (int)STRLEN(s), rettv, arg, curwin->w_cursor.lnum, curwin->w_cursor.lnum, &len, evaluate, selfdict); /* Clear the funcref afterwards, so that deleting it while * evaluating the arguments is possible (see test55). */ clear_tv(&functv); /* Stop the expression evaluation when immediately aborting on * error, or when an interrupt occurred or an exception was thrown * but not caught. */ if (aborting()) { if (ret == OK) clear_tv(rettv); ret = FAIL; } dict_unref(selfdict); selfdict = NULL; } else /* **arg == '[' || **arg == '.' */ { dict_unref(selfdict); if (rettv->v_type == VAR_DICT) { selfdict = rettv->vval.v_dict; if (selfdict != NULL) ++selfdict->dv_refcount; } else selfdict = NULL; if (eval_index(arg, rettv, evaluate, verbose) == FAIL) { clear_tv(rettv); ret = FAIL; } } } dict_unref(selfdict); return ret; } /* * Allocate memory for a variable type-value, and make it empty (0 or NULL * value). */ static typval_T * alloc_tv() { return (typval_T *)alloc_clear((unsigned)sizeof(typval_T)); } /* * Allocate memory for a variable type-value, and assign a string to it. * The string "s" must have been allocated, it is consumed. * Return NULL for out of memory, the variable otherwise. */ static typval_T * alloc_string_tv(s) char_u *s; { typval_T *rettv; rettv = alloc_tv(); if (rettv != NULL) { rettv->v_type = VAR_STRING; rettv->vval.v_string = s; } else vim_free(s); return rettv; } /* * Free the memory for a variable type-value. */ void free_tv(varp) typval_T *varp; { if (varp != NULL) { switch (varp->v_type) { case VAR_FUNC: func_unref(varp->vval.v_string); /*FALLTHROUGH*/ case VAR_STRING: vim_free(varp->vval.v_string); break; case VAR_LIST: list_unref(varp->vval.v_list); break; case VAR_DICT: dict_unref(varp->vval.v_dict); break; case VAR_NUMBER: #ifdef FEAT_FLOAT case VAR_FLOAT: #endif case VAR_UNKNOWN: break; default: EMSG2(_(e_intern2), "free_tv()"); break; } vim_free(varp); } } /* * Free the memory for a variable value and set the value to NULL or 0. */ void clear_tv(varp) typval_T *varp; { if (varp != NULL) { switch (varp->v_type) { case VAR_FUNC: func_unref(varp->vval.v_string); /*FALLTHROUGH*/ case VAR_STRING: vim_free(varp->vval.v_string); varp->vval.v_string = NULL; break; case VAR_LIST: list_unref(varp->vval.v_list); varp->vval.v_list = NULL; break; case VAR_DICT: dict_unref(varp->vval.v_dict); varp->vval.v_dict = NULL; break; case VAR_NUMBER: varp->vval.v_number = 0; break; #ifdef FEAT_FLOAT case VAR_FLOAT: varp->vval.v_float = 0.0; break; #endif case VAR_UNKNOWN: break; default: EMSG2(_(e_intern2), "clear_tv()"); } varp->v_lock = 0; } } /* * Set the value of a variable to NULL without freeing items. */ static void init_tv(varp) typval_T *varp; { if (varp != NULL) vim_memset(varp, 0, sizeof(typval_T)); } /* * Get the number value of a variable. * If it is a String variable, uses vim_str2nr(). * For incompatible types, return 0. * get_tv_number_chk() is similar to get_tv_number(), but informs the * caller of incompatible types: it sets *denote to TRUE if "denote" * is not NULL or returns -1 otherwise. */ static long get_tv_number(varp) typval_T *varp; { int error = FALSE; return get_tv_number_chk(varp, &error); /* return 0L on error */ } long get_tv_number_chk(varp, denote) typval_T *varp; int *denote; { long n = 0L; switch (varp->v_type) { case VAR_NUMBER: return (long)(varp->vval.v_number); #ifdef FEAT_FLOAT case VAR_FLOAT: EMSG(_("E805: Using a Float as a Number")); break; #endif case VAR_FUNC: EMSG(_("E703: Using a Funcref as a Number")); break; case VAR_STRING: if (varp->vval.v_string != NULL) vim_str2nr(varp->vval.v_string, NULL, NULL, TRUE, TRUE, &n, NULL); return n; case VAR_LIST: EMSG(_("E745: Using a List as a Number")); break; case VAR_DICT: EMSG(_("E728: Using a Dictionary as a Number")); break; default: EMSG2(_(e_intern2), "get_tv_number()"); break; } if (denote == NULL) /* useful for values that must be unsigned */ n = -1; else *denote = TRUE; return n; } /* * Get the lnum from the first argument. * Also accepts ".", "$", etc., but that only works for the current buffer. * Returns -1 on error. */ static linenr_T get_tv_lnum(argvars) typval_T *argvars; { typval_T rettv; linenr_T lnum; lnum = get_tv_number_chk(&argvars[0], NULL); if (lnum == 0) /* no valid number, try using line() */ { rettv.v_type = VAR_NUMBER; f_line(argvars, &rettv); lnum = rettv.vval.v_number; clear_tv(&rettv); } return lnum; } /* * Get the lnum from the first argument. * Also accepts "$", then "buf" is used. * Returns 0 on error. */ static linenr_T get_tv_lnum_buf(argvars, buf) typval_T *argvars; buf_T *buf; { if (argvars[0].v_type == VAR_STRING && argvars[0].vval.v_string != NULL && argvars[0].vval.v_string[0] == '$' && buf != NULL) return buf->b_ml.ml_line_count; return get_tv_number_chk(&argvars[0], NULL); } /* * Get the string value of a variable. * If it is a Number variable, the number is converted into a string. * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE! * get_tv_string_buf() uses a given buffer. * If the String variable has never been set, return an empty string. * Never returns NULL; * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return * NULL on error. */ static char_u * get_tv_string(varp) typval_T *varp; { static char_u mybuf[NUMBUFLEN]; return get_tv_string_buf(varp, mybuf); } static char_u * get_tv_string_buf(varp, buf) typval_T *varp; char_u *buf; { char_u *res = get_tv_string_buf_chk(varp, buf); return res != NULL ? res : (char_u *)""; } char_u * get_tv_string_chk(varp) typval_T *varp; { static char_u mybuf[NUMBUFLEN]; return get_tv_string_buf_chk(varp, mybuf); } static char_u * get_tv_string_buf_chk(varp, buf) typval_T *varp; char_u *buf; { switch (varp->v_type) { case VAR_NUMBER: sprintf((char *)buf, "%ld", (long)varp->vval.v_number); return buf; case VAR_FUNC: EMSG(_("E729: using Funcref as a String")); break; case VAR_LIST: EMSG(_("E730: using List as a String")); break; case VAR_DICT: EMSG(_("E731: using Dictionary as a String")); break; #ifdef FEAT_FLOAT case VAR_FLOAT: EMSG(_("E806: using Float as a String")); break; #endif case VAR_STRING: if (varp->vval.v_string != NULL) return varp->vval.v_string; return (char_u *)""; default: EMSG2(_(e_intern2), "get_tv_string_buf()"); break; } return NULL; } /* * Find variable "name" in the list of variables. * Return a pointer to it if found, NULL if not found. * Careful: "a:0" variables don't have a name. * When "htp" is not NULL we are writing to the variable, set "htp" to the * hashtab_T used. */ static dictitem_T * find_var(name, htp) char_u *name; hashtab_T **htp; { char_u *varname; hashtab_T *ht; ht = find_var_ht(name, &varname); if (htp != NULL) *htp = ht; if (ht == NULL) return NULL; return find_var_in_ht(ht, varname, htp != NULL); } /* * Find variable "varname" in hashtab "ht". * Returns NULL if not found. */ static dictitem_T * find_var_in_ht(ht, varname, writing) hashtab_T *ht; char_u *varname; int writing; { hashitem_T *hi; if (*varname == NUL) { /* Must be something like "s:", otherwise "ht" would be NULL. */ switch (varname[-2]) { case 's': return &SCRIPT_SV(current_SID)->sv_var; case 'g': return &globvars_var; case 'v': return &vimvars_var; case 'b': return &curbuf->b_bufvar; case 'w': return &curwin->w_winvar; #ifdef FEAT_WINDOWS case 't': return &curtab->tp_winvar; #endif case 'l': return current_funccal == NULL ? NULL : &current_funccal->l_vars_var; case 'a': return current_funccal == NULL ? NULL : &current_funccal->l_avars_var; } return NULL; } hi = hash_find(ht, varname); if (HASHITEM_EMPTY(hi)) { /* For global variables we may try auto-loading the script. If it * worked find the variable again. Don't auto-load a script if it was * loaded already, otherwise it would be loaded every time when * checking if a function name is a Funcref variable. */ if (ht == &globvarht && !writing) { /* Note: script_autoload() may make "hi" invalid. It must either * be obtained again or not used. */ if (!script_autoload(varname, FALSE) || aborting()) return NULL; hi = hash_find(ht, varname); } if (HASHITEM_EMPTY(hi)) return NULL; } return HI2DI(hi); } /* * Find the hashtab used for a variable name. * Set "varname" to the start of name without ':'. */ static hashtab_T * find_var_ht(name, varname) char_u *name; char_u **varname; { hashitem_T *hi; if (name[1] != ':') { /* The name must not start with a colon or #. */ if (name[0] == ':' || name[0] == AUTOLOAD_CHAR) return NULL; *varname = name; /* "version" is "v:version" in all scopes */ hi = hash_find(&compat_hashtab, name); if (!HASHITEM_EMPTY(hi)) return &compat_hashtab; if (current_funccal == NULL) return &globvarht; /* global variable */ return &current_funccal->l_vars.dv_hashtab; /* l: variable */ } *varname = name + 2; if (*name == 'g') /* global variable */ return &globvarht; /* There must be no ':' or '#' in the rest of the name, unless g: is used */ if (vim_strchr(name + 2, ':') != NULL || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL) return NULL; if (*name == 'b') /* buffer variable */ return &curbuf->b_vars.dv_hashtab; if (*name == 'w') /* window variable */ return &curwin->w_vars.dv_hashtab; #ifdef FEAT_WINDOWS if (*name == 't') /* tab page variable */ return &curtab->tp_vars.dv_hashtab; #endif if (*name == 'v') /* v: variable */ return &vimvarht; if (*name == 'a' && current_funccal != NULL) /* function argument */ return &current_funccal->l_avars.dv_hashtab; if (*name == 'l' && current_funccal != NULL) /* local function variable */ return &current_funccal->l_vars.dv_hashtab; if (*name == 's' /* script variable */ && current_SID > 0 && current_SID <= ga_scripts.ga_len) return &SCRIPT_VARS(current_SID); return NULL; } /* * Get the string value of a (global/local) variable. * Note: see get_tv_string() for how long the pointer remains valid. * Returns NULL when it doesn't exist. */ char_u * get_var_value(name) char_u *name; { dictitem_T *v; v = find_var(name, NULL); if (v == NULL) return NULL; return get_tv_string(&v->di_tv); } /* * Allocate a new hashtab for a sourced script. It will be used while * sourcing this script and when executing functions defined in the script. */ void new_script_vars(id) scid_T id; { int i; hashtab_T *ht; scriptvar_T *sv; if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK) { /* Re-allocating ga_data means that an ht_array pointing to * ht_smallarray becomes invalid. We can recognize this: ht_mask is * at its init value. Also reset "v_dict", it's always the same. */ for (i = 1; i <= ga_scripts.ga_len; ++i) { ht = &SCRIPT_VARS(i); if (ht->ht_mask == HT_INIT_SIZE - 1) ht->ht_array = ht->ht_smallarray; sv = SCRIPT_SV(i); sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict; } while (ga_scripts.ga_len < id) { sv = SCRIPT_SV(ga_scripts.ga_len + 1) = (scriptvar_T *)alloc_clear(sizeof(scriptvar_T)); init_var_dict(&sv->sv_dict, &sv->sv_var); ++ga_scripts.ga_len; } } } /* * Initialize dictionary "dict" as a scope and set variable "dict_var" to * point to it. */ void init_var_dict(dict, dict_var) dict_T *dict; dictitem_T *dict_var; { hash_init(&dict->dv_hashtab); dict->dv_lock = 0; dict->dv_refcount = DO_NOT_FREE_CNT; dict->dv_copyID = 0; dict_var->di_tv.vval.v_dict = dict; dict_var->di_tv.v_type = VAR_DICT; dict_var->di_tv.v_lock = VAR_FIXED; dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; dict_var->di_key[0] = NUL; } /* * Clean up a list of internal variables. * Frees all allocated variables and the value they contain. * Clears hashtab "ht", does not free it. */ void vars_clear(ht) hashtab_T *ht; { vars_clear_ext(ht, TRUE); } /* * Like vars_clear(), but only free the value if "free_val" is TRUE. */ static void vars_clear_ext(ht, free_val) hashtab_T *ht; int free_val; { int todo; hashitem_T *hi; dictitem_T *v; hash_lock(ht); todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; /* Free the variable. Don't remove it from the hashtab, * ht_array might change then. hash_clear() takes care of it * later. */ v = HI2DI(hi); if (free_val) clear_tv(&v->di_tv); if ((v->di_flags & DI_FLAGS_FIX) == 0) vim_free(v); } } hash_clear(ht); ht->ht_used = 0; } /* * Delete a variable from hashtab "ht" at item "hi". * Clear the variable value and free the dictitem. */ static void delete_var(ht, hi) hashtab_T *ht; hashitem_T *hi; { dictitem_T *di = HI2DI(hi); hash_remove(ht, hi); clear_tv(&di->di_tv); vim_free(di); } /* * List the value of one internal variable. */ static void list_one_var(v, prefix, first) dictitem_T *v; char_u *prefix; int *first; { char_u *tofree; char_u *s; char_u numbuf[NUMBUFLEN]; current_copyID += COPYID_INC; s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID); list_one_var_a(prefix, v->di_key, v->di_tv.v_type, s == NULL ? (char_u *)"" : s, first); vim_free(tofree); } static void list_one_var_a(prefix, name, type, string, first) char_u *prefix; char_u *name; int type; char_u *string; int *first; /* when TRUE clear rest of screen and set to FALSE */ { /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */ msg_start(); msg_puts(prefix); if (name != NULL) /* "a:" vars don't have a name stored */ msg_puts(name); msg_putchar(' '); msg_advance(22); if (type == VAR_NUMBER) msg_putchar('#'); else if (type == VAR_FUNC) msg_putchar('*'); else if (type == VAR_LIST) { msg_putchar('['); if (*string == '[') ++string; } else if (type == VAR_DICT) { msg_putchar('{'); if (*string == '{') ++string; } else msg_putchar(' '); msg_outtrans(string); if (type == VAR_FUNC) msg_puts((char_u *)"()"); if (*first) { msg_clr_eos(); *first = FALSE; } } /* * Set variable "name" to value in "tv". * If the variable already exists, the value is updated. * Otherwise the variable is created. */ static void set_var(name, tv, copy) char_u *name; typval_T *tv; int copy; /* make copy of value in "tv" */ { dictitem_T *v; char_u *varname; hashtab_T *ht; ht = find_var_ht(name, &varname); if (ht == NULL || *varname == NUL) { EMSG2(_(e_illvar), name); return; } v = find_var_in_ht(ht, varname, TRUE); if (tv->v_type == VAR_FUNC && var_check_func_name(name, v == NULL)) return; if (v != NULL) { /* existing variable, need to clear the value */ if (var_check_ro(v->di_flags, name) || tv_check_lock(v->di_tv.v_lock, name)) return; if (v->di_tv.v_type != tv->v_type && !((v->di_tv.v_type == VAR_STRING || v->di_tv.v_type == VAR_NUMBER) && (tv->v_type == VAR_STRING || tv->v_type == VAR_NUMBER)) #ifdef FEAT_FLOAT && !((v->di_tv.v_type == VAR_NUMBER || v->di_tv.v_type == VAR_FLOAT) && (tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)) #endif ) { EMSG2(_("E706: Variable type mismatch for: %s"), name); return; } /* * Handle setting internal v: variables separately: we don't change * the type. */ if (ht == &vimvarht) { if (v->di_tv.v_type == VAR_STRING) { vim_free(v->di_tv.vval.v_string); if (copy || tv->v_type != VAR_STRING) v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv)); else { /* Take over the string to avoid an extra alloc/free. */ v->di_tv.vval.v_string = tv->vval.v_string; tv->vval.v_string = NULL; } } else if (v->di_tv.v_type != VAR_NUMBER) EMSG2(_(e_intern2), "set_var()"); else { v->di_tv.vval.v_number = get_tv_number(tv); if (STRCMP(varname, "searchforward") == 0) set_search_direction(v->di_tv.vval.v_number ? '/' : '?'); } return; } clear_tv(&v->di_tv); } else /* add a new variable */ { /* Can't add "v:" variable. */ if (ht == &vimvarht) { EMSG2(_(e_illvar), name); return; } /* Make sure the variable name is valid. */ if (!valid_varname(varname)) return; v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(varname))); if (v == NULL) return; STRCPY(v->di_key, varname); if (hash_add(ht, DI2HIKEY(v)) == FAIL) { vim_free(v); return; } v->di_flags = 0; } if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT) copy_tv(tv, &v->di_tv); else { v->di_tv = *tv; v->di_tv.v_lock = 0; init_tv(tv); } } /* * Return TRUE if di_flags "flags" indicates variable "name" is read-only. * Also give an error message. */ static int var_check_ro(flags, name) int flags; char_u *name; { if (flags & DI_FLAGS_RO) { EMSG2(_(e_readonlyvar), name); return TRUE; } if ((flags & DI_FLAGS_RO_SBX) && sandbox) { EMSG2(_(e_readonlysbx), name); return TRUE; } return FALSE; } /* * Return TRUE if di_flags "flags" indicates variable "name" is fixed. * Also give an error message. */ static int var_check_fixed(flags, name) int flags; char_u *name; { if (flags & DI_FLAGS_FIX) { EMSG2(_("E795: Cannot delete variable %s"), name); return TRUE; } return FALSE; } /* * Check if a funcref is assigned to a valid variable name. * Return TRUE and give an error if not. */ static int var_check_func_name(name, new_var) char_u *name; /* points to start of variable name */ int new_var; /* TRUE when creating the variable */ { if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':') && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':') ? name[2] : name[0])) { EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name); return TRUE; } /* Don't allow hiding a function. When "v" is not NULL we might be * assigning another function to the same var, the type is checked * below. */ if (new_var && function_exists(name)) { EMSG2(_("E705: Variable name conflicts with existing function: %s"), name); return TRUE; } return FALSE; } /* * Check if a variable name is valid. * Return FALSE and give an error if not. */ static int valid_varname(varname) char_u *varname; { char_u *p; for (p = varname; *p != NUL; ++p) if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p)) && *p != AUTOLOAD_CHAR) { EMSG2(_(e_illvar), varname); return FALSE; } return TRUE; } /* * Return TRUE if typeval "tv" is set to be locked (immutable). * Also give an error message, using "name". */ static int tv_check_lock(lock, name) int lock; char_u *name; { if (lock & VAR_LOCKED) { EMSG2(_("E741: Value is locked: %s"), name == NULL ? (char_u *)_("Unknown") : name); return TRUE; } if (lock & VAR_FIXED) { EMSG2(_("E742: Cannot change value of %s"), name == NULL ? (char_u *)_("Unknown") : name); return TRUE; } return FALSE; } /* * Copy the values from typval_T "from" to typval_T "to". * When needed allocates string or increases reference count. * Does not make a copy of a list or dict but copies the reference! * It is OK for "from" and "to" to point to the same item. This is used to * make a copy later. */ void copy_tv(from, to) typval_T *from; typval_T *to; { to->v_type = from->v_type; to->v_lock = 0; switch (from->v_type) { case VAR_NUMBER: to->vval.v_number = from->vval.v_number; break; #ifdef FEAT_FLOAT case VAR_FLOAT: to->vval.v_float = from->vval.v_float; break; #endif case VAR_STRING: case VAR_FUNC: if (from->vval.v_string == NULL) to->vval.v_string = NULL; else { to->vval.v_string = vim_strsave(from->vval.v_string); if (from->v_type == VAR_FUNC) func_ref(to->vval.v_string); } break; case VAR_LIST: if (from->vval.v_list == NULL) to->vval.v_list = NULL; else { to->vval.v_list = from->vval.v_list; ++to->vval.v_list->lv_refcount; } break; case VAR_DICT: if (from->vval.v_dict == NULL) to->vval.v_dict = NULL; else { to->vval.v_dict = from->vval.v_dict; ++to->vval.v_dict->dv_refcount; } break; default: EMSG2(_(e_intern2), "copy_tv()"); break; } } /* * Make a copy of an item. * Lists and Dictionaries are also copied. A deep copy if "deep" is set. * For deepcopy() "copyID" is zero for a full copy or the ID for when a * reference to an already copied list/dict can be used. * Returns FAIL or OK. */ static int item_copy(from, to, deep, copyID) typval_T *from; typval_T *to; int deep; int copyID; { static int recurse = 0; int ret = OK; if (recurse >= DICT_MAXNEST) { EMSG(_("E698: variable nested too deep for making a copy")); return FAIL; } ++recurse; switch (from->v_type) { case VAR_NUMBER: #ifdef FEAT_FLOAT case VAR_FLOAT: #endif case VAR_STRING: case VAR_FUNC: copy_tv(from, to); break; case VAR_LIST: to->v_type = VAR_LIST; to->v_lock = 0; if (from->vval.v_list == NULL) to->vval.v_list = NULL; else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID) { /* use the copy made earlier */ to->vval.v_list = from->vval.v_list->lv_copylist; ++to->vval.v_list->lv_refcount; } else to->vval.v_list = list_copy(from->vval.v_list, deep, copyID); if (to->vval.v_list == NULL) ret = FAIL; break; case VAR_DICT: to->v_type = VAR_DICT; to->v_lock = 0; if (from->vval.v_dict == NULL) to->vval.v_dict = NULL; else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID) { /* use the copy made earlier */ to->vval.v_dict = from->vval.v_dict->dv_copydict; ++to->vval.v_dict->dv_refcount; } else to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID); if (to->vval.v_dict == NULL) ret = FAIL; break; default: EMSG2(_(e_intern2), "item_copy()"); ret = FAIL; } --recurse; return ret; } /* * ":echo expr1 ..." print each argument separated with a space, add a * newline at the end. * ":echon expr1 ..." print each argument plain. */ void ex_echo(eap) exarg_T *eap; { char_u *arg = eap->arg; typval_T rettv; char_u *tofree; char_u *p; int needclr = TRUE; int atstart = TRUE; char_u numbuf[NUMBUFLEN]; if (eap->skip) ++emsg_skip; while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int) { /* If eval1() causes an error message the text from the command may * still need to be cleared. E.g., "echo 22,44". */ need_clr_eos = needclr; p = arg; if (eval1(&arg, &rettv, !eap->skip) == FAIL) { /* * Report the invalid expression unless the expression evaluation * has been cancelled due to an aborting error, an interrupt, or an * exception. */ if (!aborting()) EMSG2(_(e_invexpr2), p); need_clr_eos = FALSE; break; } need_clr_eos = FALSE; if (!eap->skip) { if (atstart) { atstart = FALSE; /* Call msg_start() after eval1(), evaluating the expression * may cause a message to appear. */ if (eap->cmdidx == CMD_echo) { /* Mark the saved text as finishing the line, so that what * follows is displayed on a new line when scrolling back * at the more prompt. */ msg_sb_eol(); msg_start(); } } else if (eap->cmdidx == CMD_echo) msg_puts_attr((char_u *)" ", echo_attr); current_copyID += COPYID_INC; p = echo_string(&rettv, &tofree, numbuf, current_copyID); if (p != NULL) for ( ; *p != NUL && !got_int; ++p) { if (*p == '\n' || *p == '\r' || *p == TAB) { if (*p != TAB && needclr) { /* remove any text still there from the command */ msg_clr_eos(); needclr = FALSE; } msg_putchar_attr(*p, echo_attr); } else { #ifdef FEAT_MBYTE if (has_mbyte) { int i = (*mb_ptr2len)(p); (void)msg_outtrans_len_attr(p, i, echo_attr); p += i - 1; } else #endif (void)msg_outtrans_len_attr(p, 1, echo_attr); } } vim_free(tofree); } clear_tv(&rettv); arg = skipwhite(arg); } eap->nextcmd = check_nextcmd(arg); if (eap->skip) --emsg_skip; else { /* remove text that may still be there from the command */ if (needclr) msg_clr_eos(); if (eap->cmdidx == CMD_echo) msg_end(); } } /* * ":echohl {name}". */ void ex_echohl(eap) exarg_T *eap; { int id; id = syn_name2id(eap->arg); if (id == 0) echo_attr = 0; else echo_attr = syn_id2attr(id); } /* * ":execute expr1 ..." execute the result of an expression. * ":echomsg expr1 ..." Print a message * ":echoerr expr1 ..." Print an error * Each gets spaces around each argument and a newline at the end for * echo commands */ void ex_execute(eap) exarg_T *eap; { char_u *arg = eap->arg; typval_T rettv; int ret = OK; char_u *p; garray_T ga; int len; int save_did_emsg; ga_init2(&ga, 1, 80); if (eap->skip) ++emsg_skip; while (*arg != NUL && *arg != '|' && *arg != '\n') { p = arg; if (eval1(&arg, &rettv, !eap->skip) == FAIL) { /* * Report the invalid expression unless the expression evaluation * has been cancelled due to an aborting error, an interrupt, or an * exception. */ if (!aborting()) EMSG2(_(e_invexpr2), p); ret = FAIL; break; } if (!eap->skip) { p = get_tv_string(&rettv); len = (int)STRLEN(p); if (ga_grow(&ga, len + 2) == FAIL) { clear_tv(&rettv); ret = FAIL; break; } if (ga.ga_len) ((char_u *)(ga.ga_data))[ga.ga_len++] = ' '; STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p); ga.ga_len += len; } clear_tv(&rettv); arg = skipwhite(arg); } if (ret != FAIL && ga.ga_data != NULL) { if (eap->cmdidx == CMD_echomsg) { MSG_ATTR(ga.ga_data, echo_attr); out_flush(); } else if (eap->cmdidx == CMD_echoerr) { /* We don't want to abort following commands, restore did_emsg. */ save_did_emsg = did_emsg; EMSG((char_u *)ga.ga_data); if (!force_abort) did_emsg = save_did_emsg; } else if (eap->cmdidx == CMD_execute) do_cmdline((char_u *)ga.ga_data, eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE); } ga_clear(&ga); if (eap->skip) --emsg_skip; eap->nextcmd = check_nextcmd(arg); } /* * Skip over the name of an option: "&option", "&g:option" or "&l:option". * "arg" points to the "&" or '+' when called, to "option" when returning. * Returns NULL when no option name found. Otherwise pointer to the char * after the option name. */ static char_u * find_option_end(arg, opt_flags) char_u **arg; int *opt_flags; { char_u *p = *arg; ++p; if (*p == 'g' && p[1] == ':') { *opt_flags = OPT_GLOBAL; p += 2; } else if (*p == 'l' && p[1] == ':') { *opt_flags = OPT_LOCAL; p += 2; } else *opt_flags = 0; if (!ASCII_ISALPHA(*p)) return NULL; *arg = p; if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL) p += 4; /* termcap option */ else while (ASCII_ISALPHA(*p)) ++p; return p; } /* * ":function" */ void ex_function(eap) exarg_T *eap; { char_u *theline; int i; int j; int c; int saved_did_emsg; char_u *name = NULL; char_u *p; char_u *arg; char_u *line_arg = NULL; garray_T newargs; garray_T newlines; int varargs = FALSE; int mustend = FALSE; int flags = 0; ufunc_T *fp; int indent; int nesting; char_u *skip_until = NULL; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; /* number for nameless function */ int paren; hashtab_T *ht; int todo; hashitem_T *hi; int sourcing_lnum_off; /* * ":function" without argument: list functions. */ if (ends_excmd(*eap->arg)) { if (!eap->skip) { todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!isdigit(*fp->uf_name)) list_func_head(fp, FALSE); } } } eap->nextcmd = check_nextcmd(eap->arg); return; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE, NULL); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!isdigit(*fp->uf_name) && vim_regexec(&regmatch, fp->uf_name, 0)) list_func_head(fp, FALSE); } } vim_free(regmatch.regprog); } } if (*p == '/') ++p; eap->nextcmd = check_nextcmd(p); return; } /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL */ p = eap->arg; name = trans_function_name(&p, eap->skip, 0, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) EMSG2(_(e_dictkey), fudi.fd_newkey); vim_free(fudi.fd_newkey); return; } else eap->skip = TRUE; } /* An error in a function call during evaluation of an expression in magic * braces should not cause the function not to be defined. */ saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { EMSG(_(e_trailing)); goto ret_free; } eap->nextcmd = check_nextcmd(p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name); if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); /* show a line at a time */ ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); msg_puts((char_u *)" endfunction"); } } else emsg_funcname(N_("E123: Undefined function: %s"), name); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { EMSG2(_("E124: Missing '(': %s"), eap->arg); goto ret_free; } /* attempt to continue by skipping some text */ if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } p = skipwhite(p + 1); ga_init2(&newargs, (int)sizeof(char_u *), 3); ga_init2(&newlines, (int)sizeof(char_u *), 3); if (!eap->skip) { /* Check the name of the function. Unless it's a dictionary function * (that we are overwriting). */ if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || fudi.fd_di->di_tv.v_type != VAR_FUNC)) { if (*arg == K_SPECIAL) j = 3; else j = 0; while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j]) : eval_isnamec(arg[j]))) ++j; if (arg[j] != NUL) emsg_funcname((char *)e_invarg2, arg); } } /* * Isolate the arguments: "arg1, arg2, ...)" */ while (*p != ')') { if (p[0] == '.' && p[1] == '.' && p[2] == '.') { varargs = TRUE; p += 3; mustend = TRUE; } else { arg = p; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)) { if (!eap->skip) EMSG2(_("E125: Illegal argument: %s"), arg); break; } if (ga_grow(&newargs, 1) == FAIL) goto erret; c = *p; *p = NUL; arg = vim_strsave(arg); if (arg == NULL) goto erret; /* Check for duplicate argument name. */ for (i = 0; i < newargs.ga_len; ++i) if (STRCMP(((char_u **)(newargs.ga_data))[i], arg) == 0) { EMSG2(_("E853: Duplicate argument name: %s"), arg); goto erret; } ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg; *p = c; newargs.ga_len++; if (*p == ',') ++p; else mustend = TRUE; } p = skipwhite(p); if (mustend && *p != ')') { if (!eap->skip) EMSG2(_(e_invarg2), eap->arg); break; } } ++p; /* skip the ')' */ /* find extra arguments "range", "dict" and "abort" */ for (;;) { p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else break; } /* When there is a line break use what follows for the function body. * Makes 'exe "func Test()\n...\nendfunc"' work. */ if (*p == '\n') line_arg = p + 1; else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg) EMSG(_(e_trailing)); /* * Read the body of the function, until ":endfunction" is found. */ if (KeyTyped) { /* Check if the function already exists, don't let the user type the * whole function before telling him it doesn't work! For a script we * need to skip the body to be able to find what follows. */ if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) EMSG(_(e_funcdict)); else if (name != NULL && find_func(name) != NULL) emsg_funcname(e_funcexts, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); /* don't overwrite the function name */ cmdline_row = msg_row; } indent = 2; nesting = 0; for (;;) { if (KeyTyped) msg_scroll = TRUE; need_wait_return = FALSE; sourcing_lnum_off = sourcing_lnum; if (line_arg != NULL) { /* Use eap->arg, split up in parts by line breaks. */ theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else if (eap->getline == NULL) theline = getcmdline(':', 0L, indent); else theline = eap->getline(':', eap->cookie, indent); if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { EMSG(_("E126: Missing :endfunction")); goto erret; } /* Detect line continuation: sourcing_lnum increased more than one. */ if (sourcing_lnum > sourcing_lnum_off + 1) sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1; else sourcing_lnum_off = 0; if (skip_until != NULL) { /* between ":append" and "." and between ":python <<EOF" and "EOF" * don't check for ":endfunc". */ if (STRCMP(theline, skip_until) == 0) { vim_free(skip_until); skip_until = NULL; } } else { /* skip ':' and blanks*/ for (p = theline; vim_iswhite(*p) || *p == ':'; ++p) ; /* Check for "endfunction". */ if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0) { if (line_arg == NULL) vim_free(theline); break; } /* Increase indent inside "if", "while", "for" and "try", decrease * at "end". */ if (indent > 2 && STRNCMP(p, "end", 3) == 0) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; /* Check for defining a function inside this function. */ if (checkforcmd(&p, "function", 2)) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); if (ASCII_ISALPHA(*p)) { vim_free(trans_function_name(&p, TRUE, 0, NULL)); if (*skipwhite(p) == '(') { ++nesting; indent += 2; } } } /* Check for ":append" or ":insert". */ p = skip_range(p, NULL); if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's')))))) skip_until = vim_strsave((char_u *)"."); /* Check for ":python <<EOF", ":tcl <<EOF", etc. */ arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALPHA(p[2]) || p[2] == 't')) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { /* ":python <<" continues until a dot, like ":append" */ p = skipwhite(arg + 2); if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strsave(p); } } /* Add the line to the function. */ if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL) { if (line_arg == NULL) vim_free(theline); goto erret; } /* Copy the line to newly allocated memory. get_one_sourceline() * allocates 250 bytes per line, this saves 80% on average. The cost * is an extra alloc/free. */ p = vim_strsave(theline); if (p != NULL) { if (line_arg == NULL) vim_free(theline); theline = p; } ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline; /* Add NULL lines for continuation lines, so that the line count is * equal to the index in the growarray. */ while (sourcing_lnum_off-- > 0) ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL; /* Check for end of eap->arg. */ if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } /* Don't define the function when skipping commands or when an error was * detected. */ if (eap->skip || did_emsg) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { v = find_var(name, &ht); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(N_("E707: Function name conflicts with variable: %s"), name); goto erret; } fp = find_func(name); if (fp != NULL) { if (!eap->forceit) { emsg_funcname(e_funcexts, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"), name); goto erret; } /* redefine existing function */ ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_lines)); vim_free(name); name = NULL; } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { EMSG(_(e_funcdict)); goto erret; } if (fudi.fd_di == NULL) { /* Can't add a function to a locked dictionary */ if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg)) goto erret; } /* Can't change an existing function if it is locked */ else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg)) goto erret; /* Give the function a sequential number. Can only be used with a * Funcref! */ vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; /* Check that the autoload name matches the script name. */ j = FAIL; if (sourcing_name != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(sourcing_name); if (slen > plen && fnamecmp(p, sourcing_name + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { EMSG2(_("E746: Function name does not match script file name: %s"), name); goto erret; } } fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name))); if (fp == NULL) goto erret; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { /* add new dict entry */ fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); goto erret; } } else /* overwrite existing dict entry */ clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.v_lock = 0; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); fp->uf_refcount = 1; /* behave like "dict" was used */ flags |= FC_DICT; } /* insert the new function in the function list */ STRCPY(fp->uf_name, name); hash_add(&func_hashtab, UF2HIKEY(fp)); } fp->uf_args = newargs; fp->uf_lines = newlines; #ifdef FEAT_PROFILE fp->uf_tml_count = NULL; fp->uf_tml_total = NULL; fp->uf_tml_self = NULL; fp->uf_profiling = FALSE; if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ID = current_SID; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ret_free: vim_free(skip_until); vim_free(fudi.fd_newkey); vim_free(name); did_emsg |= saved_did_emsg; } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * Advances "pp" to just after the function name (if no error). */ static char_u * trans_function_name(pp, skip, flags, fdp) char_u **pp; int skip; /* only find the end, don't evaluate */ int flags; funcdict_T *fdp; /* return: info about dictionary used */ { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; lval_T lv; if (fdp != NULL) vim_memset(fdp, 0, sizeof(funcdict_T)); start = *pp; /* Check for hard coded <SNR>: already translated function ID (from a user * command). */ if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } /* A name starting with "<SID>" or "<SNR>" is local to a script. But * don't skip over "s:", get_lval() needs it for "s:dict.func". */ lead = eval_fname_script(start); if (lead > 2) start += lead; end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) EMSG(_("E129: Function name required")); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) EMSG2(_(e_invarg2), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) EMSG(_(e_funcref)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { /* Error found, but continue after the function name. */ *pp = end; goto theend; } /* Check if the name is a Funcref. If so, use the value. */ if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len); if (name == lv.ll_exp_name) name = NULL; } else { len = (int)(end - *pp); name = deref_func_name(*pp, &len); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { /* When there was "s:" already or the name expanded to get a * leading "s:" then remove it. */ lv.ll_name += 2; len -= 2; lead = 2; } } else { if (lead == 2) /* skip over "s:" */ lv.ll_name += 2; len = (int)(end - lv.ll_name); } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; /* do nothing */ else if (lead > 0) { lead = 3; if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { /* It's "s:" or "<SID>" */ if (current_SID <= 0) { EMSG(_(e_usingsid)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_SID); lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && builtin_function(lv.ll_name)) { EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name); goto theend; } name = alloc((unsigned)(len + lead + 1)); if (name != NULL) { if (lead > 0) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (lead > 3) /* If it's "<SID>" */ STRCPY(name + 3, sid_buf); } mch_memmove(name + lead, lv.ll_name, (size_t)len); name[len + lead] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ static int eval_fname_script(p) char_u *p; { if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0 || STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(p) char_u *p; { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * List the head of the function: "name(arg1, arg2)". */ static void list_func_head(fp, indent) ufunc_T *fp; int indent; { int j; msg_start(); if (indent) MSG_PUTS(" "); MSG_PUTS("function "); if (fp->uf_name[0] == K_SPECIAL) { MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8)); msg_puts(fp->uf_name + 3); } else msg_puts(fp->uf_name); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) MSG_PUTS(", "); msg_puts(FUNCARG(fp, j)); } if (fp->uf_varargs) { if (j) MSG_PUTS(", "); MSG_PUTS("..."); } msg_putchar(')'); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ID); } /* * Find a function by name, return pointer to it in ufuncs. * Return NULL for unknown function. */ static ufunc_T * find_func(name) char_u *name; { hashitem_T *hi; hi = hash_find(&func_hashtab, name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } #if defined(EXITFREE) || defined(PROTO) void free_all_functions() { hashitem_T *hi; /* Need to start all over every time, because func_free() may change the * hash table. */ while (func_hashtab.ht_used > 0) for (hi = func_hashtab.ht_array; ; ++hi) if (!HASHITEM_EMPTY(hi)) { func_free(HI2UF(hi)); break; } } #endif /* * Return TRUE if a function "name" exists. */ static int function_exists(name) char_u *name; { char_u *nm = name; char_u *p; int n = FALSE; p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL); nm = skipwhite(nm); /* Only accept "funcname", "funcname ", "funcname (..." and * "funcname(...", not "funcname!...". */ if (p != NULL && (*nm == NUL || *nm == '(')) { if (builtin_function(p)) n = (find_internal_func(p) >= 0); else n = (find_func(p) != NULL); } vim_free(p); return n; } /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR. */ static int builtin_function(name) char_u *name; { return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL && vim_strchr(name, AUTOLOAD_CHAR) == NULL; } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Start profiling function "fp". */ static void func_do_profile(fp) ufunc_T *fp; { int len = fp->uf_lines.ga_len; if (len == 0) len = 1; /* avoid getting error for allocating zero bytes */ fp->uf_tm_count = 0; profile_zero(&fp->uf_tm_self); profile_zero(&fp->uf_tm_total); if (fp->uf_tml_count == NULL) fp->uf_tml_count = (int *)alloc_clear((unsigned) (sizeof(int) * len)); if (fp->uf_tml_total == NULL) fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned) (sizeof(proftime_T) * len)); if (fp->uf_tml_self == NULL) fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned) (sizeof(proftime_T) * len)); fp->uf_tml_idx = -1; if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL || fp->uf_tml_self == NULL) return; /* out of memory */ fp->uf_profiling = TRUE; } /* * Dump the profiling results for all functions in file "fd". */ void func_dump_profile(fd) FILE *fd; { hashitem_T *hi; int todo; ufunc_T *fp; int i; ufunc_T **sorttab; int st_len = 0; todo = (int)func_hashtab.ht_used; if (todo == 0) return; /* nothing to dump */ sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo)); for (hi = func_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (fp->uf_profiling) { if (sorttab != NULL) sorttab[st_len++] = fp; if (fp->uf_name[0] == K_SPECIAL) fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3); else fprintf(fd, "FUNCTION %s()\n", fp->uf_name); if (fp->uf_tm_count == 1) fprintf(fd, "Called 1 time\n"); else fprintf(fd, "Called %d times\n", fp->uf_tm_count); fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total)); fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self)); fprintf(fd, "\n"); fprintf(fd, "count total (s) self (s)\n"); for (i = 0; i < fp->uf_lines.ga_len; ++i) { if (FUNCLINE(fp, i) == NULL) continue; prof_func_line(fd, fp->uf_tml_count[i], &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE); fprintf(fd, "%s\n", FUNCLINE(fp, i)); } fprintf(fd, "\n"); } } } if (sorttab != NULL && st_len > 0) { qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *), prof_total_cmp); prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE); qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *), prof_self_cmp); prof_sort_list(fd, sorttab, st_len, "SELF", TRUE); } vim_free(sorttab); } static void prof_sort_list(fd, sorttab, st_len, title, prefer_self) FILE *fd; ufunc_T **sorttab; int st_len; char *title; int prefer_self; /* when equal print only self time */ { int i; ufunc_T *fp; fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title); fprintf(fd, "count total (s) self (s) function\n"); for (i = 0; i < 20 && i < st_len; ++i) { fp = sorttab[i]; prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self, prefer_self); if (fp->uf_name[0] == K_SPECIAL) fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3); else fprintf(fd, " %s()\n", fp->uf_name); } fprintf(fd, "\n"); } /* * Print the count and times for one function or function line. */ static void prof_func_line(fd, count, total, self, prefer_self) FILE *fd; int count; proftime_T *total; proftime_T *self; int prefer_self; /* when equal print only self time */ { if (count > 0) { fprintf(fd, "%5d ", count); if (prefer_self && profile_equal(total, self)) fprintf(fd, " "); else fprintf(fd, "%s ", profile_msg(total)); if (!prefer_self && profile_equal(total, self)) fprintf(fd, " "); else fprintf(fd, "%s ", profile_msg(self)); } else fprintf(fd, " "); } /* * Compare function for total time sorting. */ static int #ifdef __BORLANDC__ _RTLENTRYF #endif prof_total_cmp(s1, s2) const void *s1; const void *s2; { ufunc_T *p1, *p2; p1 = *(ufunc_T **)s1; p2 = *(ufunc_T **)s2; return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total); } /* * Compare function for self time sorting. */ static int #ifdef __BORLANDC__ _RTLENTRYF #endif prof_self_cmp(s1, s2) const void *s1; const void *s2; { ufunc_T *p1, *p2; p1 = *(ufunc_T **)s1; p2 = *(ufunc_T **)s2; return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self); } #endif /* * If "name" has a package name try autoloading the script for it. * Return TRUE if a package was loaded. */ static int script_autoload(name, reload) char_u *name; int reload; /* load script again when already loaded */ { char_u *p; char_u *scriptname, *tofree; int ret = FALSE; int i; /* Return quickly when autoload disabled. */ if (no_autoload) return FALSE; /* If there is no '#' after name[0] there is no package name. */ p = vim_strchr(name, AUTOLOAD_CHAR); if (p == NULL || p == name) return FALSE; tofree = scriptname = autoload_name(name); /* Find the name in the list of previously loaded package names. Skip * "autoload/", it's always the same. */ for (i = 0; i < ga_loaded.ga_len; ++i) if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0) break; if (!reload && i < ga_loaded.ga_len) ret = FALSE; /* was loaded already */ else { /* Remember the name if it wasn't loaded already. */ if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK) { ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname; tofree = NULL; } /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */ if (source_runtime(scriptname, FALSE) == OK) ret = TRUE; } vim_free(tofree); return ret; } /* * Return the autoload script name for a function or variable name. * Returns NULL when out of memory. */ static char_u * autoload_name(name) char_u *name; { char_u *p; char_u *scriptname; /* Get the script file name: replace '#' with '/', append ".vim". */ scriptname = alloc((unsigned)(STRLEN(name) + 14)); if (scriptname == NULL) return FALSE; STRCPY(scriptname, "autoload/"); STRCAT(scriptname, name); *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL; STRCAT(scriptname, ".vim"); while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL) *p = '/'; return scriptname; } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(xp, idx) expand_T *xp; int idx; { static long_u done; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; } if (done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); if (fp->uf_flags & FC_DICT) return (char_u *)""; /* don't show dict functions */ if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; /* prevents overflow */ cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC) { STRCAT(IObuff, "("); if (!fp->uf_varargs && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } #endif /* FEAT_CMDL_COMPL */ /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(buf, fp) char_u *buf; ufunc_T *fp; { if (fp->uf_name[0] == K_SPECIAL) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * ":delfunction {name}" */ void ex_delfunction(eap) exarg_T *eap; { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; p = eap->arg; name = trans_function_name(&p, eap->skip, 0, &fudi); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) EMSG(_(e_funcref)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); EMSG(_(e_trailing)); return; } eap->nextcmd = check_nextcmd(p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip) fp = find_func(name); vim_free(name); if (!eap->skip) { if (fp == NULL) { EMSG2(_(e_nofunc), eap->arg); return; } if (fp->uf_calls > 0) { EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg); return; } if (fudi.fd_dict != NULL) { /* Delete the dict item that refers to the function, it will * invoke func_unref() and possibly delete the function. */ dictitem_remove(fudi.fd_dict, fudi.fd_di); } else func_free(fp); } } /* * Free a function and remove it from the list of functions. */ static void func_free(fp) ufunc_T *fp; { hashitem_T *hi; /* clear this function */ ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_lines)); #ifdef FEAT_PROFILE vim_free(fp->uf_tml_count); vim_free(fp->uf_tml_total); vim_free(fp->uf_tml_self); #endif /* remove the function from the function hashtable */ hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (HASHITEM_EMPTY(hi)) EMSG2(_(e_intern2), "func_free()"); else hash_remove(&func_hashtab, hi); vim_free(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. Only for numbered functions. */ static void func_unref(name) char_u *name; { ufunc_T *fp; if (name != NULL && isdigit(*name)) { fp = find_func(name); if (fp == NULL) EMSG2(_(e_intern2), "func_unref()"); else if (--fp->uf_refcount <= 0) { /* Only delete it when it's not being used. Otherwise it's done * when "uf_calls" becomes zero. */ if (fp->uf_calls == 0) func_free(fp); } } } /* * Count a reference to a Function. */ static void func_ref(name) char_u *name; { ufunc_T *fp; if (name != NULL && isdigit(*name)) { fp = find_func(name); if (fp == NULL) EMSG2(_(e_intern2), "func_ref()"); else ++fp->uf_refcount; } } /* * Call a user function. */ static void call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict) ufunc_T *fp; /* pointer to function */ int argcount; /* nr of args */ typval_T *argvars; /* arguments */ typval_T *rettv; /* return value */ linenr_T firstline; /* first line of range */ linenr_T lastline; /* last line of range */ dict_T *selfdict; /* Dictionary for "self" */ { char_u *save_sourcing_name; linenr_T save_sourcing_lnum; scid_T save_current_SID; funccall_T *fc; int save_did_emsg; static int depth = 0; dictitem_T *v; int fixvar_idx = 0; /* index in fixvar[] */ int i; int ai; char_u numbuf[NUMBUFLEN]; char_u *name; #ifdef FEAT_PROFILE proftime_T wait_start; proftime_T call_start; #endif /* If depth of calling is getting too high, don't execute the function */ if (depth >= p_mfd) { EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'")); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } ++depth; line_breakcheck(); /* check for CTRL-C hit */ fc = (funccall_T *)alloc(sizeof(funccall_T)); fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; rettv->vval.v_number = 0; fc->linenr = 0; fc->returned = FALSE; fc->level = ex_nesting_level; /* Check if this function has a breakpoint. */ fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var); if (selfdict != NULL) { /* Set l:self to "selfdict". Use "name" to avoid a warning from * some compiler that checks the destination size. */ v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables. * Set a:0 to "argcount". * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount - fp->uf_args.ga_len)); /* Use "name" to avoid a warning from some compiler that checks the * destination size. */ v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; vim_memset(&fc->l_varlist, 0, sizeof(list_T)); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. */ add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)lastline); for (i = 0; i < argcount; ++i) { ai = i - fp->uf_args.ga_len; if (ai < 0) /* named argument a:name */ name = FUNCARG(fp, i); else { /* "..." argument a:1, a:2, etc. */ sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; } else { v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(name))); if (v == NULL) break; v->di_flags = DI_FLAGS_RO; } STRCPY(v->di_key, name); hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); /* Note: the values are copied directly to avoid alloc/free. * "argvars" must have VAR_FIXED for v_lock. */ v->di_tv = argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (ai >= 0 && ai < MAX_FUNC_ARGS) { list_append(&fc->l_varlist, &fc->l_listitems[ai]); fc->l_listitems[ai].li_tv = argvars[i]; fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED; } } /* Don't redraw while executing the function. */ ++RedrawingDisabled; save_sourcing_name = sourcing_name; save_sourcing_lnum = sourcing_lnum; sourcing_lnum = 1; sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13)); if (sourcing_name != NULL) { if (save_sourcing_name != NULL && STRNCMP(save_sourcing_name, "function ", 9) == 0) sprintf((char *)sourcing_name, "%s..", save_sourcing_name); else STRCPY(sourcing_name, "function "); cat_func_name(sourcing_name + STRLEN(sourcing_name), fp); if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg((char_u *)_("calling %s"), sourcing_name); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts((char_u *)"("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts((char_u *)", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { s = tv2string(&argvars[i], &tofree, numbuf2, 0); if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts(s); vim_free(tofree); } } } msg_puts((char_u *)")"); } msg_puts((char_u *)"\n"); /* don't overwrite this either */ verbose_leave_scroll(); --no_wait_return; } } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL)) func_do_profile(fp); if (fp->uf_profiling || (fc->caller != NULL && fc->caller->func->uf_profiling)) { ++fp->uf_tm_count; profile_start(&call_start); profile_zero(&fp->uf_tm_children); } script_prof_save(&wait_start); } #endif save_current_SID = current_SID; current_SID = fp->uf_script_ID; save_did_emsg = did_emsg; did_emsg = FALSE; /* call do_cmdline() to execute the lines */ do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; /* when the function was aborted because of an error, return -1 */ if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (fc->caller != NULL && fc->caller->func->uf_profiling))) { profile_end(&call_start); profile_sub_wait(&wait_start, &call_start); profile_add(&fp->uf_tm_total, &call_start); profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children); if (fc->caller != NULL && fc->caller->func->uf_profiling) { profile_add(&fc->caller->func->uf_tm_children, &call_start); profile_add(&fc->caller->func->uf_tml_children, &call_start); } } #endif /* when being verbose, mention the return value */ if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg((char_u *)_("%s aborted"), sourcing_name); else if (fc->rettv->v_type == VAR_NUMBER) smsg((char_u *)_("%s returning #%ld"), sourcing_name, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; /* The value may be very long. Skip the middle part, so that we * have some idea how it starts and ends. smsg() would always * truncate it at the end. */ s = tv2string(fc->rettv, &tofree, numbuf2, 0); if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg((char_u *)_("%s returning %s"), sourcing_name, s); vim_free(tofree); } } msg_puts((char_u *)"\n"); /* don't overwrite this either */ verbose_leave_scroll(); --no_wait_return; } vim_free(sourcing_name); sourcing_name = save_sourcing_name; sourcing_lnum = save_sourcing_lnum; current_SID = save_current_SID; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&wait_start); #endif if (p_verbose >= 12 && sourcing_name != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg((char_u *)_("continuing in %s"), sourcing_name); msg_puts((char_u *)"\n"); /* don't overwrite this either */ verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; current_funccal = fc->caller; --depth; /* If the a:000 list and the l: and a: dicts are not referenced we can * free the funccall_T and what's in it. */ if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) { free_funccal(fc, FALSE); } else { hashitem_T *hi; listitem_T *li; int todo; /* "fc" is still in use. This can happen when returning "a:000" or * assigning "l:" to a global variable. * Link "fc" in the list for garbage collection later. */ fc->caller = previous_funccal; previous_funccal = fc; /* Make a copy of the a: variables, since we didn't do that above. */ todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; v = HI2DI(hi); copy_tv(&v->di_tv, &v->di_tv); } } /* Make a copy of the a:000 items, since we didn't do that above. */ for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next) copy_tv(&li->li_tv, &li->li_tv); } } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(fc, copyID) funccall_T *fc; int copyID; { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID); } /* * Free "fc" and what it contains. */ static void free_funccal(fc, free_val) funccall_T *fc; int free_val; /* a: vars were allocated */ { listitem_T *li; /* The a: variables typevals may not have been allocated, only free the * allocated variables. */ vars_clear_ext(&fc->l_avars.dv_hashtab, free_val); /* free all l: variables */ vars_clear(&fc->l_vars.dv_hashtab); /* Free the a:000 variables if they were allocated. */ if (free_val) for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next) clear_tv(&li->li_tv); vim_free(fc); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var(dp, v, name, nr) dict_T *dp; dictitem_T *v; char *name; varnumber_T nr; { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * ":return [expr]" */ void ex_return(eap) exarg_T *eap; { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; if (current_funccal == NULL) { EMSG(_("E133: :return not inside a function")); return; } if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } /* It's safer to return also on error. */ else if (!eap->skip) { /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } /* When skipping or the return gets pending, advance to the next command * in this line (!returning). Otherwise, ignore the rest of the line. * Following lines will be ignored by get_func_line(). */ if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) /* no argument */ eap->nextcmd = check_nextcmd(arg); if (eap->skip) --emsg_skip; } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return(eap, reanimate, is_cmd, rettv) exarg_T *eap; int reanimate; int is_cmd; void *rettv; { int idx; struct condstack *cstack = eap->cstack; if (reanimate) /* Undo the return. */ current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) /* A pending return again gets pending. "rettv" points to an * allocated variable with the rettv of the original ":return"'s * argument if present or is NULL else. */ cstack->cs_rettv[idx] = rettv; else { /* When undoing a return in order to make it pending, get the stored * return rettv. */ if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { /* Store the value of the pending return. */ if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else EMSG(_(e_outofmem)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { /* The pending return value could be overwritten by a ":return" * without argument in a finally clause; reset the default * return value. */ current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; /* If the return is carried out now, store the return value. For * a return immediately after reanimation, the value is already * there. */ if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(rettv) void *rettv; { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(rettv) void *rettv; { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line(c, cookie, indent) int c UNUSED; void *cookie; int indent UNUSED; { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; /* growarray with function lines */ /* If breakpoints have been added/deleted need to check for it. */ if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, sourcing_lnum); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { /* Skip NULL lines (continuation lines). */ while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); sourcing_lnum = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie); #endif } } /* Did we encounter a breakpoint? */ if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum) { dbg_breakpoint(fp->uf_name, sourcing_lnum); /* Find next breakpoint. */ fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, sourcing_lnum); fcp->dbg_tick = debug_tick; } return retval; } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Called when starting to read a function line. * "sourcing_lnum" must be correct! * When skipping lines it may not actually be executed, but we won't find out * until later and we need to store the time now. */ void func_line_start(cookie) void *cookie; { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; if (fp->uf_profiling && sourcing_lnum >= 1 && sourcing_lnum <= fp->uf_lines.ga_len) { fp->uf_tml_idx = sourcing_lnum - 1; /* Skip continuation lines. */ while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL) --fp->uf_tml_idx; fp->uf_tml_execed = FALSE; profile_start(&fp->uf_tml_start); profile_zero(&fp->uf_tml_children); profile_get_wait(&fp->uf_tml_wait); } } /* * Called when actually executing a function line. */ void func_line_exec(cookie) void *cookie; { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; if (fp->uf_profiling && fp->uf_tml_idx >= 0) fp->uf_tml_execed = TRUE; } /* * Called when done with a function line. */ void func_line_end(cookie) void *cookie; { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; if (fp->uf_profiling && fp->uf_tml_idx >= 0) { if (fp->uf_tml_execed) { ++fp->uf_tml_count[fp->uf_tml_idx]; profile_end(&fp->uf_tml_start); profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start); profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start); profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start, &fp->uf_tml_children); } fp->uf_tml_idx = -1; } } #endif /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(cookie) void *cookie; { funccall_T *fcp = (funccall_T *)cookie; /* Ignore the "abort" flag if the abortion behavior has been changed due to * an error inside a try conditional. */ return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort(cookie) void *cookie; { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION) typedef enum { VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */ VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */ VAR_FLAVOUR_VIMINFO /* all uppercase */ } var_flavour_T; static var_flavour_T var_flavour __ARGS((char_u *varname)); static var_flavour_T var_flavour(varname) char_u *varname; { char_u *p = varname; if (ASCII_ISUPPER(*p)) { while (*(++p)) if (ASCII_ISLOWER(*p)) return VAR_FLAVOUR_SESSION; return VAR_FLAVOUR_VIMINFO; } else return VAR_FLAVOUR_DEFAULT; } #endif #if defined(FEAT_VIMINFO) || defined(PROTO) /* * Restore global vars that start with a capital from the viminfo file */ int read_viminfo_varlist(virp, writing) vir_T *virp; int writing; { char_u *tab; int type = VAR_NUMBER; typval_T tv; if (!writing && (find_viminfo_parameter('!') != NULL)) { tab = vim_strchr(virp->vir_line + 1, '\t'); if (tab != NULL) { *tab++ = '\0'; /* isolate the variable name */ switch (*tab) { case 'S': type = VAR_STRING; break; #ifdef FEAT_FLOAT case 'F': type = VAR_FLOAT; break; #endif case 'D': type = VAR_DICT; break; case 'L': type = VAR_LIST; break; } tab = vim_strchr(tab, '\t'); if (tab != NULL) { tv.v_type = type; if (type == VAR_STRING || type == VAR_DICT || type == VAR_LIST) tv.vval.v_string = viminfo_readstring(virp, (int)(tab - virp->vir_line + 1), TRUE); #ifdef FEAT_FLOAT else if (type == VAR_FLOAT) (void)string2float(tab + 1, &tv.vval.v_float); #endif else tv.vval.v_number = atol((char *)tab + 1); if (type == VAR_DICT || type == VAR_LIST) { typval_T *etv = eval_expr(tv.vval.v_string, NULL); if (etv == NULL) /* Failed to parse back the dict or list, use it as a * string. */ tv.v_type = VAR_STRING; else { vim_free(tv.vval.v_string); tv = *etv; vim_free(etv); } } set_var(virp->vir_line + 1, &tv, FALSE); if (tv.v_type == VAR_STRING) vim_free(tv.vval.v_string); else if (tv.v_type == VAR_DICT || tv.v_type == VAR_LIST) clear_tv(&tv); } } } return viminfo_readline(virp); } /* * Write global vars that start with a capital to the viminfo file */ void write_viminfo_varlist(fp) FILE *fp; { hashitem_T *hi; dictitem_T *this_var; int todo; char *s; char_u *p; char_u *tofree; char_u numbuf[NUMBUFLEN]; if (find_viminfo_parameter('!') == NULL) return; fputs(_("\n# global variables:\n"), fp); todo = (int)globvarht.ht_used; for (hi = globvarht.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; this_var = HI2DI(hi); if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO) { switch (this_var->di_tv.v_type) { case VAR_STRING: s = "STR"; break; case VAR_NUMBER: s = "NUM"; break; #ifdef FEAT_FLOAT case VAR_FLOAT: s = "FLO"; break; #endif case VAR_DICT: s = "DIC"; break; case VAR_LIST: s = "LIS"; break; default: continue; } fprintf(fp, "!%s\t%s\t", this_var->di_key, s); p = echo_string(&this_var->di_tv, &tofree, numbuf, 0); if (p != NULL) viminfo_writestring(fp, p); vim_free(tofree); } } } } #endif #if defined(FEAT_SESSION) || defined(PROTO) int store_session_globals(fd) FILE *fd; { hashitem_T *hi; dictitem_T *this_var; int todo; char_u *p, *t; todo = (int)globvarht.ht_used; for (hi = globvarht.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; this_var = HI2DI(hi); if ((this_var->di_tv.v_type == VAR_NUMBER || this_var->di_tv.v_type == VAR_STRING) && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION) { /* Escape special characters with a backslash. Turn a LF and * CR into \n and \r. */ p = vim_strsave_escaped(get_tv_string(&this_var->di_tv), (char_u *)"\\\"\n\r"); if (p == NULL) /* out of memory */ break; for (t = p; *t != NUL; ++t) if (*t == '\n') *t = 'n'; else if (*t == '\r') *t = 'r'; if ((fprintf(fd, "let %s = %c%s%c", this_var->di_key, (this_var->di_tv.v_type == VAR_STRING) ? '"' : ' ', p, (this_var->di_tv.v_type == VAR_STRING) ? '"' : ' ') < 0) || put_eol(fd) == FAIL) { vim_free(p); return FAIL; } vim_free(p); } #ifdef FEAT_FLOAT else if (this_var->di_tv.v_type == VAR_FLOAT && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION) { float_T f = this_var->di_tv.vval.v_float; int sign = ' '; if (f < 0) { f = -f; sign = '-'; } if ((fprintf(fd, "let %s = %c%f", this_var->di_key, sign, f) < 0) || put_eol(fd) == FAIL) return FAIL; } #endif } } return OK; } #endif /* * Display script name where an item was last set. * Should only be invoked when 'verbose' is non-zero. */ void last_set_msg(scriptID) scid_T scriptID; { char_u *p; if (scriptID != 0) { p = home_replace_save(NULL, get_scriptname(scriptID)); if (p != NULL) { verbose_enter(); MSG_PUTS(_("\n\tLast set from ")); MSG_PUTS(p); vim_free(p); verbose_leave(); } } } /* * List v:oldfiles in a nice way. */ void ex_oldfiles(eap) exarg_T *eap UNUSED; { list_T *l = vimvars[VV_OLDFILES].vv_list; listitem_T *li; int nr = 0; if (l == NULL) msg((char_u *)_("No old files")); else { msg_start(); msg_scroll = TRUE; for (li = l->lv_first; li != NULL && !got_int; li = li->li_next) { msg_outnum((long)++nr); MSG_PUTS(": "); msg_outtrans(get_tv_string(&li->li_tv)); msg_putchar('\n'); out_flush(); /* output one line at a time */ ui_breakcheck(); } /* Assume "got_int" was set to truncate the listing. */ got_int = FALSE; #ifdef FEAT_BROWSE_CMD if (cmdmod.browse) { quit_more = FALSE; nr = prompt_for_number(FALSE); msg_starthere(); if (nr > 0) { char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES), (long)nr); if (p != NULL) { p = expand_env_save(p); eap->arg = p; eap->cmdidx = CMD_edit; cmdmod.browse = FALSE; do_exedit(eap, NULL); vim_free(p); } } } #endif } } #endif /* FEAT_EVAL */ #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO) #ifdef WIN3264 /* * Functions for ":8" filename modifier: get 8.3 version of a filename. */ static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen)); static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen)); static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen)); /* * Get the short path (8.3) for the filename in "fnamep". * Only works for a valid file name. * When the path gets longer "fnamep" is changed and the allocated buffer * is put in "bufp". * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path. * Returns OK on success, FAIL on failure. */ static int get_short_pathname(fnamep, bufp, fnamelen) char_u **fnamep; char_u **bufp; int *fnamelen; { int l, len; char_u *newbuf; len = *fnamelen; l = GetShortPathName(*fnamep, *fnamep, len); if (l > len - 1) { /* If that doesn't work (not enough space), then save the string * and try again with a new buffer big enough. */ newbuf = vim_strnsave(*fnamep, l); if (newbuf == NULL) return FAIL; vim_free(*bufp); *fnamep = *bufp = newbuf; /* Really should always succeed, as the buffer is big enough. */ l = GetShortPathName(*fnamep, *fnamep, l+1); } *fnamelen = l; return OK; } /* * Get the short path (8.3) for the filename in "fname". The converted * path is returned in "bufp". * * Some of the directories specified in "fname" may not exist. This function * will shorten the existing directories at the beginning of the path and then * append the remaining non-existing path. * * fname - Pointer to the filename to shorten. On return, contains the * pointer to the shortened pathname * bufp - Pointer to an allocated buffer for the filename. * fnamelen - Length of the filename pointed to by fname * * Returns OK on success (or nothing done) and FAIL on failure (out of memory). */ static int shortpath_for_invalid_fname(fname, bufp, fnamelen) char_u **fname; char_u **bufp; int *fnamelen; { char_u *short_fname, *save_fname, *pbuf_unused; char_u *endp, *save_endp; char_u ch; int old_len, len; int new_len, sfx_len; int retval = OK; /* Make a copy */ old_len = *fnamelen; save_fname = vim_strnsave(*fname, old_len); pbuf_unused = NULL; short_fname = NULL; endp = save_fname + old_len - 1; /* Find the end of the copy */ save_endp = endp; /* * Try shortening the supplied path till it succeeds by removing one * directory at a time from the tail of the path. */ len = 0; for (;;) { /* go back one path-separator */ while (endp > save_fname && !after_pathsep(save_fname, endp + 1)) --endp; if (endp <= save_fname) break; /* processed the complete path */ /* * Replace the path separator with a NUL and try to shorten the * resulting path. */ ch = *endp; *endp = 0; short_fname = save_fname; len = (int)STRLEN(short_fname) + 1; if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL) { retval = FAIL; goto theend; } *endp = ch; /* preserve the string */ if (len > 0) break; /* successfully shortened the path */ /* failed to shorten the path. Skip the path separator */ --endp; } if (len > 0) { /* * Succeeded in shortening the path. Now concatenate the shortened * path with the remaining path at the tail. */ /* Compute the length of the new path. */ sfx_len = (int)(save_endp - endp) + 1; new_len = len + sfx_len; *fnamelen = new_len; vim_free(*bufp); if (new_len > old_len) { /* There is not enough space in the currently allocated string, * copy it to a buffer big enough. */ *fname = *bufp = vim_strnsave(short_fname, new_len); if (*fname == NULL) { retval = FAIL; goto theend; } } else { /* Transfer short_fname to the main buffer (it's big enough), * unless get_short_pathname() did its work in-place. */ *fname = *bufp = save_fname; if (short_fname != save_fname) vim_strncpy(save_fname, short_fname, len); save_fname = NULL; } /* concat the not-shortened part of the path */ vim_strncpy(*fname + len, endp, sfx_len); (*fname)[new_len] = NUL; } theend: vim_free(pbuf_unused); vim_free(save_fname); return retval; } /* * Get a pathname for a partial path. * Returns OK for success, FAIL for failure. */ static int shortpath_for_partial(fnamep, bufp, fnamelen) char_u **fnamep; char_u **bufp; int *fnamelen; { int sepcount, len, tflen; char_u *p; char_u *pbuf, *tfname; int hasTilde; /* Count up the path separators from the RHS.. so we know which part * of the path to return. */ sepcount = 0; for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p)) if (vim_ispathsep(*p)) ++sepcount; /* Need full path first (use expand_env() to remove a "~/") */ hasTilde = (**fnamep == '~'); if (hasTilde) pbuf = tfname = expand_env_save(*fnamep); else pbuf = tfname = FullName_save(*fnamep, FALSE); len = tflen = (int)STRLEN(tfname); if (get_short_pathname(&tfname, &pbuf, &len) == FAIL) return FAIL; if (len == 0) { /* Don't have a valid filename, so shorten the rest of the * path if we can. This CAN give us invalid 8.3 filenames, but * there's not a lot of point in guessing what it might be. */ len = tflen; if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL) return FAIL; } /* Count the paths backward to find the beginning of the desired string. */ for (p = tfname + len - 1; p >= tfname; --p) { #ifdef FEAT_MBYTE if (has_mbyte) p -= mb_head_off(tfname, p); #endif if (vim_ispathsep(*p)) { if (sepcount == 0 || (hasTilde && sepcount == 1)) break; else sepcount --; } } if (hasTilde) { --p; if (p >= tfname) *p = '~'; else return FAIL; } else ++p; /* Copy in the string - p indexes into tfname - allocated at pbuf */ vim_free(*bufp); *fnamelen = (int)STRLEN(p); *bufp = pbuf; *fnamep = p; return OK; } #endif /* WIN3264 */ /* * Adjust a filename, according to a string of modifiers. * *fnamep must be NUL terminated when called. When returning, the length is * determined by *fnamelen. * Returns VALID_ flags or -1 for failure. * When there is an error, *fnamep is set to NULL. */ int modify_fname(src, usedlen, fnamep, bufp, fnamelen) char_u *src; /* string with modifiers */ int *usedlen; /* characters after src that are used */ char_u **fnamep; /* file name so far */ char_u **bufp; /* buffer for allocated file name or NULL */ int *fnamelen; /* length of fnamep */ { int valid = 0; char_u *tail; char_u *s, *p, *pbuf; char_u dirname[MAXPATHL]; int c; int has_fullname = 0; #ifdef WIN3264 char_u *fname_start = *fnamep; int has_shortname = 0; #endif repeat: /* ":p" - full path/file_name */ if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p') { has_fullname = 1; valid |= VALID_PATH; *usedlen += 2; /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */ if ((*fnamep)[0] == '~' #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME)) && ((*fnamep)[1] == '/' # ifdef BACKSLASH_IN_FILENAME || (*fnamep)[1] == '\\' # endif || (*fnamep)[1] == NUL) #endif ) { *fnamep = expand_env_save(*fnamep); vim_free(*bufp); /* free any allocated file name */ *bufp = *fnamep; if (*fnamep == NULL) return -1; } /* When "/." or "/.." is used: force expansion to get rid of it. */ for (p = *fnamep; *p != NUL; mb_ptr_adv(p)) { if (vim_ispathsep(*p) && p[1] == '.' && (p[2] == NUL || vim_ispathsep(p[2]) || (p[2] == '.' && (p[3] == NUL || vim_ispathsep(p[3]))))) break; } /* FullName_save() is slow, don't use it when not needed. */ if (*p != NUL || !vim_isAbsName(*fnamep)) { *fnamep = FullName_save(*fnamep, *p != NUL); vim_free(*bufp); /* free any allocated file name */ *bufp = *fnamep; if (*fnamep == NULL) return -1; } #ifdef WIN3264 # if _WIN32_WINNT >= 0x0500 if (vim_strchr(*fnamep, '~') != NULL) { /* Expand 8.3 filename to full path. Needed to make sure the same * file does not have two different names. * Note: problem does not occur if _WIN32_WINNT < 0x0500. */ p = alloc(_MAX_PATH + 1); if (p != NULL) { if (GetLongPathName(*fnamep, p, MAXPATHL)) { vim_free(*bufp); *bufp = *fnamep = p; } else vim_free(p); } } # endif #endif /* Append a path separator to a directory. */ if (mch_isdir(*fnamep)) { /* Make room for one or two extra characters. */ *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2); vim_free(*bufp); /* free any allocated file name */ *bufp = *fnamep; if (*fnamep == NULL) return -1; add_pathsep(*fnamep); } } /* ":." - path relative to the current directory */ /* ":~" - path relative to the home directory */ /* ":8" - shortname path - postponed till after */ while (src[*usedlen] == ':' && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8')) { *usedlen += 2; if (c == '8') { #ifdef WIN3264 has_shortname = 1; /* Postpone this. */ #endif continue; } pbuf = NULL; /* Need full path first (use expand_env() to remove a "~/") */ if (!has_fullname) { if (c == '.' && **fnamep == '~') p = pbuf = expand_env_save(*fnamep); else p = pbuf = FullName_save(*fnamep, FALSE); } else p = *fnamep; has_fullname = 0; if (p != NULL) { if (c == '.') { mch_dirname(dirname, MAXPATHL); s = shorten_fname(p, dirname); if (s != NULL) { *fnamep = s; if (pbuf != NULL) { vim_free(*bufp); /* free any allocated file name */ *bufp = pbuf; pbuf = NULL; } } } else { home_replace(NULL, p, dirname, MAXPATHL, TRUE); /* Only replace it when it starts with '~' */ if (*dirname == '~') { s = vim_strsave(dirname); if (s != NULL) { *fnamep = s; vim_free(*bufp); *bufp = s; } } } vim_free(pbuf); } } tail = gettail(*fnamep); *fnamelen = (int)STRLEN(*fnamep); /* ":h" - head, remove "/file_name", can be repeated */ /* Don't remove the first "/" or "c:\" */ while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h') { valid |= VALID_HEAD; *usedlen += 2; s = get_past_head(*fnamep); while (tail > s && after_pathsep(s, tail)) mb_ptr_back(*fnamep, tail); *fnamelen = (int)(tail - *fnamep); #ifdef VMS if (*fnamelen > 0) *fnamelen += 1; /* the path separator is part of the path */ #endif if (*fnamelen == 0) { /* Result is empty. Turn it into "." to make ":cd %:h" work. */ p = vim_strsave((char_u *)"."); if (p == NULL) return -1; vim_free(*bufp); *bufp = *fnamep = tail = p; *fnamelen = 1; } else { while (tail > s && !after_pathsep(s, tail)) mb_ptr_back(*fnamep, tail); } } /* ":8" - shortname */ if (src[*usedlen] == ':' && src[*usedlen + 1] == '8') { *usedlen += 2; #ifdef WIN3264 has_shortname = 1; #endif } #ifdef WIN3264 /* * Handle ":8" after we have done 'heads' and before we do 'tails'. */ if (has_shortname) { /* Copy the string if it is shortened by :h and when it wasn't copied * yet, because we are going to change it in place. Avoids changing * the buffer name for "%:8". */ if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start) { p = vim_strnsave(*fnamep, *fnamelen); if (p == NULL) return -1; vim_free(*bufp); *bufp = *fnamep = p; } /* Split into two implementations - makes it easier. First is where * there isn't a full name already, second is where there is. */ if (!has_fullname && !vim_isAbsName(*fnamep)) { if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL) return -1; } else { int l = *fnamelen; /* Simple case, already have the full-name. * Nearly always shorter, so try first time. */ if (get_short_pathname(fnamep, bufp, &l) == FAIL) return -1; if (l == 0) { /* Couldn't find the filename, search the paths. */ l = *fnamelen; if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL) return -1; } *fnamelen = l; } } #endif /* WIN3264 */ /* ":t" - tail, just the basename */ if (src[*usedlen] == ':' && src[*usedlen + 1] == 't') { *usedlen += 2; *fnamelen -= (int)(tail - *fnamep); *fnamep = tail; } /* ":e" - extension, can be repeated */ /* ":r" - root, without extension, can be repeated */ while (src[*usedlen] == ':' && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r')) { /* find a '.' in the tail: * - for second :e: before the current fname * - otherwise: The last '.' */ if (src[*usedlen + 1] == 'e' && *fnamep > tail) s = *fnamep - 2; else s = *fnamep + *fnamelen - 1; for ( ; s > tail; --s) if (s[0] == '.') break; if (src[*usedlen + 1] == 'e') /* :e */ { if (s > tail) { *fnamelen += (int)(*fnamep - (s + 1)); *fnamep = s + 1; #ifdef VMS /* cut version from the extension */ s = *fnamep + *fnamelen - 1; for ( ; s > *fnamep; --s) if (s[0] == ';') break; if (s > *fnamep) *fnamelen = s - *fnamep; #endif } else if (*fnamep <= tail) *fnamelen = 0; } else /* :r */ { if (s > tail) /* remove one extension */ *fnamelen = (int)(s - *fnamep); } *usedlen += 2; } /* ":s?pat?foo?" - substitute */ /* ":gs?pat?foo?" - global substitute */ if (src[*usedlen] == ':' && (src[*usedlen + 1] == 's' || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's'))) { char_u *str; char_u *pat; char_u *sub; int sep; char_u *flags; int didit = FALSE; flags = (char_u *)""; s = src + *usedlen + 2; if (src[*usedlen + 1] == 'g') { flags = (char_u *)"g"; ++s; } sep = *s++; if (sep) { /* find end of pattern */ p = vim_strchr(s, sep); if (p != NULL) { pat = vim_strnsave(s, (int)(p - s)); if (pat != NULL) { s = p + 1; /* find end of substitution */ p = vim_strchr(s, sep); if (p != NULL) { sub = vim_strnsave(s, (int)(p - s)); str = vim_strnsave(*fnamep, *fnamelen); if (sub != NULL && str != NULL) { *usedlen = (int)(p + 1 - src); s = do_string_sub(str, pat, sub, flags); if (s != NULL) { *fnamep = s; *fnamelen = (int)STRLEN(s); vim_free(*bufp); *bufp = s; didit = TRUE; } } vim_free(sub); vim_free(str); } vim_free(pat); } } /* after using ":s", repeat all the modifiers */ if (didit) goto repeat; } } return valid; } /* * Perform a substitution on "str" with pattern "pat" and substitute "sub". * "flags" can be "g" to do a global substitute. * Returns an allocated string, NULL for error. */ char_u * do_string_sub(str, pat, sub, flags) char_u *str; char_u *pat; char_u *sub; char_u *flags; { int sublen; regmatch_T regmatch; int i; int do_all; char_u *tail; garray_T ga; char_u *ret; char_u *save_cpo; /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */ save_cpo = p_cpo; p_cpo = empty_option; ga_init2(&ga, 1, 200); do_all = (flags[0] == 'g'); regmatch.rm_ic = p_ic; regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING); if (regmatch.regprog != NULL) { tail = str; while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str))) { /* * Get some space for a temporary buffer to do the substitution * into. It will contain: * - The text up to where the match is. * - The substituted text. * - The text after the match. */ sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE); if (ga_grow(&ga, (int)(STRLEN(tail) + sublen - (regmatch.endp[0] - regmatch.startp[0]))) == FAIL) { ga_clear(&ga); break; } /* copy the text up to where the match is */ i = (int)(regmatch.startp[0] - tail); mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i); /* add the substituted text */ (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data + ga.ga_len + i, TRUE, TRUE, FALSE); ga.ga_len += i + sublen - 1; /* avoid getting stuck on a match with an empty string */ if (tail == regmatch.endp[0]) { if (*tail == NUL) break; *((char_u *)ga.ga_data + ga.ga_len) = *tail++; ++ga.ga_len; } else { tail = regmatch.endp[0]; if (*tail == NUL) break; } if (!do_all) break; } if (ga.ga_data != NULL) STRCPY((char *)ga.ga_data + ga.ga_len, tail); vim_free(regmatch.regprog); } ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data); ga_clear(&ga); if (p_cpo == empty_option) p_cpo = save_cpo; else /* Darn, evaluating {sub} expression changed the value. */ free_string_option(save_cpo); return ret; } #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */
zyz2011-vim
src/eval.c
C
gpl2
541,230
# The most simplistic Makefile for Win32 (NT and Windows 95). # Used for Borland C++. !if ("$(BOR)"=="") BOR = c:\bc5 !endif !if ("$(BCC)"=="") BCC = bcc32 !endif xxd: xxd.exe xxd.exe: xxd.c $(BCC) -I$(BOR)\include -L$(BOR)\lib -DWIN32 xxd.c $(BOR)\lib\wildargs.obj clean: - del xxd.obj - del xxd.exe
zyz2011-vim
src/xxd/Make_bc5.mak
Makefile
gpl2
308
# The most simplistic Makefile, for MinGW gcc on MS-DOS ifndef USEDLL USEDLL = no endif ifeq (yes, $(USEDLL)) DEFINES = LIBS = -lc else DEFINES = LIBS = endif CC = gcc CFLAGS = -O2 -Wall -DWIN32 $(DEFINES) ifneq (sh.exe, $(SHELL)) DEL = rm else DEL = del endif xxd.exe: xxd.c $(CC) $(CFLAGS) -s -o xxd.exe xxd.c $(LIBS) clean: -$(DEL) xxd.exe
zyz2011-vim
src/xxd/Make_ming.mak
Makefile
gpl2
357
# VMS MM[KS] makefile for XXD # tested with MMK and MMS as well. # # Maintained by Zoltan Arpadffy <arpadffy@polarhome.com> # # Edit the lines in the Configuration section below to select. # # To build: use the following command line: # # mms/descrip=Make_vms.mms # or if you use mmk # mmk/descrip=Make_vms.mms # ###################################################################### # Configuration section. ###################################################################### # Compiler selection. # Comment out if you use the VAXC compiler ###################################################################### # DECC = YES ##################################################################### # Uncomment if want a debug version. Resulting executable is DVIM.EXE ###################################################################### # DEBUG = YES ###################################################################### # End of configuration section. # # Please, do not change anything below without programming experience. ###################################################################### CC = cc .IFDEF DECC CC_DEF = $(CC)/decc PREFIX = /prefix=all .ELSE CC_DEF = $(CC) PREFIX = .ENDIF LD_DEF = link .IFDEF DEBUG TARGET = dxxd.exe CFLAGS = /debug/noopt$(PREFIX)/cross_reference/include=[] LDFLAGS = /debug .ELSE TARGET = xxd.exe CFLAGS = /opt$(PREFIX)/include=[] LDFLAGS = .ENDIF .SUFFIXES : .obj .c SOURCES = xxd.c OBJ = xxd.obj .obj.c : $(CC_DEF) $(CFLAGS) $< $(TARGET) : $(OBJ) $(LD_DEF) $(LDFLAGS) /exe=$(TARGET) $+ clean : -@ if "''F$SEARCH("*.obj")'" .NES. "" then delete/noconfirm/nolog *.obj;* -@ if "''F$SEARCH("*.exe")'" .NES. "" then delete/noconfirm/nolog *.exe;*
zyz2011-vim
src/xxd/Make_vms.mms
Module Management System
gpl2
1,727
# Makefile for xxd on the Amiga, using Aztec/Manx C 5.0 or later # #>>>>> choose between debugging (-bs) or optimizing (-so) OPTIONS = -so #OPTIONS = -bs #>>>>>> choose -g for debugging LN_DEBUG = #LN_DEBUG = -g CFLAGS = $(OPTIONS) -wapruq -ps -qf -DAMIGA -Dconst= Xxd: xxd.o ln +q -m $(LN_DEBUG) -o Xxd xxd.o -lc16 xxd.o: xxd.c cc $(CFLAGS) xxd.c -o xxd.o
zyz2011-vim
src/xxd/Make_amiga.mak
Makefile
gpl2
364
# The most simplistic Makefile xxd: xxd.c $(CC) $(CFLAGS) $(LDFLAGS) -DUNIX -o xxd xxd.c clean: rm -f xxd xxd.o
zyz2011-vim
src/xxd/Makefile
Makefile
gpl2
116
# The most simplistic Makefile, for Cygnus gcc on MS-DOS ifndef USEDLL USEDLL = no endif ifeq (yes, $(USEDLL)) DEFINES = LIBS = -lc else DEFINES = -mno-cygwin LIBS = endif CC = gcc CFLAGS = -O2 -Wall -DWIN32 $(DEFINES) ifneq (sh.exe, $(SHELL)) DEL = rm else DEL = del endif xxd.exe: xxd.c $(CC) $(CFLAGS) -s -o xxd.exe xxd.c $(LIBS) clean: -$(DEL) xxd.exe
zyz2011-vim
src/xxd/Make_cyg.mak
Makefile
gpl2
370
/* xxd: my hexdump facility. jw * * 2.10.90 changed to word output * 3.03.93 new indent style, dumb bug inserted and fixed. * -c option, mls * 26.04.94 better option parser, -ps, -l, -s added. * 1.07.94 -r badly needs - as input file. Per default autoskip over * consecutive lines of zeroes, as unix od does. * -a shows them too. * -i dump as c-style #include "file.h" * 1.11.95 if "xxd -i" knows the filename, an 'unsigned char filename_bits[]' * array is written in correct c-syntax. * -s improved, now defaults to absolute seek, relative requires a '+'. * -r improved, now -r -s -0x... is supported. * change/suppress leading '\0' bytes. * -l n improved: stops exactly after n bytes. * -r improved, better handling of partial lines with trailing garbage. * -r improved, now -r -p works again! * -r improved, less flushing, much faster now! (that was silly) * 3.04.96 Per repeated request of a single person: autoskip defaults to off. * 15.05.96 -v added. They want to know the version. * -a fixed, to show last line inf file ends in all zeros. * -u added: Print upper case hex-letters, as preferred by unix bc. * -h added to usage message. Usage message extended. * Now using outfile if specified even in normal mode, aehem. * No longer mixing of ints and longs. May help doze people. * Added binify ioctl for same reason. (Enough Doze stress for 1996!) * 16.05.96 -p improved, removed occasional superfluous linefeed. * 20.05.96 -l 0 fixed. tried to read anyway. * 21.05.96 -i fixed. now honours -u, and prepends __ to numeric filenames. * compile -DWIN32 for NT or W95. George V. Reilly, * -v improved :-) * support --gnuish-longhorn-options * 25.05.96 MAC support added: CodeWarrior already uses ``outline'' in Types.h * which is included by MacHeaders (Axel Kielhorn). Renamed to * xxdline(). * 7.06.96 -i printed 'int' instead of 'char'. *blush* * added Bram's OS2 ifdefs... * 18.07.96 gcc -Wall @ SunOS4 is now slient. * Added osver for MSDOS/DJGPP/WIN32. * 29.08.96 Added size_t to strncmp() for Amiga. * 24.03.97 Windows NT support (Phil Hanna). Clean exit for Amiga WB (Bram) * 02.04.97 Added -E option, to have EBCDIC translation instead of ASCII * (azc10@yahoo.com) * 22.05.97 added -g (group octets) option (jcook@namerica.kla.com). * 23.09.98 nasty -p -r misfeature fixed: slightly wrong output, when -c was * missing or wrong. * 26.09.98 Fixed: 'xxd -i infile outfile' did not truncate outfile. * 27.10.98 Fixed: -g option parser required blank. * option -b added: 01000101 binary output in normal format. * 16.05.00 Added VAXC changes by Stephen P. Wall * 16.05.00 Improved MMS file and merge for VMS by Zoltan Arpadffy * 2011 March Better error handling by Florian Zumbiehl. * 2011 April Formatting by Bram Moolenaar * * (c) 1990-1998 by Juergen Weigert (jnweiger@informatik.uni-erlangen.de) * * Small changes made afterwards by Bram Moolenaar et al. * * Distribute freely and credit me, * make money and share with me, * lose money and don't ask me. */ /* Visual Studio 2005 has 'deprecated' many of the standard CRT functions */ #if _MSC_VER >= 1400 # define _CRT_SECURE_NO_DEPRECATE # define _CRT_NONSTDC_NO_DEPRECATE #endif #if !defined(CYGWIN) && (defined(CYGWIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__)) # define CYGWIN #endif #include <stdio.h> #ifdef VAXC # include <file.h> #else # include <fcntl.h> #endif #ifdef __TSC__ # define MSDOS #endif #if !defined(OS2) && defined(__EMX__) # define OS2 #endif #if defined(MSDOS) || defined(WIN32) || defined(OS2) || defined(__BORLANDC__) \ || defined(CYGWIN) # include <io.h> /* for setmode() */ #else # ifdef UNIX # include <unistd.h> # endif #endif #include <stdlib.h> #include <string.h> /* for strncmp() */ #include <ctype.h> /* for isalnum() */ #if __MWERKS__ && !defined(BEBOX) # include <unix.h> /* for fdopen() on MAC */ #endif #if defined(__BORLANDC__) && __BORLANDC__ <= 0x0410 && !defined(fileno) /* Missing define and prototype grabbed from the BC 4.0 <stdio.h> */ # define fileno(f) ((f)->fd) FILE _FAR *_Cdecl _FARFUNC fdopen(int __handle, char _FAR *__type); #endif /* This corrects the problem of missing prototypes for certain functions * in some GNU installations (e.g. SunOS 4.1.x). * Darren Hiebert <darren@hmi.com> (sparc-sun-sunos4.1.3_U1/2.7.2.2) */ #if defined(__GNUC__) && defined(__STDC__) # ifndef __USE_FIXED_PROTOTYPES__ # define __USE_FIXED_PROTOTYPES__ # endif #endif #ifndef __USE_FIXED_PROTOTYPES__ /* * This is historic and works only if the compiler really has no prototypes: * * Include prototypes for Sun OS 4.x, when using an ANSI compiler. * FILE is defined on OS 4.x, not on 5.x (Solaris). * if __SVR4 is defined (some Solaris versions), don't include this. */ #if defined(sun) && defined(FILE) && !defined(__SVR4) && defined(__STDC__) # define __P(a) a /* excerpt from my sun_stdlib.h */ extern int fprintf __P((FILE *, char *, ...)); extern int fputs __P((char *, FILE *)); extern int _flsbuf __P((unsigned char, FILE *)); extern int _filbuf __P((FILE *)); extern int fflush __P((FILE *)); extern int fclose __P((FILE *)); extern int fseek __P((FILE *, long, int)); extern int rewind __P((FILE *)); extern void perror __P((char *)); # endif #endif extern long int strtol(); extern long int ftell(); char version[] = "xxd V1.10 27oct98 by Juergen Weigert"; #ifdef WIN32 char osver[] = " (Win32)"; #else # ifdef DJGPP char osver[] = " (dos 32 bit)"; # else # ifdef MSDOS char osver[] = " (dos 16 bit)"; # else char osver[] = ""; # endif # endif #endif #if defined(MSDOS) || defined(WIN32) || defined(OS2) # define BIN_READ(yes) ((yes) ? "rb" : "rt") # define BIN_WRITE(yes) ((yes) ? "wb" : "wt") # define BIN_CREAT(yes) ((yes) ? (O_CREAT|O_BINARY) : O_CREAT) # define BIN_ASSIGN(fp, yes) setmode(fileno(fp), (yes) ? O_BINARY : O_TEXT) # define PATH_SEP '\\' #elif defined(CYGWIN) # define BIN_READ(yes) ((yes) ? "rb" : "rt") # define BIN_WRITE(yes) ((yes) ? "wb" : "w") # define BIN_CREAT(yes) ((yes) ? (O_CREAT|O_BINARY) : O_CREAT) # define BIN_ASSIGN(fp, yes) ((yes) ? (void) setmode(fileno(fp), O_BINARY) : (void) (fp)) # define PATH_SEP '/' #else # ifdef VMS # define BIN_READ(dummy) "r" # define BIN_WRITE(dummy) "w" # define BIN_CREAT(dummy) O_CREAT # define BIN_ASSIGN(fp, dummy) fp # define PATH_SEP ']' # define FILE_SEP '.' # else # define BIN_READ(dummy) "r" # define BIN_WRITE(dummy) "w" # define BIN_CREAT(dummy) O_CREAT # define BIN_ASSIGN(fp, dummy) fp # define PATH_SEP '/' # endif #endif /* open has only to arguments on the Mac */ #if __MWERKS__ # define OPEN(name, mode, umask) open(name, mode) #else # define OPEN(name, mode, umask) open(name, mode, umask) #endif #ifdef AMIGA # define STRNCMP(s1, s2, l) strncmp(s1, s2, (size_t)l) #else # define STRNCMP(s1, s2, l) strncmp(s1, s2, l) #endif #ifndef __P # if defined(__STDC__) || defined(MSDOS) || defined(WIN32) || defined(OS2) \ || defined(__BORLANDC__) # define __P(a) a # else # define __P(a) () # endif #endif /* Let's collect some prototypes */ /* CodeWarrior is really picky about missing prototypes */ static void exit_with_usage __P((void)); static void die __P((int)); static int huntype __P((FILE *, FILE *, FILE *, int, int, long)); static void xxdline __P((FILE *, char *, int)); #define TRY_SEEK /* attempt to use lseek, or skip forward by reading */ #define COLS 256 /* change here, if you ever need more columns */ #define LLEN (11 + (9*COLS-1)/1 + COLS + 2) char hexxa[] = "0123456789abcdef0123456789ABCDEF", *hexx = hexxa; /* the different hextypes known by this program: */ #define HEX_NORMAL 0 #define HEX_POSTSCRIPT 1 #define HEX_CINCLUDE 2 #define HEX_BITS 3 /* not hex a dump, but bits: 01111001 */ static char *pname; static void exit_with_usage() { fprintf(stderr, "Usage:\n %s [options] [infile [outfile]]\n", pname); fprintf(stderr, " or\n %s -r [-s [-]offset] [-c cols] [-ps] [infile [outfile]]\n", pname); fprintf(stderr, "Options:\n"); fprintf(stderr, " -a toggle autoskip: A single '*' replaces nul-lines. Default off.\n"); fprintf(stderr, " -b binary digit dump (incompatible with -ps,-i,-r). Default hex.\n"); fprintf(stderr, " -c cols format <cols> octets per line. Default 16 (-i: 12, -ps: 30).\n"); fprintf(stderr, " -E show characters in EBCDIC. Default ASCII.\n"); fprintf(stderr, " -g number of octets per group in normal output. Default 2.\n"); fprintf(stderr, " -h print this summary.\n"); fprintf(stderr, " -i output in C include file style.\n"); fprintf(stderr, " -l len stop after <len> octets.\n"); fprintf(stderr, " -ps output in postscript plain hexdump style.\n"); fprintf(stderr, " -r reverse operation: convert (or patch) hexdump into binary.\n"); fprintf(stderr, " -r -s off revert with <off> added to file positions found in hexdump.\n"); fprintf(stderr, " -s %sseek start at <seek> bytes abs. %sinfile offset.\n", #ifdef TRY_SEEK "[+][-]", "(or +: rel.) "); #else "", ""); #endif fprintf(stderr, " -u use upper case hex letters.\n"); fprintf(stderr, " -v show version: \"%s%s\".\n", version, osver); exit(1); } static void die(ret) int ret; { fprintf(stderr, "%s: ", pname); perror(NULL); exit(ret); } /* * Max. cols binary characters are decoded from the input stream per line. * Two adjacent garbage characters after evaluated data delimit valid data. * Everything up to the next newline is discarded. * * The name is historic and came from 'undo type opt h'. */ static int huntype(fpi, fpo, fperr, cols, hextype, base_off) FILE *fpi, *fpo, *fperr; int cols, hextype; long base_off; { int c, ign_garb = 1, n1 = -1, n2 = 0, n3, p = cols; long have_off = 0, want_off = 0; rewind(fpi); while ((c = getc(fpi)) != EOF) { if (c == '\r') /* Doze style input file? */ continue; /* Allow multiple spaces. This doesn't work when there is normal text * after the hex codes in the last line that looks like hex, thus only * use it for PostScript format. */ if (hextype == HEX_POSTSCRIPT && (c == ' ' || c == '\n' || c == '\t')) continue; n3 = n2; n2 = n1; if (c >= '0' && c <= '9') n1 = c - '0'; else if (c >= 'a' && c <= 'f') n1 = c - 'a' + 10; else if (c >= 'A' && c <= 'F') n1 = c - 'A' + 10; else { n1 = -1; if (ign_garb) continue; } ign_garb = 0; if (p >= cols) { if (!hextype) { if (n1 < 0) { p = 0; continue; } want_off = (want_off << 4) | n1; continue; } else p = 0; } if (base_off + want_off != have_off) { if (fflush(fpo) != 0) die(3); #ifdef TRY_SEEK c = fseek(fpo, base_off + want_off - have_off, 1); if (c >= 0) have_off = base_off + want_off; #endif if (base_off + want_off < have_off) { fprintf(fperr, "%s: sorry, cannot seek backwards.\n", pname); return 5; } for (; have_off < base_off + want_off; have_off++) if (putc(0, fpo) == EOF) die(3); } if (n2 >= 0 && n1 >= 0) { if (putc((n2 << 4) | n1, fpo) == EOF) die(3); have_off++; want_off++; n1 = -1; if ((++p >= cols) && !hextype) { /* skip rest of line as garbage */ want_off = 0; while ((c = getc(fpi)) != '\n' && c != EOF) ; if (c == EOF && ferror(fpi)) die(2); ign_garb = 1; } } else if (n1 < 0 && n2 < 0 && n3 < 0) { /* already stumbled into garbage, skip line, wait and see */ if (!hextype) want_off = 0; while ((c = getc(fpi)) != '\n' && c != EOF) ; if (c == EOF && ferror(fpi)) die(2); ign_garb = 1; } } if (fflush(fpo) != 0) die(3); #ifdef TRY_SEEK fseek(fpo, 0L, 2); #endif if (fclose(fpo) != 0) die(3); if (fclose(fpi) != 0) die(2); return 0; } /* * Print line l. If nz is false, xxdline regards the line a line of * zeroes. If there are three or more consecutive lines of zeroes, * they are replaced by a single '*' character. * * If the output ends with more than two lines of zeroes, you * should call xxdline again with l being the last line and nz * negative. This ensures that the last line is shown even when * it is all zeroes. * * If nz is always positive, lines are never suppressed. */ static void xxdline(fp, l, nz) FILE *fp; char *l; int nz; { static char z[LLEN+1]; static int zero_seen = 0; if (!nz && zero_seen == 1) strcpy(z, l); if (nz || !zero_seen++) { if (nz) { if (nz < 0) zero_seen--; if (zero_seen == 2) if (fputs(z, fp) == EOF) die(3); if (zero_seen > 2) if (fputs("*\n", fp) == EOF) die(3); } if (nz >= 0 || zero_seen > 0) if (fputs(l, fp) == EOF) die(3); if (nz) zero_seen = 0; } } /* This is an EBCDIC to ASCII conversion table */ /* from a proposed BTL standard April 16, 1979 */ static unsigned char etoa64[] = { 0040,0240,0241,0242,0243,0244,0245,0246, 0247,0250,0325,0056,0074,0050,0053,0174, 0046,0251,0252,0253,0254,0255,0256,0257, 0260,0261,0041,0044,0052,0051,0073,0176, 0055,0057,0262,0263,0264,0265,0266,0267, 0270,0271,0313,0054,0045,0137,0076,0077, 0272,0273,0274,0275,0276,0277,0300,0301, 0302,0140,0072,0043,0100,0047,0075,0042, 0303,0141,0142,0143,0144,0145,0146,0147, 0150,0151,0304,0305,0306,0307,0310,0311, 0312,0152,0153,0154,0155,0156,0157,0160, 0161,0162,0136,0314,0315,0316,0317,0320, 0321,0345,0163,0164,0165,0166,0167,0170, 0171,0172,0322,0323,0324,0133,0326,0327, 0330,0331,0332,0333,0334,0335,0336,0337, 0340,0341,0342,0343,0344,0135,0346,0347, 0173,0101,0102,0103,0104,0105,0106,0107, 0110,0111,0350,0351,0352,0353,0354,0355, 0175,0112,0113,0114,0115,0116,0117,0120, 0121,0122,0356,0357,0360,0361,0362,0363, 0134,0237,0123,0124,0125,0126,0127,0130, 0131,0132,0364,0365,0366,0367,0370,0371, 0060,0061,0062,0063,0064,0065,0066,0067, 0070,0071,0372,0373,0374,0375,0376,0377 }; int main(argc, argv) int argc; char *argv[]; { FILE *fp, *fpo; int c, e, p = 0, relseek = 1, negseek = 0, revert = 0; int cols = 0, nonzero = 0, autoskip = 0, hextype = HEX_NORMAL; int ebcdic = 0; int octspergrp = -1; /* number of octets grouped in output */ int grplen; /* total chars per octet group */ long length = -1, n = 0, seekoff = 0; static char l[LLEN+1]; /* static because it may be too big for stack */ char *pp; #ifdef AMIGA /* This program doesn't work when started from the Workbench */ if (argc == 0) exit(1); #endif pname = argv[0]; for (pp = pname; *pp; ) if (*pp++ == PATH_SEP) pname = pp; #ifdef FILE_SEP for (pp = pname; *pp; pp++) if (*pp == FILE_SEP) { *pp = '\0'; break; } #endif while (argc >= 2) { pp = argv[1] + (!STRNCMP(argv[1], "--", 2) && argv[1][2]); if (!STRNCMP(pp, "-a", 2)) autoskip = 1 - autoskip; else if (!STRNCMP(pp, "-b", 2)) hextype = HEX_BITS; else if (!STRNCMP(pp, "-u", 2)) hexx = hexxa + 16; else if (!STRNCMP(pp, "-p", 2)) hextype = HEX_POSTSCRIPT; else if (!STRNCMP(pp, "-i", 2)) hextype = HEX_CINCLUDE; else if (!STRNCMP(pp, "-r", 2)) revert++; else if (!STRNCMP(pp, "-E", 2)) ebcdic++; else if (!STRNCMP(pp, "-v", 2)) { fprintf(stderr, "%s%s\n", version, osver); exit(0); } else if (!STRNCMP(pp, "-c", 2)) { if (pp[2] && STRNCMP("ols", pp + 2, 3)) cols = (int)strtol(pp + 2, NULL, 0); else { if (!argv[2]) exit_with_usage(); cols = (int)strtol(argv[2], NULL, 0); argv++; argc--; } } else if (!STRNCMP(pp, "-g", 2)) { if (pp[2] && STRNCMP("group", pp + 2, 5)) octspergrp = (int)strtol(pp + 2, NULL, 0); else { if (!argv[2]) exit_with_usage(); octspergrp = (int)strtol(argv[2], NULL, 0); argv++; argc--; } } else if (!STRNCMP(pp, "-s", 2)) { relseek = 0; negseek = 0; if (pp[2] && STRNCMP("kip", pp+2, 3) && STRNCMP("eek", pp+2, 3)) { #ifdef TRY_SEEK if (pp[2] == '+') relseek++; if (pp[2+relseek] == '-') negseek++; #endif seekoff = strtol(pp + 2+relseek+negseek, (char **)NULL, 0); } else { if (!argv[2]) exit_with_usage(); #ifdef TRY_SEEK if (argv[2][0] == '+') relseek++; if (argv[2][relseek] == '-') negseek++; #endif seekoff = strtol(argv[2] + relseek+negseek, (char **)NULL, 0); argv++; argc--; } } else if (!STRNCMP(pp, "-l", 2)) { if (pp[2] && STRNCMP("en", pp + 2, 2)) length = strtol(pp + 2, (char **)NULL, 0); else { if (!argv[2]) exit_with_usage(); length = strtol(argv[2], (char **)NULL, 0); argv++; argc--; } } else if (!strcmp(pp, "--")) /* end of options */ { argv++; argc--; break; } else if (pp[0] == '-' && pp[1]) /* unknown option */ exit_with_usage(); else break; /* not an option */ argv++; /* advance to next argument */ argc--; } if (!cols) switch (hextype) { case HEX_POSTSCRIPT: cols = 30; break; case HEX_CINCLUDE: cols = 12; break; case HEX_BITS: cols = 6; break; case HEX_NORMAL: default: cols = 16; break; } if (octspergrp < 0) switch (hextype) { case HEX_BITS: octspergrp = 1; break; case HEX_NORMAL: octspergrp = 2; break; case HEX_POSTSCRIPT: case HEX_CINCLUDE: default: octspergrp = 0; break; } if (cols < 1 || ((hextype == HEX_NORMAL || hextype == HEX_BITS) && (cols > COLS))) { fprintf(stderr, "%s: invalid number of columns (max. %d).\n", pname, COLS); exit(1); } if (octspergrp < 1) octspergrp = cols; if (argc > 3) exit_with_usage(); if (argc == 1 || (argv[1][0] == '-' && !argv[1][1])) BIN_ASSIGN(fp = stdin, !revert); else { if ((fp = fopen(argv[1], BIN_READ(!revert))) == NULL) { fprintf(stderr,"%s: ", pname); perror(argv[1]); return 2; } } if (argc < 3 || (argv[2][0] == '-' && !argv[2][1])) BIN_ASSIGN(fpo = stdout, revert); else { int fd; int mode = revert ? O_WRONLY : (O_TRUNC|O_WRONLY); if (((fd = OPEN(argv[2], mode | BIN_CREAT(revert), 0666)) < 0) || (fpo = fdopen(fd, BIN_WRITE(revert))) == NULL) { fprintf(stderr, "%s: ", pname); perror(argv[2]); return 3; } rewind(fpo); } if (revert) { if (hextype && (hextype != HEX_POSTSCRIPT)) { fprintf(stderr, "%s: sorry, cannot revert this type of hexdump\n", pname); return -1; } return huntype(fp, fpo, stderr, cols, hextype, negseek ? -seekoff : seekoff); } if (seekoff || negseek || !relseek) { #ifdef TRY_SEEK if (relseek) e = fseek(fp, negseek ? -seekoff : seekoff, 1); else e = fseek(fp, negseek ? -seekoff : seekoff, negseek ? 2 : 0); if (e < 0 && negseek) { fprintf(stderr, "%s: sorry cannot seek.\n", pname); return 4; } if (e >= 0) seekoff = ftell(fp); else #endif { long s = seekoff; while (s--) if (getc(fp) == EOF) { if (ferror(fp)) { die(2); } else { fprintf(stderr, "%s: sorry cannot seek.\n", pname); return 4; } } } } if (hextype == HEX_CINCLUDE) { if (fp != stdin) { if (fprintf(fpo, "unsigned char %s", isdigit((int)argv[1][0]) ? "__" : "") < 0) die(3); for (e = 0; (c = argv[1][e]) != 0; e++) if (putc(isalnum(c) ? c : '_', fpo) == EOF) die(3); if (fputs("[] = {\n", fpo) == EOF) die(3); } p = 0; c = 0; while ((length < 0 || p < length) && (c = getc(fp)) != EOF) { if (fprintf(fpo, (hexx == hexxa) ? "%s0x%02x" : "%s0X%02X", (p % cols) ? ", " : ",\n "+2*!p, c) < 0) die(3); p++; } if (c == EOF && ferror(fp)) die(2); if (p) if (fputs("\n};\n" + 3 * (fp == stdin), fpo) == EOF) die(3); if (fp != stdin) { if (fprintf(fpo, "unsigned int %s", isdigit((int)argv[1][0]) ? "__" : "") < 0) die(3); for (e = 0; (c = argv[1][e]) != 0; e++) if (putc(isalnum(c) ? c : '_', fpo) == EOF) die(3); if (fprintf(fpo, "_len = %d;\n", p) < 0) die(3); } if (fclose(fp)) die(2); if (fclose(fpo)) die(3); return 0; } if (hextype == HEX_POSTSCRIPT) { p = cols; e = 0; while ((length < 0 || n < length) && (e = getc(fp)) != EOF) { if (putc(hexx[(e >> 4) & 0xf], fpo) == EOF || putc(hexx[e & 0xf], fpo) == EOF) die(3); n++; if (!--p) { if (putc('\n', fpo) == EOF) die(3); p = cols; } } if (e == EOF && ferror(fp)) die(2); if (p < cols) if (putc('\n', fpo) == EOF) die(3); if (fclose(fp)) die(2); if (fclose(fpo)) die(3); return 0; } /* hextype: HEX_NORMAL or HEX_BITS */ if (hextype == HEX_NORMAL) grplen = octspergrp + octspergrp + 1; /* chars per octet group */ else /* hextype == HEX_BITS */ grplen = 8 * octspergrp + 1; e = 0; while ((length < 0 || n < length) && (e = getc(fp)) != EOF) { if (p == 0) { sprintf(l, "%07lx: ", n + seekoff); for (c = 9; c < LLEN; l[c++] = ' '); } if (hextype == HEX_NORMAL) { l[c = (9 + (grplen * p) / octspergrp)] = hexx[(e >> 4) & 0xf]; l[++c] = hexx[ e & 0xf]; } else /* hextype == HEX_BITS */ { int i; c = (9 + (grplen * p) / octspergrp) - 1; for (i = 7; i >= 0; i--) l[++c] = (e & (1 << i)) ? '1' : '0'; } if (ebcdic) e = (e < 64) ? '.' : etoa64[e-64]; /* When changing this update definition of LLEN above. */ l[11 + (grplen * cols - 1)/octspergrp + p] = #ifdef __MVS__ (e >= 64) #else (e > 31 && e < 127) #endif ? e : '.'; if (e) nonzero++; n++; if (++p == cols) { l[c = (11 + (grplen * cols - 1)/octspergrp + p)] = '\n'; l[++c] = '\0'; xxdline(fpo, l, autoskip ? nonzero : 1); nonzero = 0; p = 0; } } if (e == EOF && ferror(fp)) die(2); if (p) { l[c = (11 + (grplen * cols - 1)/octspergrp + p)] = '\n'; l[++c] = '\0'; xxdline(fpo, l, 1); } else if (autoskip) xxdline(fpo, l, -1); /* last chance to flush out suppressed lines */ if (fclose(fp)) die(2); if (fclose(fpo)) die(3); return 0; } /* vi:set ts=8 sw=4 sts=2 cino+={2 cino+=n-2 : */
zyz2011-vim
src/xxd/xxd.c
C
gpl2
22,787
# The most simplistic Makefile for Win32 using Microsoft Visual C++ # (NT and Windows 95) xxd: xxd.exe xxd.exe: xxd.c cl /nologo -DWIN32 xxd.c # This was for an older compiler # cl /nologo -DWIN32 xxd.c /link setargv.obj clean: - if exist xxd.obj del xxd.obj - if exist xxd.exe del xxd.exe
zyz2011-vim
src/xxd/Make_mvc.mak
Makefile
gpl2
312
# Simple makefile for Borland C++ 4.0 # 3.1 can NOT be used, it has problems with the fileno() define. # Command line variables: # BOR path to root of Borland C (E:\BORLANDC) # DEBUG set to "yes" for debugging (no) !ifndef BOR BOR = e:\bc4 !endif !if ("$(DEBUG)" == "yes") DEBUG_FLAG = -v -DDEBUG !else DEBUG_FLAG = !endif CC = $(BOR)\bin\bcc INC = -I$(BOR)\include LIB = -L$(BOR)\lib # The following compile options can be changed for better machines. # replace -1- with -2 to produce code for a 80286 or higher # replace -1- with -3 to produce code for a 80386 or higher # add -v for source debugging OPTIMIZE= -1- -Ox CFLAGS = -A -mc -DMSDOS $(DEBUG_FLAG) $(OPTIMIZE) $(INC) $(LIB) xxd.exe: xxd.c $(CC) $(CFLAGS) xxd.c
zyz2011-vim
src/xxd/Make_bc3.mak
Makefile
gpl2
732
# A very (if most the most) simplistic Makefile for OS/2 CC=gcc CFLAGS=-O2 -fno-strength-reduce -DOS2 xxd.exe: xxd.c $(CC) $(CFLAGS) -s -o $@ $< clean: - del xxd.o - del xxd.exe
zyz2011-vim
src/xxd/Make_os2.mak
Makefile
gpl2
184
# The most simplistic Makefile, for DJGPP on MS-DOS CFLAGS = -O2 -Wall xxd.exe: xxd.c gcc $(CFLAGS) -s -o xxd.exe xxd.c -lpc clean: del xxd.exe
zyz2011-vim
src/xxd/Make_djg.mak
Makefile
gpl2
149
/* if_python3.c */ int python3_enabled __ARGS((int verbose)); void python3_end __ARGS((void)); int python3_loaded __ARGS((void)); void ex_py3 __ARGS((exarg_T *eap)); void ex_py3file __ARGS((exarg_T *eap)); void python3_buffer_free __ARGS((buf_T *buf)); void python3_window_free __ARGS((win_T *win)); /* vim: set ft=c : */
zyz2011-vim
src/proto/if_python3.pro
C
gpl2
322
/* os_amiga.c */ void win_resize_on __ARGS((void)); void win_resize_off __ARGS((void)); void mch_write __ARGS((char_u *p, int len)); int mch_inchar __ARGS((char_u *buf, int maxlen, long time, int tb_change_cnt)); int mch_char_avail __ARGS((void)); long_u mch_avail_mem __ARGS((int special)); void mch_delay __ARGS((long msec, int ignoreinput)); void mch_suspend __ARGS((void)); void mch_init __ARGS((void)); int mch_check_win __ARGS((int argc, char **argv)); int mch_input_isatty __ARGS((void)); void fname_case __ARGS((char_u *name, int len)); void mch_settitle __ARGS((char_u *title, char_u *icon)); void mch_restore_title __ARGS((int which)); int mch_can_restore_title __ARGS((void)); int mch_can_restore_icon __ARGS((void)); int mch_get_user_name __ARGS((char_u *s, int len)); void mch_get_host_name __ARGS((char_u *s, int len)); long mch_get_pid __ARGS((void)); int mch_dirname __ARGS((char_u *buf, int len)); int mch_FullName __ARGS((char_u *fname, char_u *buf, int len, int force)); int mch_isFullName __ARGS((char_u *fname)); long mch_getperm __ARGS((char_u *name)); int mch_setperm __ARGS((char_u *name, long perm)); void mch_hide __ARGS((char_u *name)); int mch_isdir __ARGS((char_u *name)); int mch_mkdir __ARGS((char_u *name)); int mch_can_exe __ARGS((char_u *name)); int mch_nodetype __ARGS((char_u *name)); void mch_early_init __ARGS((void)); void mch_exit __ARGS((int r)); void mch_settmode __ARGS((int tmode)); int mch_screenmode __ARGS((char_u *arg)); int mch_get_shellsize __ARGS((void)); void mch_set_shellsize __ARGS((void)); void mch_new_shellsize __ARGS((void)); int mch_call_shell __ARGS((char_u *cmd, int options)); void mch_breakcheck __ARGS((void)); long Chk_Abort __ARGS((void)); int mch_expandpath __ARGS((garray_T *gap, char_u *pat, int flags)); int mch_has_exp_wildcard __ARGS((char_u *p)); int mch_has_wildcard __ARGS((char_u *p)); char_u *mch_getenv __ARGS((char_u *var)); int mch_setenv __ARGS((char *var, char *value, int x)); /* vim: set ft=c : */
zyz2011-vim
src/proto/os_amiga.pro
C
gpl2
1,983
/* ex_cmds2.c */ void do_debug __ARGS((char_u *cmd)); void ex_debug __ARGS((exarg_T *eap)); void dbg_check_breakpoint __ARGS((exarg_T *eap)); int dbg_check_skipped __ARGS((exarg_T *eap)); void ex_breakadd __ARGS((exarg_T *eap)); void ex_debuggreedy __ARGS((exarg_T *eap)); void ex_breakdel __ARGS((exarg_T *eap)); void ex_breaklist __ARGS((exarg_T *eap)); linenr_T dbg_find_breakpoint __ARGS((int file, char_u *fname, linenr_T after)); int has_profiling __ARGS((int file, char_u *fname, int *fp)); void dbg_breakpoint __ARGS((char_u *name, linenr_T lnum)); void profile_start __ARGS((proftime_T *tm)); void profile_end __ARGS((proftime_T *tm)); void profile_sub __ARGS((proftime_T *tm, proftime_T *tm2)); char *profile_msg __ARGS((proftime_T *tm)); void profile_setlimit __ARGS((long msec, proftime_T *tm)); int profile_passed_limit __ARGS((proftime_T *tm)); void profile_zero __ARGS((proftime_T *tm)); void profile_add __ARGS((proftime_T *tm, proftime_T *tm2)); void profile_self __ARGS((proftime_T *self, proftime_T *total, proftime_T *children)); void profile_get_wait __ARGS((proftime_T *tm)); void profile_sub_wait __ARGS((proftime_T *tm, proftime_T *tma)); int profile_equal __ARGS((proftime_T *tm1, proftime_T *tm2)); int profile_cmp __ARGS((proftime_T *tm1, proftime_T *tm2)); void ex_profile __ARGS((exarg_T *eap)); char_u *get_profile_name __ARGS((expand_T *xp, int idx)); void set_context_in_profile_cmd __ARGS((expand_T *xp, char_u *arg)); void profile_dump __ARGS((void)); void script_prof_save __ARGS((proftime_T *tm)); void script_prof_restore __ARGS((proftime_T *tm)); void prof_inchar_enter __ARGS((void)); void prof_inchar_exit __ARGS((void)); int prof_def_func __ARGS((void)); int autowrite __ARGS((buf_T *buf, int forceit)); void autowrite_all __ARGS((void)); int check_changed __ARGS((buf_T *buf, int checkaw, int mult_win, int forceit, int allbuf)); void browse_save_fname __ARGS((buf_T *buf)); void dialog_changed __ARGS((buf_T *buf, int checkall)); int can_abandon __ARGS((buf_T *buf, int forceit)); int check_changed_any __ARGS((int hidden)); int check_fname __ARGS((void)); int buf_write_all __ARGS((buf_T *buf, int forceit)); int get_arglist __ARGS((garray_T *gap, char_u *str)); int get_arglist_exp __ARGS((char_u *str, int *fcountp, char_u ***fnamesp)); void set_arglist __ARGS((char_u *str)); void check_arg_idx __ARGS((win_T *win)); void ex_args __ARGS((exarg_T *eap)); void ex_previous __ARGS((exarg_T *eap)); void ex_rewind __ARGS((exarg_T *eap)); void ex_last __ARGS((exarg_T *eap)); void ex_argument __ARGS((exarg_T *eap)); void do_argfile __ARGS((exarg_T *eap, int argn)); void ex_next __ARGS((exarg_T *eap)); void ex_argedit __ARGS((exarg_T *eap)); void ex_argadd __ARGS((exarg_T *eap)); void ex_argdelete __ARGS((exarg_T *eap)); void ex_listdo __ARGS((exarg_T *eap)); void ex_compiler __ARGS((exarg_T *eap)); void ex_runtime __ARGS((exarg_T *eap)); int source_runtime __ARGS((char_u *name, int all)); int do_in_runtimepath __ARGS((char_u *name, int all, void (*callback)(char_u *fname, void *ck), void *cookie)); void ex_options __ARGS((exarg_T *eap)); void ex_source __ARGS((exarg_T *eap)); linenr_T *source_breakpoint __ARGS((void *cookie)); int *source_dbg_tick __ARGS((void *cookie)); int source_level __ARGS((void *cookie)); int do_source __ARGS((char_u *fname, int check_other, int is_vimrc)); void ex_scriptnames __ARGS((exarg_T *eap)); void scriptnames_slash_adjust __ARGS((void)); char_u *get_scriptname __ARGS((scid_T id)); void free_scriptnames __ARGS((void)); char *fgets_cr __ARGS((char *s, int n, FILE *stream)); char_u *getsourceline __ARGS((int c, void *cookie, int indent)); void script_line_start __ARGS((void)); void script_line_exec __ARGS((void)); void script_line_end __ARGS((void)); void ex_scriptencoding __ARGS((exarg_T *eap)); void ex_finish __ARGS((exarg_T *eap)); void do_finish __ARGS((exarg_T *eap, int reanimate)); int source_finished __ARGS((char_u *(*fgetline)(int, void *, int), void *cookie)); void ex_checktime __ARGS((exarg_T *eap)); char_u *get_mess_lang __ARGS((void)); void set_lang_var __ARGS((void)); void ex_language __ARGS((exarg_T *eap)); void free_locales __ARGS((void)); char_u *get_lang_arg __ARGS((expand_T *xp, int idx)); char_u *get_locales __ARGS((expand_T *xp, int idx)); /* vim: set ft=c : */
zyz2011-vim
src/proto/ex_cmds2.pro
C
gpl2
4,285
/* regexp.c */ int re_multiline __ARGS((regprog_T *prog)); int re_lookbehind __ARGS((regprog_T *prog)); char_u *skip_regexp __ARGS((char_u *startp, int dirc, int magic, char_u **newp)); regprog_T *vim_regcomp __ARGS((char_u *expr, int re_flags)); int vim_regcomp_had_eol __ARGS((void)); void free_regexp_stuff __ARGS((void)); int vim_regexec __ARGS((regmatch_T *rmp, char_u *line, colnr_T col)); int vim_regexec_nl __ARGS((regmatch_T *rmp, char_u *line, colnr_T col)); long vim_regexec_multi __ARGS((regmmatch_T *rmp, win_T *win, buf_T *buf, linenr_T lnum, colnr_T col, proftime_T *tm)); reg_extmatch_T *ref_extmatch __ARGS((reg_extmatch_T *em)); void unref_extmatch __ARGS((reg_extmatch_T *em)); char_u *regtilde __ARGS((char_u *source, int magic)); int vim_regsub __ARGS((regmatch_T *rmp, char_u *source, char_u *dest, int copy, int magic, int backslash)); int vim_regsub_multi __ARGS((regmmatch_T *rmp, linenr_T lnum, char_u *source, char_u *dest, int copy, int magic, int backslash)); char_u *reg_submatch __ARGS((int no)); /* vim: set ft=c : */
zyz2011-vim
src/proto/regexp.pro
C
gpl2
1,050
/* main.c */ void main_loop __ARGS((int cmdwin, int noexmode)); void getout_preserve_modified __ARGS((int exitval)); void getout __ARGS((int exitval)); int process_env __ARGS((char_u *env, int is_viminit)); void mainerr_arg_missing __ARGS((char_u *str)); void time_push __ARGS((void *tv_rel, void *tv_start)); void time_pop __ARGS((void *tp)); void time_msg __ARGS((char *mesg, void *tv_start)); void server_to_input_buf __ARGS((char_u *str)); char_u *eval_client_expr_to_string __ARGS((char_u *expr)); char_u *serverConvert __ARGS((char_u *client_enc, char_u *data, char_u **tofree)); int toF_TyA __ARGS((int c)); int fkmap __ARGS((int c)); void conv_to_pvim __ARGS((void)); void conv_to_pstd __ARGS((void)); char_u *lrswap __ARGS((char_u *ibuf)); char_u *lrFswap __ARGS((char_u *cmdbuf, int len)); char_u *lrF_sub __ARGS((char_u *ibuf)); int cmdl_fkmap __ARGS((int c)); int F_isalpha __ARGS((int c)); int F_isdigit __ARGS((int c)); int F_ischar __ARGS((int c)); void farsi_fkey __ARGS((cmdarg_T *cap)); int arabic_shape __ARGS((int c, int *ccp, int *c1p, int prev_c, int prev_c1, int next_c)); /* vim: set ft=c : */
zyz2011-vim
src/proto/main.pro
C
gpl2
1,118
/* gui_x11.c */ void gui_x11_key_hit_cb __ARGS((Widget w, XtPointer dud, XEvent *event, Boolean *dum)); void gui_mch_prepare __ARGS((int *argc, char **argv)); int gui_mch_init_check __ARGS((void)); int gui_mch_init __ARGS((void)); void gui_mch_uninit __ARGS((void)); void gui_mch_new_colors __ARGS((void)); int gui_mch_open __ARGS((void)); void gui_init_tooltip_font __ARGS((void)); void gui_init_menu_font __ARGS((void)); void gui_mch_exit __ARGS((int rc)); int gui_mch_get_winpos __ARGS((int *x, int *y)); void gui_mch_set_winpos __ARGS((int x, int y)); void gui_mch_set_shellsize __ARGS((int width, int height, int min_width, int min_height, int base_width, int base_height, int direction)); void gui_mch_get_screen_dimensions __ARGS((int *screen_w, int *screen_h)); int gui_mch_init_font __ARGS((char_u *font_name, int do_fontset)); GuiFont gui_mch_get_font __ARGS((char_u *name, int giveErrorIfMissing)); char_u *gui_mch_get_fontname __ARGS((GuiFont font, char_u *name)); int gui_mch_adjust_charheight __ARGS((void)); void gui_mch_set_font __ARGS((GuiFont font)); void gui_mch_set_fontset __ARGS((GuiFontset fontset)); void gui_mch_free_font __ARGS((GuiFont font)); void gui_mch_free_fontset __ARGS((GuiFontset fontset)); GuiFontset gui_mch_get_fontset __ARGS((char_u *name, int giveErrorIfMissing, int fixed_width)); int fontset_height __ARGS((XFontSet fs)); int fontset_height2 __ARGS((XFontSet fs)); guicolor_T gui_mch_get_color __ARGS((char_u *reqname)); void gui_mch_set_fg_color __ARGS((guicolor_T color)); void gui_mch_set_bg_color __ARGS((guicolor_T color)); void gui_mch_set_sp_color __ARGS((guicolor_T color)); void gui_mch_draw_string __ARGS((int row, int col, char_u *s, int len, int flags)); int gui_mch_haskey __ARGS((char_u *name)); int gui_get_x11_windis __ARGS((Window *win, Display **dis)); void gui_mch_beep __ARGS((void)); void gui_mch_flash __ARGS((int msec)); void gui_mch_invert_rectangle __ARGS((int r, int c, int nr, int nc)); void gui_mch_iconify __ARGS((void)); void gui_mch_set_foreground __ARGS((void)); void gui_mch_draw_hollow_cursor __ARGS((guicolor_T color)); void gui_mch_draw_part_cursor __ARGS((int w, int h, guicolor_T color)); void gui_mch_update __ARGS((void)); int gui_mch_wait_for_chars __ARGS((long wtime)); void gui_mch_flush __ARGS((void)); void gui_mch_clear_block __ARGS((int row1, int col1, int row2, int col2)); void gui_mch_clear_all __ARGS((void)); void gui_mch_delete_lines __ARGS((int row, int num_lines)); void gui_mch_insert_lines __ARGS((int row, int num_lines)); void clip_mch_lose_selection __ARGS((VimClipboard *cbd)); int clip_mch_own_selection __ARGS((VimClipboard *cbd)); void clip_mch_request_selection __ARGS((VimClipboard *cbd)); void clip_mch_set_selection __ARGS((VimClipboard *cbd)); void gui_mch_menu_grey __ARGS((vimmenu_T *menu, int grey)); void gui_mch_menu_hidden __ARGS((vimmenu_T *menu, int hidden)); void gui_mch_draw_menubar __ARGS((void)); void gui_x11_menu_cb __ARGS((Widget w, XtPointer client_data, XtPointer call_data)); void gui_mch_set_blinking __ARGS((long waittime, long on, long off)); void gui_mch_stop_blink __ARGS((void)); void gui_mch_start_blink __ARGS((void)); long_u gui_mch_get_rgb __ARGS((guicolor_T pixel)); void gui_x11_callbacks __ARGS((Widget textArea, Widget vimForm)); void gui_mch_getmouse __ARGS((int *x, int *y)); void gui_mch_setmouse __ARGS((int x, int y)); XButtonPressedEvent *gui_x11_get_last_mouse_event __ARGS((void)); void gui_mch_drawsign __ARGS((int row, int col, int typenr)); void *gui_mch_register_sign __ARGS((char_u *signfile)); void gui_mch_destroy_sign __ARGS((void *sign)); void gui_mch_mousehide __ARGS((int hide)); void mch_set_mouse_shape __ARGS((int shape)); void gui_mch_menu_set_tip __ARGS((vimmenu_T *menu)); /* vim: set ft=c : */
zyz2011-vim
src/proto/gui_x11.pro
C
gpl2
3,765
/* ex_docmd.c */ void do_exmode __ARGS((int improved)); int do_cmdline_cmd __ARGS((char_u *cmd)); int do_cmdline __ARGS((char_u *cmdline, char_u *(*fgetline)(int, void *, int), void *cookie, int flags)); int getline_equal __ARGS((char_u *(*fgetline)(int, void *, int), void *cookie, char_u *(*func)(int, void *, int))); void *getline_cookie __ARGS((char_u *(*fgetline)(int, void *, int), void *cookie)); int checkforcmd __ARGS((char_u **pp, char *cmd, int len)); int modifier_len __ARGS((char_u *cmd)); int cmd_exists __ARGS((char_u *name)); char_u *set_one_cmd_context __ARGS((expand_T *xp, char_u *buff)); char_u *skip_range __ARGS((char_u *cmd, int *ctx)); void ex_ni __ARGS((exarg_T *eap)); int expand_filename __ARGS((exarg_T *eap, char_u **cmdlinep, char_u **errormsgp)); void separate_nextcmd __ARGS((exarg_T *eap)); int ends_excmd __ARGS((int c)); char_u *find_nextcmd __ARGS((char_u *p)); char_u *check_nextcmd __ARGS((char_u *p)); char_u *get_command_name __ARGS((expand_T *xp, int idx)); void ex_comclear __ARGS((exarg_T *eap)); void uc_clear __ARGS((garray_T *gap)); char_u *get_user_commands __ARGS((expand_T *xp, int idx)); char_u *get_user_cmd_flags __ARGS((expand_T *xp, int idx)); char_u *get_user_cmd_nargs __ARGS((expand_T *xp, int idx)); char_u *get_user_cmd_complete __ARGS((expand_T *xp, int idx)); int parse_compl_arg __ARGS((char_u *value, int vallen, int *complp, long *argt, char_u **compl_arg)); void not_exiting __ARGS((void)); void tabpage_close __ARGS((int forceit)); void tabpage_close_other __ARGS((tabpage_T *tp, int forceit)); void ex_all __ARGS((exarg_T *eap)); void handle_drop __ARGS((int filec, char_u **filev, int split)); void alist_clear __ARGS((alist_T *al)); void alist_init __ARGS((alist_T *al)); void alist_unlink __ARGS((alist_T *al)); void alist_new __ARGS((void)); void alist_expand __ARGS((int *fnum_list, int fnum_len)); void alist_set __ARGS((alist_T *al, int count, char_u **files, int use_curbuf, int *fnum_list, int fnum_len)); void alist_add __ARGS((alist_T *al, char_u *fname, int set_fnum)); void alist_slash_adjust __ARGS((void)); void ex_splitview __ARGS((exarg_T *eap)); void tabpage_new __ARGS((void)); void do_exedit __ARGS((exarg_T *eap, win_T *old_curwin)); void free_cd_dir __ARGS((void)); void ex_cd __ARGS((exarg_T *eap)); void do_sleep __ARGS((long msec)); int vim_mkdir_emsg __ARGS((char_u *name, int prot)); FILE *open_exfile __ARGS((char_u *fname, int forceit, char *mode)); void update_topline_cursor __ARGS((void)); void exec_normal_cmd __ARGS((char_u *cmd, int remap, int silent)); int find_cmdline_var __ARGS((char_u *src, int *usedlen)); char_u *eval_vars __ARGS((char_u *src, char_u *srcstart, int *usedlen, linenr_T *lnump, char_u **errormsg, int *escaped)); char_u *expand_sfile __ARGS((char_u *arg)); int put_eol __ARGS((FILE *fd)); int put_line __ARGS((FILE *fd, char *s)); void dialog_msg __ARGS((char_u *buff, char *format, char_u *fname)); char_u *get_behave_arg __ARGS((expand_T *xp, int idx)); /* vim: set ft=c : */
zyz2011-vim
src/proto/ex_docmd.pro
C
gpl2
3,002
/* os_msdos.c */ void mch_set_normal_colors __ARGS((void)); void mch_update_cursor __ARGS((void)); long_u mch_avail_mem __ARGS((int special)); void mch_delay __ARGS((long msec, int ignoreinput)); void mch_write __ARGS((char_u *s, int len)); int mch_inchar __ARGS((char_u *buf, int maxlen, long time, int tb_change_cnt)); int mch_char_avail __ARGS((void)); void mch_suspend __ARGS((void)); void mch_init __ARGS((void)); int mch_check_win __ARGS((int argc, char **argv)); int mch_input_isatty __ARGS((void)); void fname_case __ARGS((char_u *name, int len)); long mch_get_pid __ARGS((void)); int mch_FullName __ARGS((char_u *fname, char_u *buf, int len, int force)); void slash_adjust __ARGS((char_u *p)); int mch_isFullName __ARGS((char_u *fname)); void mch_early_init __ARGS((void)); void mch_exit __ARGS((int r)); void mch_settmode __ARGS((int tmode)); void mch_setmouse __ARGS((int on)); int mch_screenmode __ARGS((char_u *arg)); int mch_get_shellsize __ARGS((void)); void mch_set_shellsize __ARGS((void)); void mch_new_shellsize __ARGS((void)); void mch_check_columns __ARGS((void)); int mch_call_shell __ARGS((char_u *cmd, int options)); void mch_breakcheck __ARGS((void)); int mch_has_exp_wildcard __ARGS((char_u *p)); int mch_has_wildcard __ARGS((char_u *p)); int mch_chdir __ARGS((char *path)); char *djgpp_setlocale __ARGS((void)); int clip_mch_own_selection __ARGS((VimClipboard *cbd)); void clip_mch_lose_selection __ARGS((VimClipboard *cbd)); void clip_mch_request_selection __ARGS((VimClipboard *cbd)); void clip_mch_set_selection __ARGS((VimClipboard *cbd)); long mch_getperm __ARGS((char_u *name)); int mch_setperm __ARGS((char_u *name, long perm)); void mch_hide __ARGS((char_u *name)); int mch_isdir __ARGS((char_u *name)); int mch_can_exe __ARGS((char_u *name)); int mch_nodetype __ARGS((char_u *name)); int mch_dirname __ARGS((char_u *buf, int len)); int mch_remove __ARGS((char_u *name)); char_u *mch_getenv __ARGS((char_u *name)); int mch_get_user_name __ARGS((char_u *s, int len)); void mch_get_host_name __ARGS((char_u *s, int len)); /* vim: set ft=c : */
zyz2011-vim
src/proto/os_msdos.pro
C
gpl2
2,077
/* if_python.c */ int python_enabled __ARGS((int verbose)); void python_end __ARGS((void)); int python_loaded __ARGS((void)); void ex_python __ARGS((exarg_T *eap)); void ex_pyfile __ARGS((exarg_T *eap)); void python_buffer_free __ARGS((buf_T *buf)); void python_window_free __ARGS((win_T *win)); /* vim: set ft=c : */
zyz2011-vim
src/proto/if_python.pro
C
gpl2
318