<commit_before>var React = require('react-native');
var {
  Image
} = React;

var GiftedFormManager = require('../GiftedFormManager');

module.exports = {

  getInitialState() {
    return {
      validationErrorMessage: null,
    };
  },

  propTypes: {
    name: React.PropTypes.string,
    title: React.PropTypes.string,
    formName: React.PropTypes.string,
    // image: ,
    widgetStyles: React.PropTypes.object,
    formStyles: React.PropTypes.object,
    validationImage: React.PropTypes.bool,
    openModal: React.PropTypes.func,
    // navigator: ,
    onFocus: React.PropTypes.func,
    onBlur: React.PropTypes.func,
  },

  getDefaultProps() {
    return {
      name: '',
      title: '',
      formName: '',
      image: null,
      widgetStyles: {},
      formStyles: {},
      validationImage: true,
      openModal: null,
      navigator: null,
      onFocus: () => {},
      onBlur: () => {},
    };
  },

  componentDidMount() {
    // get value from store
    var formState = GiftedFormManager.stores[this.props.formName];
    if (typeof formState !== 'undefined') {
      if (typeof formState.values[this.props.name] !== 'undefined') {
        this.setState({
          value: formState.values[this.props.name],
        });
        this._validate(formState.values[this.props.name]);
      }
    }
  },

  // get the styles by priority
  // defaultStyles < formStyles < widgetStyles
  getStyle(styleNames = []) {
    if (typeof styleNames === 'string') {
      styleNames = [styleNames];
    }

    if (typeof this.defaultStyles === 'undefined') {
      this.defaultStyles = {};
    }

    var styles = [];

    for (let i = 0; i < styleNames.length; i++) {
      if (typeof this.defaultStyles[styleNames[i]] !== 'undefined') {
        styles.push(this.defaultStyles[styleNames[i]]);
      }
    }

    for (let i = 0; i < styleNames.length; i++) {
      if (typeof this.props.formStyles[this.props.type] !== 'undefined') {
        if (typeof this.props.formStyles[this.props.type][styleNames[i]] !== 'undefined') {
          styles.push(this.props.formStyles[this.props.type][styleNames[i]]);
        }
      }
    }

    for (let i = 0; i < styleNames.length; i++) {
      if (typeof this.props.widgetStyles[styleNames[i]] !== 'undefined') {
        styles.push(this.props.widgetStyles[styleNames[i]]);
      }
    }

    return styles;
  },

  _validate(value) {
    if (typeof value === 'undefined') {
      value = this.state.value;
    }

    // @todo option for live validation ?
    var validators = GiftedFormManager.getValidators(this.props.formName, this.props.name);
    if (Array.isArray(validators.validate)) {
      if (validators.validate.length > 0) {
        var validation = GiftedFormManager.validateAndParseOne(this.props.name, value, {validate: validators.validate, title: validators.title});
        if (validation.isValid === false) {
          this.setState({
            validationErrorMessage: validation.message
          });
        } else {
          this.setState({
            validationErrorMessage: null
          });
        }
        this.props.onValidation && this.props.onValidation();
        // @todo set isvalid of modal children here
      }
    }
  },

  _setValue(value) {
    this.setState({
      value: value
    });
    GiftedFormManager.updateValue(this.props.formName, this.props.name, value);
  },

  _onChange(value) {
    this._setValue(value);
    this._validate(value);

    // @todo modal widgets validation - the modalwidget row should inform about validation status
  },

  // @todo options enable live checking
  _renderValidationError() {
    if (!(typeof this.state.value === 'undefined' || this.state.value === '') && this.state.validationErrorMessage !== null && this.state.validationErrorMessage !== '') {
      var ValidationErrorWidget = require('../widgets/ValidationErrorWidget');
      return (
        <ValidationErrorWidget
          message={this.state.validationErrorMessage}
        />
      );
    }
    return null;
  },

  _renderImage() {
    var validators = null;
    if (this.props.displayValue) {
      // in case of modal widget
      validators = GiftedFormManager.getValidators(this.props.formName, this.props.displayValue);
    } else {
      validators = GiftedFormManager.getValidators(this.props.formName, this.props.name);
    }

    let toValidate = false;
    if (Array.isArray(validators.validate)) {
      if (validators.validate.length > 0) {
        toValidate = true;
      }
    }

    // @todo image delete_sign / checkmark should be editable via option
    // @todo options enable live validation
    if (!(typeof this.state.value === 'undefined' || this.state.value === '') && this.state.validationErrorMessage !== null && this.props.image !== null && this.props.type !== 'OptionWidget' && this.props.validationImage === true && toValidate === true) {
      return (
        <Image
          style={this.getStyle('rowImage')}
          resizeMode={Image.resizeMode.contain}
          source={require('../icons/delete_sign.png')}
        />
      );
    } else if (!(typeof this.state.value === 'undefined' || this.state.value === '') && this.state.validationErrorMessage === null && this.props.image !== null && this.props.type !== 'OptionWidget' && this.props.validationImage === true && toValidate === true) {
      return (
        <Image
          style={this.getStyle('rowImage')}
          resizeMode={Image.resizeMode.contain}
          source={require('../icons/checkmark.png')}
        />
      );
    } else if (this.props.image !== null) {
      if (typeof this.props.image == 'object') {
        return(this.props.image);
      } else {
        return (
          <Image
            style={this.getStyle('rowImage')}
            resizeMode={Image.resizeMode.contain}
            source={this.props.image}
          />
        );
      }
    }
    return null;
  },
};
<commit_msg>Adds value and onValue props to WidgetMixin<commit_after>var React = require('react-native');
var {
  Image
} = React;

var GiftedFormManager = require('../GiftedFormManager');

module.exports = {

  getInitialState() {
    return {
      validationErrorMessage: null,
    };
  },

  propTypes: {
    name: React.PropTypes.string,
    title: React.PropTypes.string,
    formName: React.PropTypes.string,
    // image: ,
    widgetStyles: React.PropTypes.object,
    formStyles: React.PropTypes.object,
    validationImage: React.PropTypes.bool,
    openModal: React.PropTypes.func,
    // navigator: ,
    onFocus: React.PropTypes.func,
    onBlur: React.PropTypes.func,
    // If we want to store the state elsewhere (Redux store, for instance), we can use value and onValue prop
    value: React.PropTypes.string,
    onValue: React.PropTypes.func,
  },

  getDefaultProps() {
    return {
      name: '',
      title: '',
      formName: '',
      image: null,
      widgetStyles: {},
      formStyles: {},
      validationImage: true,
      openModal: null,
      navigator: null,
      onFocus: () => {},
      onBlur: () => {},
    };
  },

  componentDidMount() {
    // get value from prop
    if (typeof this.props.value !== 'undefined') {
      this.setState({
        value: this.props.value,
      });
      this._validate(this.props.value);
      return;
    }
    // get value from store
    var formState = GiftedFormManager.stores[this.props.formName];
    if (typeof formState !== 'undefined') {
      if (typeof formState.values[this.props.name] !== 'undefined') {
        this.setState({
          value: formState.values[this.props.name],
        });
        this._validate(formState.values[this.props.name]);
      }
    }
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.value && nextProps.value !== this.props.value) {
      this._onChange(nextProps.value);
    }
  },

  // get the styles by priority
  // defaultStyles < formStyles < widgetStyles
  getStyle(styleNames = []) {
    if (typeof styleNames === 'string') {
      styleNames = [styleNames];
    }

    if (typeof this.defaultStyles === 'undefined') {
      this.defaultStyles = {};
    }

    var styles = [];

    for (let i = 0; i < styleNames.length; i++) {
      if (typeof this.defaultStyles[styleNames[i]] !== 'undefined') {
        styles.push(this.defaultStyles[styleNames[i]]);
      }
    }

    for (let i = 0; i < styleNames.length; i++) {
      if (typeof this.props.formStyles[this.props.type] !== 'undefined') {
        if (typeof this.props.formStyles[this.props.type][styleNames[i]] !== 'undefined') {
          styles.push(this.props.formStyles[this.props.type][styleNames[i]]);
        }
      }
    }

    for (let i = 0; i < styleNames.length; i++) {
      if (typeof this.props.widgetStyles[styleNames[i]] !== 'undefined') {
        styles.push(this.props.widgetStyles[styleNames[i]]);
      }
    }

    return styles;
  },

  _validate(value) {
    if (typeof value === 'undefined') {
      value = this.state.value;
    }

    // @todo option for live validation ?
    var validators = GiftedFormManager.getValidators(this.props.formName, this.props.name);
    if (Array.isArray(validators.validate)) {
      if (validators.validate.length > 0) {
        var validation = GiftedFormManager.validateAndParseOne(this.props.name, value, {validate: validators.validate, title: validators.title});
        if (validation.isValid === false) {
          this.setState({
            validationErrorMessage: validation.message
          });
        } else {
          this.setState({
            validationErrorMessage: null
          });
        }
        this.props.onValidation && this.props.onValidation();
        // @todo set isvalid of modal children here
      }
    }
  },

  _setValue(value) {
    this.setState({
      value: value
    });
    GiftedFormManager.updateValue(this.props.formName, this.props.name, value);
  },

  _onChange(value) {
    this._setValue(value);
    this._validate(value);

    this.props.onValue && this.props.onValue(value);

    // @todo modal widgets validation - the modalwidget row should inform about validation status
  },

  // @todo options enable live checking
  _renderValidationError() {
    if (!(typeof this.state.value === 'undefined' || this.state.value === '') && this.state.validationErrorMessage !== null && this.state.validationErrorMessage !== '') {
      var ValidationErrorWidget = require('../widgets/ValidationErrorWidget');
      return (
        <ValidationErrorWidget
          message={this.state.validationErrorMessage}
        />
      );
    }
    return null;
  },

  _renderImage() {
    var validators = null;
    if (this.props.displayValue) {
      // in case of modal widget
      validators = GiftedFormManager.getValidators(this.props.formName, this.props.displayValue);
    } else {
      validators = GiftedFormManager.getValidators(this.props.formName, this.props.name);
    }

    let toValidate = false;
    if (Array.isArray(validators.validate)) {
      if (validators.validate.length > 0) {
        toValidate = true;
      }
    }

    // @todo image delete_sign / checkmark should be editable via option
    // @todo options enable live validation
    if (!(typeof this.state.value === 'undefined' || this.state.value === '') && this.state.validationErrorMessage !== null && this.props.image !== null && this.props.type !== 'OptionWidget' && this.props.validationImage === true && toValidate === true) {
      return (
        <Image
          style={this.getStyle('rowImage')}
          resizeMode={Image.resizeMode.contain}
          source={require('../icons/delete_sign.png')}
        />
      );
    } else if (!(typeof this.state.value === 'undefined' || this.state.value === '') && this.state.validationErrorMessage === null && this.props.image !== null && this.props.type !== 'OptionWidget' && this.props.validationImage === true && toValidate === true) {
      return (
        <Image
          style={this.getStyle('rowImage')}
          resizeMode={Image.resizeMode.contain}
          source={require('../icons/checkmark.png')}
        />
      );
    } else if (this.props.image !== null) {
      if (typeof this.props.image == 'object') {
        return(this.props.image);
      } else {
        return (
          <Image
            style={this.getStyle('rowImage')}
            resizeMode={Image.resizeMode.contain}
            source={this.props.image}
          />
        );
      }
    }
    return null;
  },
};
<|endoftext|>


