1 package gnu.kawa.functions; 2 import gnu.lists.*; 3 import java.text.MessageFormat ; 4 import gnu.text.ReportFormat; 5 import gnu.mapping.*; 6 7 public class Format extends ProcedureN 8 { 9 public static final Format format = new Format(); 10 static { format.setName("format"); } 11 12 public static void format(OutPort dst, Object [] args, int arg_offset) 13 { 14 Object format = args[arg_offset++]; 15 Object [] vals = new Object [args.length - arg_offset]; 16 System.arraycopy(args, arg_offset, vals, 0, vals.length); 17 if (format instanceof MessageFormat ) 18 { 19 String out = ((MessageFormat ) format).format(vals); 20 dst.print(out); 21 } 22 else 23 { 24 if (! (format instanceof ReportFormat)) 25 format = ParseFormat.parseFormat.apply1(format); 26 try 27 { 28 ((ReportFormat) format).format(vals, 0, dst, null); 29 } 30 catch (java.io.IOException ex) 31 { 32 throw new RuntimeException ("Error in format: "+ ex); 33 } 34 } 35 } 36 37 public static FString formatToString (Object [] args, int arg_offset) 38 { 39 CharArrayOutPort port = new CharArrayOutPort(); 40 format(port, args, arg_offset); 41 char[] chars = port.toCharArray(); 42 port.close (); 43 return new FString(chars); 44 } 45 46 53 public static FString formatToString(char style, Object fmt, Object [] args) 54 { 55 ReportFormat rfmt = ParseFormat.asFormat(fmt, style); 56 CharArrayOutPort port = new CharArrayOutPort(); 57 try 58 { 59 rfmt.format(args, 0, port, null); 60 } 61 catch (java.io.IOException ex) 62 { 63 throw new RuntimeException ("Error in format: "+ ex); 64 } 65 char[] chars = port.toCharArray(); 66 port.close (); 67 return new FString(chars); 68 } 69 70 public Object applyN (Object [] args) 71 { 72 return format$V(args); 73 } 74 75 public static Object format$V (Object [] args) 76 { 77 Object port_arg = args[0]; 78 if (port_arg == Boolean.TRUE) 79 { 80 format(OutPort.outDefault(), args, 1); 81 return Values.empty; 82 } 83 else if (port_arg == Boolean.FALSE) 84 { 85 return formatToString(args, 1); 86 } 87 else if (port_arg instanceof FString 88 || port_arg instanceof MessageFormat 89 || port_arg instanceof ReportFormat) 90 { 91 return formatToString(args, 0); 92 } 93 else if (port_arg instanceof OutPort) 94 { 95 format((OutPort) port_arg, args, 1); 96 return Values.empty; 97 } 98 else if (port_arg instanceof java.io.Writer ) 99 { 100 OutPort port = new OutPort((java.io.Writer ) port_arg); 101 format(port, args, 1); 102 port.close(); 103 return Values.empty; 104 } 105 else if (port_arg instanceof java.io.OutputStream ) 106 { 107 OutPort port = new OutPort((java.io.OutputStream ) port_arg); 108 format(port, args, 1); 109 port.close(); 110 return Values.empty; 111 } 112 else 113 throw new RuntimeException ("bad first argument to format"); 114 } 115 } 116 | Popular Tags |