clips-sys 0.3.0

Bindgen generated wrapper for CLIPS (clipsrules.net)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
//
//  CLIPSTerminalView.m
//  CLIPS
//
//  Created by Gary Riley on 2/23/06.
//

#import "CLIPSEnvironment.h"
#import "CLIPSTerminalView.h"
#import "CLIPSTerminalController.h"
#import <CLIPS/clips.h>

#define DOES_NOT_CHAR  0
#define NEEDS_CHAR     1 
#define HAS_CHAR       2

@implementation CLIPSTerminalView

@synthesize environment;

/********************************/
/* initWithFrame:textContainer: */
/********************************/
- (id) initWithFrame: (NSRect) frameRect textContainer: (NSTextContainer *) aTextContainer
  {
   self = [super initWithFrame: frameRect textContainer: aTextContainer];
   
   if (self)
     { }
     
   return self;
  }
   
/******************/
/* initWithFrame: */
/******************/
- (id) initWithFrame: (NSRect) frameRect
  {
   self = [super initWithFrame: frameRect];
   
   if (self)
     { }
     
   return self;
  }
  
/*********/
/* init: */
/*********/
- (id) init
  {
   self = [super init];
   
   if (self) 
     { inputBuffer = NULL; }
   
   return self;
  }
  
/************/    
/* dealloc: */
/************/    
- (void) dealloc
  {
   if (inputBuffer != NULL)
     { free(inputBuffer); }
  }
   
/*****************/
/* awakeFromNib: */
/*****************/
- (void) awakeFromNib
  {
   inputCharLock = [[NSConditionLock alloc] initWithCondition: DOES_NOT_CHAR];
   hiliteColor = [[NSDictionary alloc] initWithObjectsAndKeys: [NSColor selectedTextBackgroundColor], NSBackgroundColorAttributeName, nil];
  }