<commit_before><commit_msg>Improved documentation.<commit_after><|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Jan 12 2015 11:54:03 GMT-0500 (EST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      "node_modules/jquery/dist/jquery.min.js",
      "src/*.js",
      "spec/**/*Spec.js"
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'junit'],

    junitReporter: {
      outputFile: 'test-results.xml'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<commit_msg>modify karma's config to support targeted tests<commit_after>// Karma configuration
// Generated on Mon Jan 12 2015 11:54:03 GMT-0500 (EST)

module.exports = function(config) {

  // list of files / patterns to load in the browser
  var files = [
    'node_modules/jquery/dist/jquery.min.js',
    'src/*.js'
  ];

  var specTargets = process.env.JASMINE_SPEC_TARGETS;
  if (specTargets !== undefined) {
    specTargets.split(',').forEach(function(target) {
      files.push(target);
    });
  } else {
    // default target all spec tests
    files.push('spec/*.js');
  }

  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: files,

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'junit'],

    junitReporter: {
      outputFile: 'test-results.xml'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>


<commit_before>const fs = require('fs-extra')
const path = require('path')
const cwd = process.cwd()

const postfixName = '-service'
const makeProject = (name) => {
  const newDir = []
  newDir.push(fs.ensureDir(`${cwd}/${name}/`))
  newDir.push(fs.ensureDir(`${cwd}/${name}/src/models/`))
  newDir.push(fs.ensureDir(`${cwd}/${name}/src/app/requester/`))
  newDir.push(fs.ensureDir(`${cwd}/${name}/src/app/responder/`))
  newDir.push(fs.ensureDir(`${cwd}/${name}/src/app/publisher/`))
  newDir.push(fs.ensureDir(`${cwd}/${name}/src/app/subscriber/`))

  return Promise.all(newDir)
}

module.exports = (name, options) => {
  if (name === undefined) throw new Error(`No name passed\nRun 'mslite help'`)
  if (options.postfix) {
    name += postfixName
  }
  makeProject(name).then(() => {
    const src = path.resolve(__dirname, '..', '..', 'files/action')
    const dest = `${cwd}/${name}`

    return fs.copy(src, dest)
  }).then(() => {
    console.log('made new projject')
  })
}
<commit_msg>feat(.gitkeep): added .gitkeep to ensure dir(s) are tracked by git from creation<commit_after>const fs = require('fs-extra')
const path = require('path')
const cwd = process.cwd()

const postfixName = '-service'
const makeProject = (name) => {
  const newDir = []
  newDir.push(fs.ensureDir(`${cwd}/${name}/`))
  newDir.push(fs.ensureFile(`${cwd}/${name}/src/models/.gitkeep`))
  newDir.push(fs.ensureDir(`${cwd}/${name}/src/app/requester/.gitkeep`))
  newDir.push(fs.ensureDir(`${cwd}/${name}/src/app/responder/.gitkeep`))
  newDir.push(fs.ensureDir(`${cwd}/${name}/src/app/publisher/.gitkeep`))
  newDir.push(fs.ensureDir(`${cwd}/${name}/src/app/subscriber/.gitkeep`))

  return Promise.all(newDir)
}

module.exports = (name, options) => {
  if (name === undefined) throw new Error(`No name passed\nRun 'mslite help'`)
  if (options.postfix) {
    name += postfixName
  }
  makeProject(name).then(() => {
    const src = path.resolve(__dirname, '..', '..', 'files/action')
    const dest = `${cwd}/${name}`

    return fs.copy(src, dest)
  }).then(() => {
    console.log('made new projject')
  })
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

// Copyright & License details are available under JXCORE_LICENSE file

var jxtools = require('jxtools');
var fs = require('fs');
var path = require('path');
var cp = require('child_process');
var common = require('../lib/common.js');

if (process.argv.length <= 2) {
  console.log("Too little arguments.");
  process.exit();
}

var argv2 = process.argv[2].replace("--", "");

var parsedArgv = jxcore.utils.argv.parse();
if (parsedArgv.h || parsedArgv.help) {
  jxcore.utils.console.log(common.getHelp(argv2));
  return;
}

var files = fs.readdirSync(path.join(__dirname,  '../lib/commands'));
if (files.indexOf(argv2 + '.js') === -1) {
  jxcore.utils.console.error('Unknown command', argv2);
  process.exit(-1);
}

var mod = require(path.join('../lib/commands', argv2 + '.js'));

var _run = function() {
  mod.run(function(err, txt) {
    if (err)
      jxcore.utils.console.error(err);
    if (txt)
      jxcore.utils.console.log(txt);
  });
};

if (mod.dontCheckCordova) {
  _run();
} else {
  cp.exec('cordova info', function (error, stdout, stderr) {
    if (error) {
      jxcore.utils.console.error('The `cordova info` test failed:', stderr.toString().trim());
      jxcore.utils.console.log(stderr.toString().trim());
      return;
    }

    _run()
  });
}

<commit_msg>exits with error code when error<commit_after>#!/usr/bin/env node

// Copyright & License details are available under JXCORE_LICENSE file

var jxtools = require('jxtools');
var fs = require('fs');
var path = require('path');
var cp = require('child_process');
var common = require('../lib/common.js');

if (process.argv.length <= 2) {
  console.log("Too little arguments.");
  process.exit();
}

var argv2 = process.argv[2].replace("--", "");

var parsedArgv = jxcore.utils.argv.parse();
if (parsedArgv.h || parsedArgv.help) {
  jxcore.utils.console.log(common.getHelp(argv2));
  return;
}

var files = fs.readdirSync(path.join(__dirname,  '../lib/commands'));
if (files.indexOf(argv2 + '.js') === -1) {
  jxcore.utils.console.error('Unknown command', argv2);
  process.exit(-1);
}

var mod = require(path.join('../lib/commands', argv2 + '.js'));

var _run = function() {
  mod.run(function(err, txt) {
    if (err)
      jxcore.utils.console.error(err);
    if (txt)
      jxcore.utils.console.log(txt);

    if (err)
      process.exit(1);
  });
};

if (mod.dontCheckCordova) {
  _run();
} else {
  cp.exec('cordova info', function (error, stdout, stderr) {
    if (error) {
      jxcore.utils.console.error('The `cordova info` test failed:', stderr.toString().trim());
      jxcore.utils.console.log(stderr.toString().trim());
      return;
    }

    _run()
  });
}

<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * xtc-cli
 *
 * xtc command line tools
 */

'use strict';

var cmdr = require('commander');
var c = require('chalk');
var Liftoff = require('liftoff');
var inquirer = require('inquirer');
var u = require('../lib/xtc-utils.js');

var log = console.log;
/*
var semver = require('semver');
var archy = require('archy');

var resolve = require('resolve');
var findup = require('findup-sync');
var gutil = require('gulp-util');
var prettyTime = require('pretty-hrtime');
*/

function handleArguments(env) {

	//var argv = env.argv;
	//var cliPackage = require('../package');
	var xtcMain = env.modulePath;
	var xtcJson = env.modulePackage;

	cmdr.version(require('../package').version);

	cmdr
		.command('help [command]')
		.description('Show usage information')
		.action(function(cmd) {
			'string' === typeof cmd
				? cmdr.emit(cmd, null, ['--help'])
				: cmdr.outputHelp()
			;
			process.exit();
		});

	cmdr
		.command('info')
		.description('Information about the project setup')
		.action(function(cmd) {
			var info =
				c.underline('\nProject information\n\n') +
				'xtc version: %s\n'
			;

			log(info, xtcJson.version);
		});

	cmdr
		.command('start')
		.description('Starts the xtc server. Use `-p [number]` to force a port.')
		.option('-p, --port [number]', 'Specify the port that xtc should listen to.')
		.action(function(cmd) {

			var xtcArgs = [xtcMain];

			u.checkLocalXtc(env);
			cmd.port && xtcArgs.push('--port='+ cmd.port);
			u.spawn('node', xtcArgs, { stdio: 'inherit' })
				.catch(u.fail)
			;
		});

	cmdr
		.command('build')
		.description('Start frontend asset build. Use `-d` for production build to dist target.')
		.option('-d, --dist', 'Run build in distribution mode. Output is minified.')
		.action(function(cmd) {

			var xtcArgs = ['--base=./node_modules/xtc']
				,grunt
			;

			u.checkLocalXtc(env);
			cmd.dist && xtcArgs.push('--dist');
			u.spawn('grunt', xtcArgs, { stdio: 'inherit' })
				.catch(u.fail)
			;
		});

	cmdr
		.command('mkmod')
		.description('Create new Terrific frontend modules')
		.action(function(cmd) {

			u.checkLocalXtc(env);
			u.spawn('yo', ['xtc:module'], { stdio: 'inherit' })
				.catch(u.fail)
			;
		});

	cmdr
		.command('mkskin')
		.description('Create new skins for a Terrific frontend module')
		.action(function(cmd) {

			u.checkLocalXtc(env);
			u.spawn('yo', ['xtc:skin'], { stdio: 'inherit'})
				.catch(u.fail)
			;
		});

	cmdr
		.command('setup')
		.description('Launch project setup')
		.action(function(cmd) {

			u.checkLocalXtc(env);
			u.spawn('yo', ['xtc'], { stdio: 'inherit'})
				.catch(u.fail)
			;
		});

	cmdr
		.command('install')
		.description('Install xtc and set up a project')
		.action(function(cmd) {

			var config = {};

			log(c.magenta('\nxtc install\n'));

			///////////////////////////////////////////////////////////////////
			// Ask user if cwd is the desired install location
			u.prompt({
					type : 'confirm',
					name : 'IsPathOk',
					message : 'Your project will be set up in ' +env.cwd +' Ok?',
					default: true
				})
				.then(
					function( answers ) {
						//config.projectPath = answers.projectPath;
						if (!answers.IsPathOk) {
							u.fail(0, 'Change to the desired directory and try again.')
						}
					},
					function(err) {
						u.fail(null, err.stack);
					}
				)

				///////////////////////////////////////////////////////////////////
				// Get list of xtc versions from npm (or cache)
				.then(function() {
					log('Getting list of xtc versions from npm...');
					return u.pkgInfo('xtc');
				})
				.catch(function(err) {
					if (err.message === 'getaddrinfo ENOTFOUND') {
						u.fail(null, 'DNS error. Are you offline?');
					} else {
						u.fail(err.stack);
					}
				})

				///////////////////////////////////////////////////////////////////
				// let the user choose the version to install. default to latest
				.then(function(versions) {

					var choices = versions.slice();

					choices.unshift(new inquirer.Separator());
					choices.push(new inquirer.Separator(), '#develop branch', new inquirer.Separator());
					choices.push('tarball', new inquirer.Separator());

					return u.prompt([
						{
							type : 'list',
							name : 'xtcVersion',
							message : 'Choose a version to install',
							paginated : true,
							default: 0,
							choices : choices
						}
					]);
				})
				.catch(function(err) {
					u.fail(null, err.stack);
				})

				///////////////////////////////////////////////////////////////////
				// npm install xtc@version (versioned generator is in xtc's dependencies)
				.then(function( answers ) {
					var xtcInstallArg;

					config.xtcVersion = answers.xtcVersion;

					if (config.xtcVersion == '#develop branch') {
						xtcInstallArg = 'git://github.com/marcdiethelm/xtc.git#develop';
					} else if (config.xtcVersion == 'tarball') { // todo: need a prompt for tarball location (and then save that…)
						xtcInstallArg = '/Users/marc/projects/xtc-0.8.0-rc1.tgz';
					} else {
						xtcInstallArg = 'xtc@'+ config.xtcVersion;
					}

					log(c.magenta('\nInstalling xtc module %s...\n'), config.xtcVersion);

					return u.spawn('npm', ['install', xtcInstallArg], { stdio: 'inherit'});
				})
				.then(function() {
						log(c.cyan('\nxtc module installed successfully'));
					}, function(code) {
						u.fail(code, 'I think something went wrong...')
					}
				)

				///////////////////////////////////////////////////////////////////
				// bundledDependencies don't have their dependencies installed. need to do that ourselves.
				// https://github.com/npm/npm/issues/2442
				.then(function() {
					log(c.magenta('\nInstalling generator-xtc dependencies...\n'));

					return u.spawn('npm', ['install'], {
						stdio: 'inherit'
					   ,cwd: './node_modules/generator-xtc'
					});
				})
				.then(function() {
						log(c.cyan('\ngenerator-xtc dependencies installed successfully'));
					}, function(code) {
						u.fail(code, 'I think something went wrong...')
					}
				)

				///////////////////////////////////////////////////////////////////
				// run project generator
				.then(function() {
					log(c.magenta('\nStarting project setup...\n'));
					return u.spawn('yo', ['xtc'], { stdio: 'inherit'});
				})
				.catch(function(code) {
					u.fail(code, 'I think something went wrong...');
				})
				.done(null, u.fail);
		});

	/*cmdr
		.command('update')
		.description('Update xtc module and create new project files in a folder for safe manual merging.')
		.action(function(cmd) {

			log('not implemented yet')

			u.checkLocalXtc(env);

			// you have version xx, you can update to versions [xy, xz, ...]

			// npm update xtc module

			// read install config and run a setup with pre-filled defaults (from original/last install)
			// write files to a new folder project-update-x.y.z for manual merging by the user.
		});*/

	cmdr.parse(process.argv);

	/*if (process.cwd() !== env.cwd) {
		process.chdir(env.cwd);
		console.log('Working directory changed to', c.magenta(env.cwd));
	}*/
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var cli = new Liftoff({
	name: 'xtc'
});

cli.launch(handleArguments);
<commit_msg>Display help if no args are entered<commit_after>#!/usr/bin/env node

/**
 * xtc-cli
 *
 * xtc command line tools
 */

'use strict';

var cmdr = require('commander');
var c = require('chalk');
var Liftoff = require('liftoff');
var inquirer = require('inquirer');
var u = require('../lib/xtc-utils.js');

var log = console.log;
/*
var semver = require('semver');
var archy = require('archy');

var resolve = require('resolve');
var findup = require('findup-sync');
var gutil = require('gulp-util');
var prettyTime = require('pretty-hrtime');
*/

function handleArguments(env) {

	//var argv = env.argv;
	//var cliPackage = require('../package');
	var xtcMain = env.modulePath;
	var xtcJson = env.modulePackage;

	cmdr.version(require('../package').version);

	cmdr
		.command('help [command]')
		.description('Show usage information')
		.action(function(cmd) {
			'string' === typeof cmd
				? cmdr.emit(cmd, null, ['--help'])
				: cmdr.outputHelp()
			;
			process.exit();
		});

	cmdr
		.command('info')
		.description('Information about the project setup')
		.action(function(cmd) {
			var info =
				c.underline('\nProject information\n\n') +
				'xtc version: %s\n'
			;

			log(info, xtcJson.version);
		});

	cmdr
		.command('start')
		.description('Starts the xtc server. Use `-p [number]` to force a port.')
		.option('-p, --port [number]', 'Specify the port that xtc should listen to.')
		.action(function(cmd) {

			var xtcArgs = [xtcMain];

			u.checkLocalXtc(env);
			cmd.port && xtcArgs.push('--port='+ cmd.port);
			u.spawn('node', xtcArgs, { stdio: 'inherit' })
				.catch(u.fail)
			;
		});

	cmdr
		.command('build')
		.description('Start frontend asset build. Use `-d` for production build to dist target.')
		.option('-d, --dist', 'Run build in distribution mode. Output is minified.')
		.action(function(cmd) {

			var xtcArgs = ['--base=./node_modules/xtc']
				,grunt
			;

			u.checkLocalXtc(env);
			cmd.dist && xtcArgs.push('--dist');
			u.spawn('grunt', xtcArgs, { stdio: 'inherit' })
				.catch(u.fail)
			;
		});

	cmdr
		.command('mkmod')
		.description('Create new Terrific frontend modules')
		.action(function(cmd) {

			u.checkLocalXtc(env);
			u.spawn('yo', ['xtc:module'], { stdio: 'inherit' })
				.catch(u.fail)
			;
		});

	cmdr
		.command('mkskin')
		.description('Create new skins for a Terrific frontend module')
		.action(function(cmd) {

			u.checkLocalXtc(env);
			u.spawn('yo', ['xtc:skin'], { stdio: 'inherit'})
				.catch(u.fail)
			;
		});

	cmdr
		.command('setup')
		.description('Launch project setup')
		.action(function(cmd) {

			u.checkLocalXtc(env);
			u.spawn('yo', ['xtc'], { stdio: 'inherit'})
				.catch(u.fail)
			;
		});

	cmdr
		.command('install')
		.description('Install xtc and set up a project')
		.action(function(cmd) {

			var config = {};

			log(c.magenta('\nxtc install\n'));

			///////////////////////////////////////////////////////////////////
			// Ask user if cwd is the desired install location
			u.prompt({
					type : 'confirm',
					name : 'IsPathOk',
					message : 'Your project will be set up in ' +env.cwd +' Ok?',
					default: true
				})
				.then(
					function( answers ) {
						//config.projectPath = answers.projectPath;
						if (!answers.IsPathOk) {
							u.fail(0, 'Change to the desired directory and try again.')
						}
					},
					function(err) {
						u.fail(null, err.stack);
					}
				)

				///////////////////////////////////////////////////////////////////
				// Get list of xtc versions from npm (or cache)
				.then(function() {
					log('Getting list of xtc versions from npm...');
					return u.pkgInfo('xtc');
				})
				.catch(function(err) {
					if (err.message === 'getaddrinfo ENOTFOUND') {
						u.fail(null, 'DNS error. Are you offline?');
					} else {
						u.fail(err.stack);
					}
				})

				///////////////////////////////////////////////////////////////////
				// let the user choose the version to install. default to latest
				.then(function(versions) {

					var choices = versions.slice();

					choices.unshift(new inquirer.Separator());
					choices.push(new inquirer.Separator(), '#develop branch', new inquirer.Separator());
					choices.push('tarball', new inquirer.Separator());

					return u.prompt([
						{
							type : 'list',
							name : 'xtcVersion',
							message : 'Choose a version to install',
							paginated : true,
							default: 0,
							choices : choices
						}
					]);
				})
				.catch(function(err) {
					u.fail(null, err.stack);
				})

				///////////////////////////////////////////////////////////////////
				// npm install xtc@version (versioned generator is in xtc's dependencies)
				.then(function( answers ) {
					var xtcInstallArg;

					config.xtcVersion = answers.xtcVersion;

					if (config.xtcVersion == '#develop branch') {
						xtcInstallArg = 'git://github.com/marcdiethelm/xtc.git#develop';
					} else if (config.xtcVersion == 'tarball') { // todo: need a prompt for tarball location (and then save that…)
						xtcInstallArg = '/Users/marc/projects/xtc-0.8.0-rc1.tgz';
					} else {
						xtcInstallArg = 'xtc@'+ config.xtcVersion;
					}

					log(c.magenta('\nInstalling xtc module %s...\n'), config.xtcVersion);

					return u.spawn('npm', ['install', xtcInstallArg], { stdio: 'inherit'});
				})
				.then(function() {
						log(c.cyan('\nxtc module installed successfully'));
					}, function(code) {
						u.fail(code, 'I think something went wrong...')
					}
				)

				///////////////////////////////////////////////////////////////////
				// bundledDependencies don't have their dependencies installed. need to do that ourselves.
				// https://github.com/npm/npm/issues/2442
				.then(function() {
					log(c.magenta('\nInstalling generator-xtc dependencies...\n'));

					return u.spawn('npm', ['install'], {
						stdio: 'inherit'
					   ,cwd: './node_modules/generator-xtc'
					});
				})
				.then(function() {
						log(c.cyan('\ngenerator-xtc dependencies installed successfully'));
					}, function(code) {
						u.fail(code, 'I think something went wrong...')
					}
				)

				///////////////////////////////////////////////////////////////////
				// run project generator
				.then(function() {
					log(c.magenta('\nStarting project setup...\n'));
					return u.spawn('yo', ['xtc'], { stdio: 'inherit'});
				})
				.catch(function(code) {
					u.fail(code, 'I think something went wrong...');
				})
				.done(null, u.fail);
		});

	/*cmdr
		.command('update')
		.description('Update xtc module and create new project files in a folder for safe manual merging.')
		.action(function(cmd) {

			log('not implemented yet')

			u.checkLocalXtc(env);

			// you have version xx, you can update to versions [xy, xz, ...]

			// npm update xtc module

			// read install config and run a setup with pre-filled defaults (from original/last install)
			// write files to a new folder project-update-x.y.z for manual merging by the user.
		});*/

	cmdr.parse(process.argv);
	if (!cmdr.args.length) cmdr.help();

	/*if (process.cwd() !== env.cwd) {
		process.chdir(env.cwd);
		console.log('Working directory changed to', c.magenta(env.cwd));
	}*/
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var cli = new Liftoff({
	name: 'xtc'
});

cli.launch(handleArguments);
<|endoftext|>


<commit_before>/*eslint-env node*/
module.exports = function (grunt) {
    'use strict';

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        copy: {
            dagre: {
                expand: true,
                flatten: true,
                src: 'node_modules/dagre/dist/dagre.js',
                dest: '../src/plugin/iframe_root/modules/vendor/dagre'
            },
            // 'dagre-d3': {
            //     expand: true,
            //     flatten: true,
            //     src: 'node_modules/dagre-d3/dist/dagre-d3.js',
            //     dest: '../src/plugin/iframe_root/js/vendor/dagre-d3'
            // },
            // 'pure-uuid': {
            //     expand: true,
            //     flatten: true,
            //     src: 'node_modules/pure-uuid/uuid.js',
            //     dest: '../src/plugin/iframe_root/modules/vendor/pure-uuid'
            // },
            preact: {
                expand: true,
                flatten: true,
                src: 'node_modules/preact/dist/preact.umd.js',
                dest: '../src/plugin/iframe_root/modules/vendor/preact'
            },
            htm: {
                expand: true,
                flatten: true,
                src: 'node_modules/htm/dist/htm.umd.js',
                dest: '../src/plugin/iframe_root/modules/vendor/htm'
            },
            leaflet: {
                expand: true,
                flatten: false,
                cwd: 'node_modules/leaflet/dist',
                src: [
                    'leaflet-src.js',
                    'leaflet.css',
                    'images/*',
                ],
                dest: '../src/plugin/iframe_root/modules/vendor/leaflet'
            }
        },
        clean: {
            options: {
                force: true
            },
            vendor: '../src/plugin/iframe_root/modules/vendor/*',
            bower: './bower_components/',
            npm: './node_modules/'
        }
    });

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
};
<commit_msg>cleanup file<commit_after>/*eslint-env node*/
module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        copy: {
            dagre: {
                expand: true,
                flatten: true,
                src: 'node_modules/dagre/dist/dagre.js',
                dest: '../src/plugin/iframe_root/modules/vendor/dagre'
            },
            preact: {
                expand: true,
                flatten: true,
                src: 'node_modules/preact/dist/preact.umd.js',
                dest: '../src/plugin/iframe_root/modules/vendor/preact'
            },
            htm: {
                expand: true,
                flatten: true,
                src: 'node_modules/htm/dist/htm.umd.js',
                dest: '../src/plugin/iframe_root/modules/vendor/htm'
            },
            leaflet: {
                expand: true,
                flatten: false,
                cwd: 'node_modules/leaflet/dist',
                src: [
                    'leaflet-src.js',
                    'leaflet.css',
                    'images/*',
                ],
                dest: '../src/plugin/iframe_root/modules/vendor/leaflet'
            }
        },
        clean: {
            options: {
                force: true
            },
            vendor: '../src/plugin/iframe_root/modules/vendor/*',
            bower: './bower_components/',
            npm: './node_modules/'
        }
    });

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
};
<|endoftext|>


