/*
**  CEView+Fontification.m
**
**  Copyright (c) 2002, 2003
**
**  Author: Yen-Ju Chen <yjchenx@hotmail.com>
**          Bjoern Giesler <bjoern@giesler.de>
**
**  This program is free software; you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation; either version 2 of the License, or
**  (at your option) any later version.
**
**  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.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with this program; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "CEView+Fontification.h"
#include "CodeParser.h"
#include "FontificationHandler.h"
#include "BundleLoader.h"
#include "RulesetManager.h"
#include "CEViewTypesetter.h"
#include <AppKit/AppKit.h>

#define EQUAL(str) ([language isEqualToString: str])

@implementation CodeEditorView (Fontification)

- (BOOL) supportLanguage: (NSString *) language
{
  if ( [bundleLanguages containsObject: language] )
    {
      return YES;
    }
  return NO;
}

- (void) fontifyAccordingToLanguage: (NSString *) language
{
  [self fontifyAccordingToLanguage: language
                           inRange: NSMakeRange(0, [[self textStorage] length])];
}

- (void) fontifyAccordingToLanguage: (NSString *) language
                            inRange: (NSRange) range
{
  CodeParser *parser;
  id <FontificationHandler> handler;
  unsigned int index;
  NSFont *font = [[RulesetManager sharedRulesetManager] normalFont];
  NSColor *color = [[RulesetManager sharedRulesetManager] colorForType: @"Normal"];

  NSLog(@"fontify start...");

  index = [bundleLanguages indexOfObject: language];

  if (index == NSNotFound)
    return;

  if (fontificationHandlerClass)
    {
      handler = [[fontificationHandlerClass alloc] init];
    }
  else
    {
      return;
    }

  [handler setString: [self textStorage]];
  [handler setRange: range];

  parser = [[CodeParser alloc] initWithCodeHandler: handler
             withString: [[self string] substringWithRange: range]];

  [[self textStorage] beginEditing];

  [[self textStorage] addAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                         color, NSForegroundColorAttributeName,
                                          font, NSFontAttributeName, nil]
                             range: range];

  NSLog(@"Fontification parse begin");
  [parser parse];
  NSLog(@"Fontification parse end");

  [[self textStorage] endEditing];
  RELEASE(handler);
  RELEASE(parser);

  NSLog(@"fontify done !!!");
}

@end