/*************************/
/* performDragOperation: */
/*************************/
- (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  {
   /*============================================*/
   /* Dropping text in the terminal window isn't */
   /* isn't supported when CLIPS is executing    */
   /* a command and expecting input.             */
   /*============================================*/
   
   if ([inputCharLock condition] == NEEDS_CHAR)
     { return NO; }

   /*===============================================================*/
   /* If the insertion point is before the beginning of the current */
   /* command, then place it at the end of the terminal windows,    */
   /* otherwise place the insertion point at the drag point.        */
   /*===============================================================*/

   NSPoint draggingLocation = [self convertPoint: [sender draggingLocation] fromView: nil];
   NSUInteger location = [self characterIndexForInsertionAtPoint: draggingLocation];
   
   NSUInteger textLength;
   NSString *theTerminalText;
   NSUInteger inputOffset = [self inputStringOffset];
      
   theTerminalText = [self string];
   textLength = [theTerminalText length];
   NSUInteger inputStart = textLength - inputOffset;
   if (location < inputStart)
     {
      // TBD The drag cursor leaves an artifact at the original location
      NSRange theRange = { textLength, 0 };
      [super setSelectedRange: theRange];
     }
   else
     {
      NSRange theRange = { location, 0 };
      [super setSelectedRange: theRange];
     }

   NSPasteboard *pb = [sender draggingPasteboard];
   if (! [self readStringFromPasteboard: pb])
     { return NO; }
   
   return YES;
  }

/***********/
/* delete: */
/***********/
- (IBAction) delete: (id) sender
  {
   char *str;
   NSUInteger textLength;
   NSString *theTerminalText;
   NSUInteger inputOffset = [self inputStringOffset];
      
   theTerminalText = [self string];
      
   NSString *theCommand, *preCommand, *postCommand;
   textLength = [theTerminalText length];
   NSUInteger inputStart = textLength - inputOffset;
         
   NSRange selectionRange = [super selectedRange];

   if (selectionRange.location < inputStart)
     { return; }

   theCommand = [theTerminalText substringFromIndex: inputStart];
   
   preCommand = [theCommand substringToIndex: (selectionRange.location - inputStart)];
   
   postCommand = [theCommand substringFromIndex: (selectionRange.location + selectionRange.length - inputStart)];

   str = (char *) [preCommand UTF8String];
   SetCommandString([environment environment],str);
      
   str = (char *) [postCommand UTF8String];
   AppendCommandString([environment environment],str);
   
   [super delete: sender];
  }

/**********/
/* paste: */
/**********/
- (IBAction) paste: (id) sender
  {
   // InsertText should handle changing selection
   //NSRange theRange = { [[super string] length], 0 };
   //[super setSelectedRange: theRange];

   NSPasteboard *pb = [NSPasteboard generalPasteboard];
   
   [self readStringFromPasteboard: pb];
  }

/*****************************/
/* readStringFromPasteboard: */
/*****************************/
- (BOOL) readStringFromPasteboard: (NSPasteboard *) pb
  {
   NSString *theText;
   NSString *type;
   
   // Is there a string on the pasteboard?
   
   type = [pb availableTypeFromArray: [NSArray arrayWithObject: NSStringPboardType]];
   
   if (type)
     {
      // Read the string from the pasteboard
      theText = [pb stringForType: NSStringPboardType];
      
      [self insertText: theText replacementRange: [self selectedRange]];
      
      [self scrollRangeToVisible: [self selectedRange]];
      
      return YES;
     }
     
   return NO;
  }
  
/**********/    
/* print: */
/**********/    
- (NSUInteger) print: (NSString *) theString
  {
   NSRange theRange = { [[super string] length], 0 };

   NSMutableAttributedString *terminalStorage = [self textStorage];

   [super setSelectedRange: theRange];   

   /*==================================================================*/  
   /* If the terminal window doesn't contain any text, use insertText  */
   /* to add the text, otherwise use replaceCharactersInRange. If the  */
   /* terminal window doesn't contain text, it uses the wrong font it  */
   /* the latter method is used, so this test is a workaround for that */
   /* problem. Another possible workaround is to use an attributed     */
   /* string with the font attribute added.                            */
   /*==================================================================*/  
          
   if ([terminalStorage isEqualToAttributedString: [[NSAttributedString new] initWithString: @""]])
     { [super insertText: theString replacementRange: [self selectedRange]]; }
   else
     {
      [terminalStorage replaceCharactersInRange: theRange withString: theString];
      [self didChangeText];
     }
   
   /*================================================*/
   /* Let the terminal controller know that text has */
   /* been added and it should be made visible.      */
   /*================================================*/
   
   [[dialogWindow windowController] setScrollToEnd: YES];
   
   return [[super string] length];
  }

/******************/    
/* clearTerminal: */
/******************/    
- (void) clearTerminal
  {
   NSMutableAttributedString *terminalStorage = [self textStorage];

   [terminalStorage setAttributedString: [[NSAttributedString new] initWithString: @""]];
   [self didChangeText];
   
   /*================================================*/
   /* Let the terminal controller know that text has */
   /* been changed and it should be made visible.    */
   /*================================================*/
   
   [[dialogWindow windowController] setScrollToEnd: YES];
  }

/***********************/    
/* balanceParentheses: */
/***********************/    
- (void) balanceParentheses
  {
   NSRange selectionRange;
   NSUInteger cursorLocation;
   size_t commandLength;
   unichar characterToCheck;
   unsigned short nestingDepth;
   NSString *theText = [super string];
   NSUserDefaults *theValues;
   
   /*==============================================================*/
   /* Check the defaults to see if parentheses should be balanced. */
   /*==============================================================*/
   
   theValues = [[NSUserDefaultsController sharedUserDefaultsController] values];
    
   if (! [[theValues valueForKey: @"dialogBalanceParens"] boolValue]) 
     { return; } 

  /*================================================*/
   /* Don't balance parentheses if there is no text. */
   /*================================================*/
   
   if ([theText length] == 0)
     { return; }
     
   /*=======================================================*/
   /* Don't balance the parentheses if there is no command. */
   /*=======================================================*/
   
   commandLength = RouterData([environment environment])->CommandBufferInputCount;
   if (commandLength <= 0) 
     { return; }

   /*=================================*/
   /* Retrieve the current selection. */
   /*=================================*/
          
   selectionRange = [super selectedRange];
   
   /*======================*/
   /* Where is the cursor? */
   /*======================*/
    
   cursorLocation = selectionRange.location;
   
   if (cursorLocation == 0) return;
   
   cursorLocation--;
   
   /*===============================================*/
   /* What is the character at the cursor location? */
   /*===============================================*/
    
   characterToCheck = [theText characterAtIndex: cursorLocation];

   /*======================================*/
   /* We only balance a right parenthesis. */
   /*======================================*/
   
   if (characterToCheck != ')') return;

   /*======================================================================*/
   /* The nesting depth will start at zero. Each time a ')' is encountered */
   /* the nesting depth is incremented by one and each time a '(' is       */
   /* encountered the nesting depth is decremented by one. If a '(' is     */
   /* encountered when the nesting depth is zero (the starting value), the */
   /* matching parenthesis has been found.                                 */
   /*======================================================================*/
   
   nestingDepth = 0;

   /*==================================================*/
   /* Start looking for the matching left parenthesis. */
   /*==================================================*/
      
   while (cursorLocation-- && commandLength--) 
     {
      characterToCheck = [theText characterAtIndex: cursorLocation];
      if (characterToCheck == '(') 
        {
         if (nestingDepth == 0) 
           {
            [[super layoutManager] addTemporaryAttributes: hiliteColor forCharacterRange: NSMakeRange(cursorLocation, 1)];
		    [self performSelector: @selector(resetBackgroundColour:) withObject: NSStringFromRange(NSMakeRange(cursorLocation, 1)) afterDelay: 0.12];
		    return;
		   }
         else
		   { nestingDepth--; }
	    }
      else if (characterToCheck == ')') 
        { nestingDepth++; }
     }

   /*================================================*/
   /* Beep to indicate a matching ')' was not found. */
   /*================================================*/
   
   NSBeep();
  }

/***************/
/* insertText: */
/***************/
- (void) insertText: (NSString *) theText replacementRange: (NSRange) replacementRange
  {
   Environment *theEnvironment = [environment environment];
   
   /*================================================*/
   /* If the environment is executing a command (the */
   /* executionLock has been set), then don't allow  */
   /* any input unless the executing environment is  */
   /* requesting input.                              */
   /*================================================*/
   
   if ([[environment executionLock] tryLock])
     { [[environment executionLock] unlock]; }
   else if ([inputCharLock condition] != NEEDS_CHAR)
     { return; }
     
   /*================================*/
   /* Dump any text remaining in the */ 
   /* output buffer to the terminal. */
   /*================================*/
     
   [[dialogWindow windowController] dumpOutputBuffer];

   /*========================================================*/
   /* If the inputCharLock is set to NEEDS_CHAR, then we're  */
   /* waiting for input for functions like read or readline. */
   /* In this case we want to add any new input to the end   */
   /* of the terminal as we don't support inline editing of  */
   /* input to these functions.                              */
   /*========================================================*/

   if ([inputCharLock condition] == NEEDS_CHAR)
     {
      char *str; 
      size_t len;
      str = (char *) [theText UTF8String];
      charFound = str[0];
 
      NSRange theRange = { [[super string] length], 0 };
      [super setSelectedRange: theRange];

      [super insertText: theText replacementRange: replacementRange];
      
      if ((len = strlen(str)) >  1)
        {
         /* TBD Concatenate to existing buffer */
         if (inputBuffer != NULL)
           { free(inputBuffer); }
           
         inputBuffer = (char *) malloc(len);
         strcpy(inputBuffer,&str[1]);
         inputPos = 0;
        }
      
      [inputCharLock lock];
      [inputCharLock unlockWithCondition: HAS_CHAR];
      return;
     }
          
   if (! routerPrint)
     { 
      char *str;
      NSUInteger textLength;

      NSString *theTerminalText;
      NSUInteger inputOffset = [self inputStringOffset];
      
      theTerminalText = [self string];
      
      NSString *theCommand, *preCommand, *postCommand;
      textLength = [theTerminalText length];
      NSUInteger inputStart = textLength - inputOffset;
         
      NSRange selectionRange = [super selectedRange];

      if (selectionRange.location < inputStart)
        {
         NSRange theRange = { [[super string] length], 0 };
         [super setSelectedRange: theRange];
         selectionRange = theRange;
        }

      theCommand = [theTerminalText substringFromIndex: inputStart];
   
      preCommand = [theCommand substringToIndex: (selectionRange.location - inputStart)];
   
      postCommand = [theCommand substringFromIndex: (selectionRange.location + selectionRange.length - inputStart)];

      /*================================================================*/
      /* The string returned by UTF8String is placed in the autorelease */
      /* pool, so there is no need to release the str in this function. */
      /*================================================================*/

      str = (char *) [preCommand UTF8String];
      SetCommandString([environment environment],str);
      
      str = (char *) [theText UTF8String];
      AppendCommandString(theEnvironment,str);
      
      str = (char *) [postCommand UTF8String];
      AppendCommandString([environment environment],str);
     }
   else
     {
      NSRange theRange = { [[super string] length], 0 };
      [super setSelectedRange: theRange];
     }

   /*=======================================*/
   /* Add the text to the terminal at the   */
   /* current insertion point or selection. */
   /*=======================================*/
   
   [super insertText: theText replacementRange: replacementRange];
   
   if (! routerPrint)
     {
      [self balanceParentheses];
      
      if (CommandCompleteAndNotEmpty(theEnvironment))
        {
         // TBD At this point lock command input.
        }
     }
  }

/*************************************************************/
/* moveUpAndModifySelection: Overide of the up arrow + shift */
/*   keys to allow cycling through command history.          */
/*************************************************************/
- (void) moveUpAndModifySelection: (id) sender
  {
   CLIPSTerminalController *theController = (CLIPSTerminalController *) [self delegate];

   if (theController == nil)
     { [super moveUpAndModifySelection: sender]; }
   else if (theController->currentCommand->next != NULL)
     {
      [theController SwitchCommandFrom: theController->currentCommand
                                    To: theController->bottomCommand];
     }
  }

/*****************************************************************/
/* moveDownAndModifySelection: Overide of the down arrow + shift */
/*   keys to allow cycling through command history.              */
/*****************************************************************/
- (void) moveDownAndModifySelection: (id) sender
  {
   CLIPSTerminalController *theController = (CLIPSTerminalController *) [self delegate];

   if (theController == nil)
     { [super moveDownAndModifySelection: sender]; }
   else if (theController->currentCommand->prev != NULL)
     {
      [theController SwitchCommandFrom: theController->currentCommand
                                    To: theController->topCommand];
     }
  }

/*********************************************/
/* moveUp: Overide of the up arrow key to   */
/*   allow cycling through command history. */
/********************************************/
- (void) moveUp: (id) sender
   {
    CLIPSTerminalController *theController = (CLIPSTerminalController *) [self delegate];

    if (theController == nil)
      { [super moveUp: sender]; }
    else if (theController->currentCommand->next != NULL)
      {
       [theController SwitchCommandFrom: theController->currentCommand
                                     To: theController->currentCommand->next];
      }
   }

/***********************************************/
/* moveDown: Override of the down arrow key to */
/*   allow cycling through command history.    */
/***********************************************/
- (void) moveDown: (id) sender
   {
    CLIPSTerminalController *theController = (CLIPSTerminalController *) [self delegate];

    if (theController == nil)
      { [super moveUp: sender]; }
    else if (theController->currentCommand->prev != NULL)
      {
       [theController SwitchCommandFrom: theController->currentCommand
                                     To: theController->currentCommand->prev];
      }
   }

/*******************/
/* deleteBackward: */
/*******************/
- (void) deleteBackward: (id) sender
  {
   NSUInteger inputOffset = [self inputStringOffset];
   NSUInteger textLength;
   NSString *theTerminalText;
   char *str;

   /*====================================================*/
   /* If the input buffer is empty, then there are no    */
   /* characters to delete. Remove the current selection */
   /* and move the cursor to the end of the terminal.    */
   /*====================================================*/
   
   if (RouterData([environment environment])->CommandBufferInputCount <= 0) 
     {
      NSRange theRange = { [[super string] length], 0 };
      [super setSelectedRange: theRange];
      return;
     }

   /*==========================================================*/
   /* Is a running CLIPS function or program (such as the read */
   /* function) waiting for character input from stdin. If so, */
   /* move the cursor to the end of the terminal and just      */
   /* delete the last character.                               */
   /*==========================================================*/
   
   if ([inputCharLock condition] == NEEDS_CHAR)
     {
      NSRange theRange = { [[super string] length], 0 };
      [super setSelectedRange: theRange];
      [super deleteBackward: sender];
      charFound = '\b';
      [inputCharLock lock];
      [inputCharLock unlockWithCondition: HAS_CHAR];
      return;
     }

   /*=================================*/
   /* Retrieve the current selection. */
   /*=================================*/
          
   NSRange selectionRange = [super selectedRange];

   /*========================*/
   /* Determine the start of */
   /* the current command.   */
   /*========================*/
   
   theTerminalText = [self string];
   textLength = [theTerminalText length];
   NSUInteger inputStart = textLength - inputOffset;
  
   /*=============================================*/
   /* If the selection contains any prior output, */
   /* then remove the selection and move the      */
   /* cursor to the end of the terminal.          */
   /*=============================================*/
    
   if (selectionRange.location < inputStart)
     {
      NSRange theRange = { [[super string] length], 0 };
      [super setSelectedRange: theRange];
      return;
     }
 
   /*======================================*/
   /* If the cursor is at the beginning of */
   /* input, then deleting has no effect.  */
   /*======================================*/
   
   if ((selectionRange.location == inputStart) && selectionRange.length == 0)
     { return; }
 
   NSString *theCommand, *preCommand, *postCommand;
   
   theCommand = [theTerminalText substringFromIndex: inputStart];
   
   if (selectionRange.length == 0)
     { preCommand = [theCommand substringToIndex: ((selectionRange.location - inputStart) - 1)]; }
   else
     {
      preCommand = [theCommand substringToIndex: (selectionRange.location - inputStart)];
     }
   
   postCommand = [theCommand substringFromIndex: (selectionRange.location + selectionRange.length - inputStart)];

   str = (char *) [preCommand UTF8String];
   SetCommandString([environment environment],str);
   str = (char *) [postCommand UTF8String];
   AppendCommandString([environment environment],str);

   /*==============================================*/
   /* Process the backspace against the unexecuted */
   /* command being entered at the command prompt. */
   /*==============================================*/

   [super deleteBackward: sender];
   
   [self balanceParentheses];
  }
  
/***********************************************************/
/* waitForChar: Waits for the user to enter a character in */
/*   response to CLIPS router getc request from stdin.     */
/***********************************************************/
- (int) waitForChar
  {
   NSRange theRange = { [[super string] length], 0 };
   charFound = -1;

   /*============================================*/
   /* Bring the bottom of the terminal into view */
   /* so we can see the text being entered.      */
   /*============================================*/
   
   [super scrollRangeToVisible: theRange]; 

   /*=====================================*/
   /* Check for queued input from a UTF-8 */
   /* character or a pasted string.       */
   /*=====================================*/
   
   if (inputBuffer != NULL)
     {
      charFound = inputBuffer[inputPos];
      if (inputBuffer[++inputPos] == '\0')
        {
         free(inputBuffer);
         inputBuffer = NULL;
        }
        
      return charFound;
     }
     
   /*==============================================*/
   /* Change the condition on the lock to indicate */
   /* that an input character is needed.           */
   /*==============================================*/
            
   [inputCharLock lock];
   [inputCharLock unlockWithCondition: NEEDS_CHAR];

   /*=========================================================*/
   /* Block this thread until an input character is detected. */ 
   /*=========================================================*/
     
   [inputCharLock lockWhenCondition: HAS_CHAR];
   [inputCharLock unlockWithCondition: DOES_NOT_CHAR];
   
   /*=============================*/
   /* Return the character found. */
   /*=============================*/
   
   return charFound;
  }

/**************************/
/* resetBackgroundColour: */
/**************************/
- (void) resetBackgroundColour: (id) sender
  {
   [[super layoutManager] removeTemporaryAttribute: NSBackgroundColorAttributeName forCharacterRange: NSRangeFromString(sender)];
  }

/************************************************************************/
/* inputStringOffset: Determines the number of characters in the output */
/*    buffer that are associated with the input that user has currently */
/*    entered. This will typically be the command being entered after   */
/*    the CLIPS> prompt, but could also be the characters entered for   */
/*    an input function such as (read) or (readline). The environment   */
/*    value CommandBufferInputCount contains the number of bytes taken  */
/*    up by the current input, but we need to determine the number of   */
/*    UTF8 characters this represents. We compute this by looking at    */
/*    the last portion of input in the buffer adding one character at a */
/*    time until we get a number of bytes equal to the                  */
/*    CommandBufferInputCount.                                          */
/************************************************************************/
- (NSUInteger) inputStringOffset
  {
    NSString *theString;
    NSUInteger textLength;

    textLength = [[self string] length];
    NSUInteger inputByteCount = RouterData([environment environment])->CommandBufferInputCount;
    NSUInteger bufferByteCount = 0;
    NSUInteger charOffset = 0;
    
    while (bufferByteCount < inputByteCount)
      {
       charOffset++;
       theString = [[self string] substringFromIndex: (textLength - charOffset)];
       bufferByteCount = [theString lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
      }
   
   return charOffset;
  }

/*%%%%%%%%%%%%%%%%%%%%*/
/* Overridden Methods */
/*%%%%%%%%%%%%%%%%%%%%*/

/*************************/
/* performKeyEquivalent: */
/*************************/
/*
- (BOOL) performKeyEquivalent: (NSEvent *) theEvent
  {
   if ([inputCharLock condition] == NEEDS_CHAR)
     { return NO; }
        
   if (([theEvent modifierFlags] & NSCommandKeyMask) &&
       [[theEvent characters] isEqual: @"."])
     {
      Environment *theEnvironment = [environment environment];
      
      if ([theEvent modifierFlags] & NSShiftKeyMask)
        {
         SetHaltExecution(theEnvironment,true);
         CloseAllBatchSources(theEnvironment);
        }
      else
        {
#if DEFRULE_CONSTRUCT
         if (EngineData(theEnvironment)->ExecutingRule != NULL)
           { EngineData(theEnvironment)->HaltRules = true; }
         else
#endif
           {
            SetHaltExecution(theEnvironment,true);
            CloseAllBatchSources(theEnvironment);
           }
        }
       
      waitingForChar = NO;
      charFound = -1;
      [NSApp stopModal];

      return YES;
     }
     
   return NO;
  }
*/
/************************************************/
/* validateMenuItem: The cut and delete actions */
/*   are not allowed in the terminal window.    */
/************************************************/
- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
  {
   NSString *selectorString;
   selectorString = NSStringFromSelector([menuItem action]);
   
   /*============================================================*/
   /* The paste, cut, and delete actions are only allowed in the */
   /* terminal window when the selection is in the input area.   */
   /*============================================================*/
   
   if (([menuItem action] == @selector(paste:)) ||
       ([menuItem action] == @selector(cut:)) ||
       ([menuItem action] == @selector(delete:)))
     {
      NSUInteger textLength;

      NSString *theTerminalText;
      NSUInteger inputOffset = [self inputStringOffset];
      
      theTerminalText = [self string];
      
      textLength = [theTerminalText length];
      NSUInteger inputStart = textLength - inputOffset;
         
      NSRange selectionRange = [super selectedRange];

      if (selectionRange.location < inputStart)
        { return NO; }
     }
     
   /*====================================*/
   /* Otherwise, allow the superclass to */
   /* determine the valid menu items.    */
   /*====================================*/
   
   return [super validateMenuItem: menuItem];
  }
  
@end