<commit_before><commit_msg>PATH_TO_CCXT_BASE -> PATH_TO_CCXT transpile.js<commit_after><|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  function wordRegexp(words) {
    return new RegExp("^((" + words.join(")|(") + "))\\b");
  }

  var wordOperators = wordRegexp(["and", "or", "not", "is"]);
  var commonKeywords = ["as", "assert", "break", "class", "continue",
                        "def", "del", "elif", "else", "except", "finally",
                        "for", "from", "global", "if", "import",
                        "lambda", "pass", "raise", "return",
                        "try", "while", "with", "yield", "in"];
  var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
                        "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
                        "enumerate", "eval", "filter", "float", "format", "frozenset",
                        "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
                        "input", "int", "isinstance", "issubclass", "iter", "len",
                        "list", "locals", "map", "max", "memoryview", "min", "next",
                        "object", "oct", "open", "ord", "pow", "property", "range",
                        "repr", "reversed", "round", "set", "setattr", "slice",
                        "sorted", "staticmethod", "str", "sum", "super", "tuple",
                        "type", "vars", "zip", "__import__", "NotImplemented",
                        "Ellipsis", "__debug__"];
  CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));

  function top(state) {
    return state.scopes[state.scopes.length - 1];
  }

  CodeMirror.defineMode("python", function(conf, parserConf) {
    var ERRORCLASS = "error";

    var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;
    //               (Backwards-compatiblity with old, cumbersome config system)
    var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,
                     parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@])/]
    for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)

    var hangingIndent = parserConf.hangingIndent || conf.indentUnit;

    var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
    if (parserConf.extra_keywords != undefined)
      myKeywords = myKeywords.concat(parserConf.extra_keywords);

    if (parserConf.extra_builtins != undefined)
      myBuiltins = myBuiltins.concat(parserConf.extra_builtins);

    var py3 = !(parserConf.version && Number(parserConf.version) < 3)
    if (py3) {
      // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
      var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
      myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
      myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
      var stringPrefixes = new RegExp("^(([rbuf]|(br)|(fr))?('{3}|\"{3}|['\"]))", "i");
    } else {
      var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
      myKeywords = myKeywords.concat(["exec", "print"]);
      myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
                                      "file", "intern", "long", "raw_input", "reduce", "reload",
                                      "unichr", "unicode", "xrange", "False", "True", "None"]);
      var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(myKeywords);
    var builtins = wordRegexp(myBuiltins);

    // tokenizers
    function tokenBase(stream, state) {
      var sol = stream.sol() && state.lastToken != "\\"
      if (sol) state.indent = stream.indentation()
      // Handle scope changes
      if (sol && top(state).type == "py") {
        var scopeOffset = top(state).offset;
        if (stream.eatSpace()) {
          var lineOffset = stream.indentation();
          if (lineOffset > scopeOffset)
            pushPyScope(state);
          else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")
            state.errorToken = true;
          return null;
        } else {
          var style = tokenBaseInner(stream, state);
          if (scopeOffset > 0 && dedent(stream, state))
            style += " " + ERRORCLASS;
          return style;
        }
      }
      return tokenBaseInner(stream, state);
    }

    function tokenBaseInner(stream, state) {
      if (stream.eatSpace()) return null;

      // Handle Comments
      if (stream.match(/^#.*/)) return "comment";

      // Handle Number Literals
      if (stream.match(/^[0-9\.]/, false)) {
        var floatLiteral = false;
        // Floats
        if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
        if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
        if (stream.match(/^\.\d+/)) { floatLiteral = true; }
        if (floatLiteral) {
          // Float literals may be "imaginary"
          stream.eat(/J/i);
          return "number";
        }
        // Integers
        var intLiteral = false;
        // Hex
        if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
        // Binary
        if (stream.match(/^0b[01_]+/i)) intLiteral = true;
        // Octal
        if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
        // Decimal
        if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
          // Decimal literals may be "imaginary"
          stream.eat(/J/i);
          // TODO - Can you have imaginary longs?
          intLiteral = true;
        }
        // Zero by itself with no other piece of number.
        if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
        if (intLiteral) {
          // Integer literals may be "long"
          stream.eat(/L/i);
          return "number";
        }
      }

      // Handle Strings
      if (stream.match(stringPrefixes)) {
        var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;
        if (!isFmtString) {
          state.tokenize = tokenStringFactory(stream.current(), state.tokenize);
          return state.tokenize(stream, state);
        } else {
          state.tokenize = formatStringFactory(stream.current(), state.tokenize);
          return state.tokenize(stream, state);
        }
      }

      for (var i = 0; i < operators.length; i++)
        if (stream.match(operators[i])) return "operator"

      if (stream.match(delimiters)) return "punctuation";

      if (state.lastToken == "." && stream.match(identifiers))
        return "property";

      if (stream.match(keywords) || stream.match(wordOperators))
        return "keyword";

      if (stream.match(builtins))
        return "builtin";

      if (stream.match(/^(self|cls)\b/))
        return "variable-2";

      if (stream.match(identifiers)) {
        if (state.lastToken == "def" || state.lastToken == "class")
          return "def";
        return "variable";
      }

      // Handle non-detected items
      stream.next();
      return ERRORCLASS;
    }

    function formatStringFactory(delimiter, tokenOuter) {
      while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenNestedExpr(depth) {
        return function(stream, state) {
          var inner = tokenBaseInner(stream, state)
          console.log(inner, stream.current())
          if (inner == "punctuation") {
            if (stream.current() == "{") {
              state.tokenize = tokenNestedExpr(depth + 1)
            } else if (stream.current() == "}") {
              if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1)
              else state.tokenize = tokenString
            }
          }
          return inner
        }
      }

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\{\}\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenOuter;
            return OUTCLASS;
          } else if (stream.match('{{')) {
            // ignore {{ in f-str
            return OUTCLASS;
          } else if (stream.match('{', false)) {
            // switch to nested mode
            state.tokenize = tokenNestedExpr(0)
            if (stream.current()) return OUTCLASS;
            else return state.tokenize()
          } else if (stream.match('}}')) {
            return OUTCLASS;
          } else if (stream.match('}')) {
            // single } in f-string is an error
            return ERRORCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenOuter;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function tokenStringFactory(delimiter, tokenOuter) {
      while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenOuter;
            return OUTCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenOuter;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function pushPyScope(state) {
      while (top(state).type != "py") state.scopes.pop()
      state.scopes.push({offset: top(state).offset + conf.indentUnit,
                         type: "py",
                         align: null})
    }

    function pushBracketScope(stream, state, type) {
      var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1
      state.scopes.push({offset: state.indent + hangingIndent,
                         type: type,
                         align: align})
    }

    function dedent(stream, state) {
      var indented = stream.indentation();
      while (state.scopes.length > 1 && top(state).offset > indented) {
        if (top(state).type != "py") return true;
        state.scopes.pop();
      }
      return top(state).offset != indented;
    }

    function tokenLexer(stream, state) {
      if (stream.sol()) state.beginningOfLine = true;

      var style = state.tokenize(stream, state);
      var current = stream.current();

      // Handle decorators
      if (state.beginningOfLine && current == "@")
        return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;

      if (/\S/.test(current)) state.beginningOfLine = false;

      if ((style == "variable" || style == "builtin")
          && state.lastToken == "meta")
        style = "meta";

      // Handle scope changes.
      if (current == "pass" || current == "return")
        state.dedent += 1;

      if (current == "lambda") state.lambda = true;
      if (current == ":" && !state.lambda && top(state).type == "py")
        pushPyScope(state);

      if (current.length == 1 && !/string|comment/.test(style)) {
        var delimiter_index = "[({".indexOf(current);
        if (delimiter_index != -1)
          pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));

        delimiter_index = "])}".indexOf(current);
        if (delimiter_index != -1) {
          if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
          else return ERRORCLASS;
        }
      }
      if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
        if (state.scopes.length > 1) state.scopes.pop();
        state.dedent -= 1;
      }

      return style;
    }

    var external = {
      startState: function(basecolumn) {
        return {
          tokenize: tokenBase,
          scopes: [{offset: basecolumn || 0, type: "py", align: null}],
          indent: basecolumn || 0,
          lastToken: null,
          lambda: false,
          dedent: 0
        };
      },

      token: function(stream, state) {
        var addErr = state.errorToken;
        if (addErr) state.errorToken = false;
        var style = tokenLexer(stream, state);

        if (style && style != "comment")
          state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
        if (style == "punctuation") style = null;

        if (stream.eol() && state.lambda)
          state.lambda = false;
        return addErr ? style + " " + ERRORCLASS : style;
      },

      indent: function(state, textAfter) {
        if (state.tokenize != tokenBase)
          return state.tokenize.isString ? CodeMirror.Pass : 0;

        var scope = top(state), closing = scope.type == textAfter.charAt(0)
        if (scope.align != null)
          return scope.align - (closing ? 1 : 0)
        else
          return scope.offset - (closing ? hangingIndent : 0)
      },

      electricInput: /^\s*[\}\]\)]$/,
      closeBrackets: {triples: "'\""},
      lineComment: "#",
      fold: "indent"
    };
    return external;
  });

  CodeMirror.defineMIME("text/x-python", "python");

  var words = function(str) { return str.split(" "); };

  CodeMirror.defineMIME("text/x-cython", {
    name: "python",
    extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+
                          "extern gil include nogil property public "+
                          "readonly struct union DEF IF ELIF ELSE")
  });

});
<commit_msg>Remove debug statement<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  function wordRegexp(words) {
    return new RegExp("^((" + words.join(")|(") + "))\\b");
  }

  var wordOperators = wordRegexp(["and", "or", "not", "is"]);
  var commonKeywords = ["as", "assert", "break", "class", "continue",
                        "def", "del", "elif", "else", "except", "finally",
                        "for", "from", "global", "if", "import",
                        "lambda", "pass", "raise", "return",
                        "try", "while", "with", "yield", "in"];
  var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
                        "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
                        "enumerate", "eval", "filter", "float", "format", "frozenset",
                        "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
                        "input", "int", "isinstance", "issubclass", "iter", "len",
                        "list", "locals", "map", "max", "memoryview", "min", "next",
                        "object", "oct", "open", "ord", "pow", "property", "range",
                        "repr", "reversed", "round", "set", "setattr", "slice",
                        "sorted", "staticmethod", "str", "sum", "super", "tuple",
                        "type", "vars", "zip", "__import__", "NotImplemented",
                        "Ellipsis", "__debug__"];
  CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));

  function top(state) {
    return state.scopes[state.scopes.length - 1];
  }

  CodeMirror.defineMode("python", function(conf, parserConf) {
    var ERRORCLASS = "error";

    var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;
    //               (Backwards-compatiblity with old, cumbersome config system)
    var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,
                     parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@])/]
    for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)

    var hangingIndent = parserConf.hangingIndent || conf.indentUnit;

    var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
    if (parserConf.extra_keywords != undefined)
      myKeywords = myKeywords.concat(parserConf.extra_keywords);

    if (parserConf.extra_builtins != undefined)
      myBuiltins = myBuiltins.concat(parserConf.extra_builtins);

    var py3 = !(parserConf.version && Number(parserConf.version) < 3)
    if (py3) {
      // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
      var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
      myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
      myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
      var stringPrefixes = new RegExp("^(([rbuf]|(br)|(fr))?('{3}|\"{3}|['\"]))", "i");
    } else {
      var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
      myKeywords = myKeywords.concat(["exec", "print"]);
      myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
                                      "file", "intern", "long", "raw_input", "reduce", "reload",
                                      "unichr", "unicode", "xrange", "False", "True", "None"]);
      var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(myKeywords);
    var builtins = wordRegexp(myBuiltins);

    // tokenizers
    function tokenBase(stream, state) {
      var sol = stream.sol() && state.lastToken != "\\"
      if (sol) state.indent = stream.indentation()
      // Handle scope changes
      if (sol && top(state).type == "py") {
        var scopeOffset = top(state).offset;
        if (stream.eatSpace()) {
          var lineOffset = stream.indentation();
          if (lineOffset > scopeOffset)
            pushPyScope(state);
          else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")
            state.errorToken = true;
          return null;
        } else {
          var style = tokenBaseInner(stream, state);
          if (scopeOffset > 0 && dedent(stream, state))
            style += " " + ERRORCLASS;
          return style;
        }
      }
      return tokenBaseInner(stream, state);
    }

    function tokenBaseInner(stream, state) {
      if (stream.eatSpace()) return null;

      // Handle Comments
      if (stream.match(/^#.*/)) return "comment";

      // Handle Number Literals
      if (stream.match(/^[0-9\.]/, false)) {
        var floatLiteral = false;
        // Floats
        if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
        if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
        if (stream.match(/^\.\d+/)) { floatLiteral = true; }
        if (floatLiteral) {
          // Float literals may be "imaginary"
          stream.eat(/J/i);
          return "number";
        }
        // Integers
        var intLiteral = false;
        // Hex
        if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
        // Binary
        if (stream.match(/^0b[01_]+/i)) intLiteral = true;
        // Octal
        if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
        // Decimal
        if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
          // Decimal literals may be "imaginary"
          stream.eat(/J/i);
          // TODO - Can you have imaginary longs?
          intLiteral = true;
        }
        // Zero by itself with no other piece of number.
        if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
        if (intLiteral) {
          // Integer literals may be "long"
          stream.eat(/L/i);
          return "number";
        }
      }

      // Handle Strings
      if (stream.match(stringPrefixes)) {
        var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;
        if (!isFmtString) {
          state.tokenize = tokenStringFactory(stream.current(), state.tokenize);
          return state.tokenize(stream, state);
        } else {
          state.tokenize = formatStringFactory(stream.current(), state.tokenize);
          return state.tokenize(stream, state);
        }
      }

      for (var i = 0; i < operators.length; i++)
        if (stream.match(operators[i])) return "operator"

      if (stream.match(delimiters)) return "punctuation";

      if (state.lastToken == "." && stream.match(identifiers))
        return "property";

      if (stream.match(keywords) || stream.match(wordOperators))
        return "keyword";

      if (stream.match(builtins))
        return "builtin";

      if (stream.match(/^(self|cls)\b/))
        return "variable-2";

      if (stream.match(identifiers)) {
        if (state.lastToken == "def" || state.lastToken == "class")
          return "def";
        return "variable";
      }

      // Handle non-detected items
      stream.next();
      return ERRORCLASS;
    }

    function formatStringFactory(delimiter, tokenOuter) {
      while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenNestedExpr(depth) {
        return function(stream, state) {
          var inner = tokenBaseInner(stream, state)
          if (inner == "punctuation") {
            if (stream.current() == "{") {
              state.tokenize = tokenNestedExpr(depth + 1)
            } else if (stream.current() == "}") {
              if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1)
              else state.tokenize = tokenString
            }
          }
          return inner
        }
      }

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\{\}\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenOuter;
            return OUTCLASS;
          } else if (stream.match('{{')) {
            // ignore {{ in f-str
            return OUTCLASS;
          } else if (stream.match('{', false)) {
            // switch to nested mode
            state.tokenize = tokenNestedExpr(0)
            if (stream.current()) return OUTCLASS;
            else return state.tokenize()
          } else if (stream.match('}}')) {
            return OUTCLASS;
          } else if (stream.match('}')) {
            // single } in f-string is an error
            return ERRORCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenOuter;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function tokenStringFactory(delimiter, tokenOuter) {
      while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenOuter;
            return OUTCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenOuter;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function pushPyScope(state) {
      while (top(state).type != "py") state.scopes.pop()
      state.scopes.push({offset: top(state).offset + conf.indentUnit,
                         type: "py",
                         align: null})
    }

    function pushBracketScope(stream, state, type) {
      var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1
      state.scopes.push({offset: state.indent + hangingIndent,
                         type: type,
                         align: align})
    }

    function dedent(stream, state) {
      var indented = stream.indentation();
      while (state.scopes.length > 1 && top(state).offset > indented) {
        if (top(state).type != "py") return true;
        state.scopes.pop();
      }
      return top(state).offset != indented;
    }

    function tokenLexer(stream, state) {
      if (stream.sol()) state.beginningOfLine = true;

      var style = state.tokenize(stream, state);
      var current = stream.current();

      // Handle decorators
      if (state.beginningOfLine && current == "@")
        return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;

      if (/\S/.test(current)) state.beginningOfLine = false;

      if ((style == "variable" || style == "builtin")
          && state.lastToken == "meta")
        style = "meta";

      // Handle scope changes.
      if (current == "pass" || current == "return")
        state.dedent += 1;

      if (current == "lambda") state.lambda = true;
      if (current == ":" && !state.lambda && top(state).type == "py")
        pushPyScope(state);

      if (current.length == 1 && !/string|comment/.test(style)) {
        var delimiter_index = "[({".indexOf(current);
        if (delimiter_index != -1)
          pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));

        delimiter_index = "])}".indexOf(current);
        if (delimiter_index != -1) {
          if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
          else return ERRORCLASS;
        }
      }
      if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
        if (state.scopes.length > 1) state.scopes.pop();
        state.dedent -= 1;
      }

      return style;
    }

    var external = {
      startState: function(basecolumn) {
        return {
          tokenize: tokenBase,
          scopes: [{offset: basecolumn || 0, type: "py", align: null}],
          indent: basecolumn || 0,
          lastToken: null,
          lambda: false,
          dedent: 0
        };
      },

      token: function(stream, state) {
        var addErr = state.errorToken;
        if (addErr) state.errorToken = false;
        var style = tokenLexer(stream, state);

        if (style && style != "comment")
          state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
        if (style == "punctuation") style = null;

        if (stream.eol() && state.lambda)
          state.lambda = false;
        return addErr ? style + " " + ERRORCLASS : style;
      },

      indent: function(state, textAfter) {
        if (state.tokenize != tokenBase)
          return state.tokenize.isString ? CodeMirror.Pass : 0;

        var scope = top(state), closing = scope.type == textAfter.charAt(0)
        if (scope.align != null)
          return scope.align - (closing ? 1 : 0)
        else
          return scope.offset - (closing ? hangingIndent : 0)
      },

      electricInput: /^\s*[\}\]\)]$/,
      closeBrackets: {triples: "'\""},
      lineComment: "#",
      fold: "indent"
    };
    return external;
  });

  CodeMirror.defineMIME("text/x-python", "python");

  var words = function(str) { return str.split(" "); };

  CodeMirror.defineMIME("text/x-cython", {
    name: "python",
    extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+
                          "extern gil include nogil property public "+
                          "readonly struct union DEF IF ELIF ELSE")
  });

});
<|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

/**
 * Author: Koh Zi Han, based on implementation by Koh Zi Chun
 */

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("scheme", function () {
    var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
        ATOM = "atom", NUMBER = "number", BRACKET = "bracket";
    var INDENT_WORD_SKIP = 2;

    function makeKeywords(str) {
        var obj = {}, words = str.split(" ");
        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
        return obj;
    }

    var keywords = makeKeywords("λ case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt #f floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? #t tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?");
    var indentKeys = makeKeywords("define let letrec let* lambda");

    function stateStack(indent, type, prev) { // represents a state stack object
        this.indent = indent;
        this.type = type;
        this.prev = prev;
    }

    function pushStack(state, indent, type) {
        state.indentStack = new stateStack(indent, type, state.indentStack);
    }

    function popStack(state) {
        state.indentStack = state.indentStack.prev;
    }

    var binaryMatcher = new RegExp(/^(?:[-+]i|[-+][01]+#*(?:\/[01]+#*)?i|[-+]?[01]+#*(?:\/[01]+#*)?@[-+]?[01]+#*(?:\/[01]+#*)?|[-+]?[01]+#*(?:\/[01]+#*)?[-+](?:[01]+#*(?:\/[01]+#*)?)?i|[-+]?[01]+#*(?:\/[01]+#*)?)(?=[()\s;"]|$)/i);
    var octalMatcher = new RegExp(/^(?:[-+]i|[-+][0-7]+#*(?:\/[0-7]+#*)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?@[-+]?[0-7]+#*(?:\/[0-7]+#*)?|[-+]?[0-7]+#*(?:\/[0-7]+#*)?[-+](?:[0-7]+#*(?:\/[0-7]+#*)?)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?)(?=[()\s;"]|$)/i);
    var hexMatcher = new RegExp(/^(?:[-+]i|[-+][\da-f]+#*(?:\/[\da-f]+#*)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?@[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?[-+](?:[\da-f]+#*(?:\/[\da-f]+#*)?)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?)(?=[()\s;"]|$)/i);
    var decimalMatcher = new RegExp(/^(?:[-+]i|[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)i|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)@[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)?i|(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*))(?=[()\s;"]|$)/i);

    function isBinaryNumber (stream) {
        return stream.match(binaryMatcher);
    }

    function isOctalNumber (stream) {
        return stream.match(octalMatcher);
    }

    function isDecimalNumber (stream, backup) {
        if (backup === true) {
            stream.backUp(1);
        }
        return stream.match(decimalMatcher);
    }

    function isHexNumber (stream) {
        return stream.match(hexMatcher);
    }

    return {
        startState: function () {
            return {
                indentStack: null,
                indentation: 0,
                mode: false,
                sExprComment: false,
                sExprQuote: false
            };
        },

        token: function (stream, state) {
            if (state.indentStack == null && stream.sol()) {
                // update indentation, but only if indentStack is empty
                state.indentation = stream.indentation();
            }

            // skip spaces
            if (stream.eatSpace()) {
                return null;
            }
            var returnType = null;

            switch(state.mode){
                case "string": // multi-line string parsing mode
                    var next, escaped = false;
                    while ((next = stream.next()) != null) {
                        if (next == "\"" && !escaped) {

                            state.mode = false;
                            break;
                        }
                        escaped = !escaped && next == "\\";
                    }
                    returnType = STRING; // continue on in scheme-string mode
                    break;
                case "comment": // comment parsing mode
                    var next, maybeEnd = false;
                    while ((next = stream.next()) != null) {
                        if (next == "#" && maybeEnd) {

                            state.mode = false;
                            break;
                        }
                        maybeEnd = (next == "|");
                    }
                    returnType = COMMENT;
                    break;
                case "s-expr-comment": // s-expr commenting mode
                    state.mode = false;
                    if(stream.peek() == "(" || stream.peek() == "["){
                        // actually start scheme s-expr commenting mode
                        state.sExprComment = 0;
                    }else{
                        // if not we just comment the entire of the next token
                        stream.eatWhile(/[^\s\(\)\[\]]/); // eat symbol atom
                        returnType = COMMENT;
                        break;
                    }
                default: // default parsing mode
                    var ch = stream.next();

                    if (ch == "\"") {
                        state.mode = "string";
                        returnType = STRING;

                    } else if (ch == "'") {
                        if (stream.peek() == "(" || stream.peek() == "["){
                            if (typeof state.sExprQuote != "number") {
                                state.sExprQuote = 0;
                            } // else already in a quoted expression
                            returnType = ATOM;
                        } else {
                            stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/);
                            returnType = ATOM;
                        }
                    } else if (ch == '#') {
                        if (stream.eat("|")) {                    // Multi-line comment
                            state.mode = "comment"; // toggle to comment mode
                            returnType = COMMENT;
                        } else if (stream.eat(/[tf]/i)) {            // #t/#f (atom)
                            returnType = ATOM;
                        } else if (stream.eat(';')) {                // S-Expr comment
                            state.mode = "s-expr-comment";
                            returnType = COMMENT;
                        } else {
                            var numTest = null, hasExactness = false, hasRadix = true;
                            if (stream.eat(/[ei]/i)) {
                                hasExactness = true;
                            } else {
                                stream.backUp(1);       // must be radix specifier
                            }
                            if (stream.match(/^#b/i)) {
                                numTest = isBinaryNumber;
                            } else if (stream.match(/^#o/i)) {
                                numTest = isOctalNumber;
                            } else if (stream.match(/^#x/i)) {
                                numTest = isHexNumber;
                            } else if (stream.match(/^#d/i)) {
                                numTest = isDecimalNumber;
                            } else if (stream.match(/^[-+0-9.]/, false)) {
                                hasRadix = false;
                                numTest = isDecimalNumber;
                            // re-consume the intial # if all matches failed
                            } else if (!hasExactness) {
                                stream.eat('#');
                            }
                            if (numTest != null) {
                                if (hasRadix && !hasExactness) {
                                    // consume optional exactness after radix
                                    stream.match(/^#[ei]/i);
                                }
                                if (numTest(stream))
                                    returnType = NUMBER;
                            }
                        }
                    } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) { // match non-prefixed number, must be decimal
                        returnType = NUMBER;
                    } else if (ch == ";") { // comment
                        stream.skipToEnd(); // rest of the line is a comment
                        returnType = COMMENT;
                    } else if (ch == "(" || ch == "[") {
                      var keyWord = ''; var indentTemp = stream.column(), letter;
                        /**
                        Either
                        (indent-word ..
                        (non-indent-word ..
                        (;something else, bracket, etc.
                        */

                        while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) {
                            keyWord += letter;
                        }

                        if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word

                            pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
                        } else { // non-indent word
                            // we continue eating the spaces
                            stream.eatSpace();
                            if (stream.eol() || stream.peek() == ";") {
                                // nothing significant after
                                // we restart indentation 1 space after
                                pushStack(state, indentTemp + 1, ch);
                            } else {
                                pushStack(state, indentTemp + stream.current().length, ch); // else we match
                            }
                        }
                        stream.backUp(stream.current().length - 1); // undo all the eating

                        if(typeof state.sExprComment == "number") state.sExprComment++;
                        if(typeof state.sExprQuote == "number") state.sExprQuote++;

                        returnType = BRACKET;
                    } else if (ch == ")" || ch == "]") {
                        returnType = BRACKET;
                        if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
                            popStack(state);

                            if(typeof state.sExprComment == "number"){
                                if(--state.sExprComment == 0){
                                    returnType = COMMENT; // final closing bracket
                                    state.sExprComment = false; // turn off s-expr commenting mode
                                }
                            }
                            if(typeof state.sExprQuote == "number"){
                                if(--state.sExprQuote == 0){
                                    returnType = ATOM; // final closing bracket
                                    state.sExprQuote = false; // turn off s-expr quote mode
                                }
                            }
                        }
                    } else {
                        stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/);

                        if (keywords && keywords.propertyIsEnumerable(stream.current())) {
                            returnType = BUILTIN;
                        } else returnType = "variable";
                    }
            }
            return (typeof state.sExprComment == "number") ? COMMENT : ((typeof state.sExprQuote == "number") ? ATOM : returnType);
        },

        indent: function (state) {
            if (state.indentStack == null) return state.indentation;
            return state.indentStack.indent;
        },

        closeBrackets: {pairs: "()[]{}\"\""},
        lineComment: ";;"
    };
});

CodeMirror.defineMIME("text/x-scheme", "scheme");

});
<commit_msg>[scheme mode] Add more special indentation words and keywords<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

/**
 * Author: Koh Zi Han, based on implementation by Koh Zi Chun
 */

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("scheme", function () {
    var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
        ATOM = "atom", NUMBER = "number", BRACKET = "bracket";
    var INDENT_WORD_SKIP = 2;

    function makeKeywords(str) {
        var obj = {}, words = str.split(" ");
        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
        return obj;
    }

    var keywords = makeKeywords("λ case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax define-macro defmacro delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt #f floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? #t tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?");
    var indentKeys = makeKeywords("define let letrec let* lambda define-macro defmacro let-syntax letrec-syntax define-syntax syntax-rules");

    function stateStack(indent, type, prev) { // represents a state stack object
        this.indent = indent;
        this.type = type;
        this.prev = prev;
    }

    function pushStack(state, indent, type) {
        state.indentStack = new stateStack(indent, type, state.indentStack);
    }

    function popStack(state) {
        state.indentStack = state.indentStack.prev;
    }

    var binaryMatcher = new RegExp(/^(?:[-+]i|[-+][01]+#*(?:\/[01]+#*)?i|[-+]?[01]+#*(?:\/[01]+#*)?@[-+]?[01]+#*(?:\/[01]+#*)?|[-+]?[01]+#*(?:\/[01]+#*)?[-+](?:[01]+#*(?:\/[01]+#*)?)?i|[-+]?[01]+#*(?:\/[01]+#*)?)(?=[()\s;"]|$)/i);
    var octalMatcher = new RegExp(/^(?:[-+]i|[-+][0-7]+#*(?:\/[0-7]+#*)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?@[-+]?[0-7]+#*(?:\/[0-7]+#*)?|[-+]?[0-7]+#*(?:\/[0-7]+#*)?[-+](?:[0-7]+#*(?:\/[0-7]+#*)?)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?)(?=[()\s;"]|$)/i);
    var hexMatcher = new RegExp(/^(?:[-+]i|[-+][\da-f]+#*(?:\/[\da-f]+#*)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?@[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?[-+](?:[\da-f]+#*(?:\/[\da-f]+#*)?)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?)(?=[()\s;"]|$)/i);
    var decimalMatcher = new RegExp(/^(?:[-+]i|[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)i|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)@[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)?i|(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*))(?=[()\s;"]|$)/i);

    function isBinaryNumber (stream) {
        return stream.match(binaryMatcher);
    }

    function isOctalNumber (stream) {
        return stream.match(octalMatcher);
    }

    function isDecimalNumber (stream, backup) {
        if (backup === true) {
            stream.backUp(1);
        }
        return stream.match(decimalMatcher);
    }

    function isHexNumber (stream) {
        return stream.match(hexMatcher);
    }

    return {
        startState: function () {
            return {
                indentStack: null,
                indentation: 0,
                mode: false,
                sExprComment: false,
                sExprQuote: false
            };
        },

        token: function (stream, state) {
            if (state.indentStack == null && stream.sol()) {
                // update indentation, but only if indentStack is empty
                state.indentation = stream.indentation();
            }

            // skip spaces
            if (stream.eatSpace()) {
                return null;
            }
            var returnType = null;

            switch(state.mode){
                case "string": // multi-line string parsing mode
                    var next, escaped = false;
                    while ((next = stream.next()) != null) {
                        if (next == "\"" && !escaped) {

                            state.mode = false;
                            break;
                        }
                        escaped = !escaped && next == "\\";
                    }
                    returnType = STRING; // continue on in scheme-string mode
                    break;
                case "comment": // comment parsing mode
                    var next, maybeEnd = false;
                    while ((next = stream.next()) != null) {
                        if (next == "#" && maybeEnd) {

                            state.mode = false;
                            break;
                        }
                        maybeEnd = (next == "|");
                    }
                    returnType = COMMENT;
                    break;
                case "s-expr-comment": // s-expr commenting mode
                    state.mode = false;
                    if(stream.peek() == "(" || stream.peek() == "["){
                        // actually start scheme s-expr commenting mode
                        state.sExprComment = 0;
                    }else{
                        // if not we just comment the entire of the next token
                        stream.eatWhile(/[^\s\(\)\[\]]/); // eat symbol atom
                        returnType = COMMENT;
                        break;
                    }
                default: // default parsing mode
                    var ch = stream.next();

                    if (ch == "\"") {
                        state.mode = "string";
                        returnType = STRING;

                    } else if (ch == "'") {
                        if (stream.peek() == "(" || stream.peek() == "["){
                            if (typeof state.sExprQuote != "number") {
                                state.sExprQuote = 0;
                            } // else already in a quoted expression
                            returnType = ATOM;
                        } else {
                            stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/);
                            returnType = ATOM;
                        }
                    } else if (ch == '#') {
                        if (stream.eat("|")) {                    // Multi-line comment
                            state.mode = "comment"; // toggle to comment mode
                            returnType = COMMENT;
                        } else if (stream.eat(/[tf]/i)) {            // #t/#f (atom)
                            returnType = ATOM;
                        } else if (stream.eat(';')) {                // S-Expr comment
                            state.mode = "s-expr-comment";
                            returnType = COMMENT;
                        } else {
                            var numTest = null, hasExactness = false, hasRadix = true;
                            if (stream.eat(/[ei]/i)) {
                                hasExactness = true;
                            } else {
                                stream.backUp(1);       // must be radix specifier
                            }
                            if (stream.match(/^#b/i)) {
                                numTest = isBinaryNumber;
                            } else if (stream.match(/^#o/i)) {
                                numTest = isOctalNumber;
                            } else if (stream.match(/^#x/i)) {
                                numTest = isHexNumber;
                            } else if (stream.match(/^#d/i)) {
                                numTest = isDecimalNumber;
                            } else if (stream.match(/^[-+0-9.]/, false)) {
                                hasRadix = false;
                                numTest = isDecimalNumber;
                            // re-consume the intial # if all matches failed
                            } else if (!hasExactness) {
                                stream.eat('#');
                            }
                            if (numTest != null) {
                                if (hasRadix && !hasExactness) {
                                    // consume optional exactness after radix
                                    stream.match(/^#[ei]/i);
                                }
                                if (numTest(stream))
                                    returnType = NUMBER;
                            }
                        }
                    } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) { // match non-prefixed number, must be decimal
                        returnType = NUMBER;
                    } else if (ch == ";") { // comment
                        stream.skipToEnd(); // rest of the line is a comment
                        returnType = COMMENT;
                    } else if (ch == "(" || ch == "[") {
                      var keyWord = ''; var indentTemp = stream.column(), letter;
                        /**
                        Either
                        (indent-word ..
                        (non-indent-word ..
                        (;something else, bracket, etc.
                        */

                        while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) {
                            keyWord += letter;
                        }

                        if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word

                            pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
                        } else { // non-indent word
                            // we continue eating the spaces
                            stream.eatSpace();
                            if (stream.eol() || stream.peek() == ";") {
                                // nothing significant after
                                // we restart indentation 1 space after
                                pushStack(state, indentTemp + 1, ch);
                            } else {
                                pushStack(state, indentTemp + stream.current().length, ch); // else we match
                            }
                        }
                        stream.backUp(stream.current().length - 1); // undo all the eating

                        if(typeof state.sExprComment == "number") state.sExprComment++;
                        if(typeof state.sExprQuote == "number") state.sExprQuote++;

                        returnType = BRACKET;
                    } else if (ch == ")" || ch == "]") {
                        returnType = BRACKET;
                        if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
                            popStack(state);

                            if(typeof state.sExprComment == "number"){
                                if(--state.sExprComment == 0){
                                    returnType = COMMENT; // final closing bracket
                                    state.sExprComment = false; // turn off s-expr commenting mode
                                }
                            }
                            if(typeof state.sExprQuote == "number"){
                                if(--state.sExprQuote == 0){
                                    returnType = ATOM; // final closing bracket
                                    state.sExprQuote = false; // turn off s-expr quote mode
                                }
                            }
                        }
                    } else {
                        stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/);

                        if (keywords && keywords.propertyIsEnumerable(stream.current())) {
                            returnType = BUILTIN;
                        } else returnType = "variable";
                    }
            }
            return (typeof state.sExprComment == "number") ? COMMENT : ((typeof state.sExprQuote == "number") ? ATOM : returnType);
        },

        indent: function (state) {
            if (state.indentStack == null) return state.indentation;
            return state.indentStack.indent;
        },

        closeBrackets: {pairs: "()[]{}\"\""},
        lineComment: ";;"
    };
});

CodeMirror.defineMIME("text/x-scheme", "scheme");

});
<|endoftext|>