<commit_before>var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var minifycss = require('gulp-minify-css');
var del = require('del');
var uglify = require('gulp-uglify');
var runSequence = require('run-sequence');

// Path config
var config = {
  bootstrapDir: './node_modules/bootstrap-sass',
  publicDir: './dist',
  devDir: './src/dev'
};

// Dev Bootstrap Sass
gulp.task('dev:bootstrapcss', function () {
  return gulp.src(config.devDir + '/sass/bootstrap.scss')
      .pipe(sass({
        includePaths: [config.bootstrapDir + '/assets/stylesheets']
      }))
      .pipe(gulp.dest(config.devDir + '/bootstrap/css'));
});

// Dist Bootstrap CSS
gulp.task('dist:bootstrapcss', function () {
  return gulp.src(config.devDir + '/bootstrap/css/bootstrap.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/bootstrap/css'));
});

// Dev Bootstrap Fonts
gulp.task('dev:fonts', function () {
  return gulp.src(config.bootstrapDir + '/assets/fonts/bootstrap/**/*')
      .pipe(gulp.dest(config.devDir + '/bootstrap/fonts'));
});

// Dist Bootstrap Fonts
gulp.task('dist:fonts', function () {
  return gulp.src(config.devDir + '/bootstrap/fonts/*')
      .pipe(gulp.dest(config.publicDir + '/bootstrap/fonts'));
});

// Dist Bootstrap Fonts
gulp.task('dist:fonts', function () {
  return gulp.src(config.bootstrapDir + '/assets/fonts/bootstrap/**/*')
      .pipe(gulp.dest(config.devDir + '/bootstrap/fonts'));
});

// Dev Front CSS
gulp.task('dev:frontcss', function () {
  return gulp.src(config.devDir + '/sass/front.scss')
      .pipe(sass())
      .pipe(autoprefixer())
      .pipe(gulp.dest(config.devDir + '/css'));
});

// Dist Front CSS
gulp.task('dist:frontcss', ['dev:frontcss'], function () {
  return gulp.src(config.sourceDir + '/css/front.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/css'));
});

// Dev JS
gulp.task('dev:js', function () {
  // Front JS
  gulp.src([config.devDir + '/js/common/*.js', '!' + config.devDir + '/js/common/front.js'])
      .pipe(concat('front.js'))
      .pipe(gulp.dest(config.devDir + '/js/common'));
});

// Build For Dev
gulp.task('dev:build', ['dev:bootstrapcss', 'dev:fonts', 'dev:frontcss', 'dev:js']);

// Build Clean
gulp.task('clean:dev', function () {
  return del([
    config.devDir + '/css/front.css',
    config.devDir + '/js/common/front.js',
    config.devDir + '/bootstrap/css',
    config.devDir + '/bootstrap/fonts'
  ]);
});

// Dist
gulp.task('dist:build', ['dev:build'], function () {
  // Bootstrap CSS
  gulp.src(config.devDir + '/bootstrap/css/bootstrap.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/bootstrap/css'));

  // Bootstrap Fonts
  gulp.src(config.devDir + '/bootstrap/fonts/*')
      .pipe(gulp.dest(config.publicDir + '/bootstrap/fonts'));

  // Front CSS
  gulp.src(config.devDir + '/css/front.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/css'));

  // Theme CSS
  gulp.src(config.devDir + '/css/theme/*.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/css/theme'));

  // Bootstrap JS
  gulp.src(config.devDir + '/bootstrap/js/bootstrap.js')
      .pipe(uglify())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/bootstrap/js'));

  // Front JS
  gulp.src(config.devDir + '/js/common/front.js')
      .pipe(uglify())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/js/common'));

  // JQuery JS
  gulp.src(config.devDir + '/js/jquery/jquery.min.js')
      .pipe(gulp.dest(config.publicDir + '/js/jquery'));

  // FileUpload JS
  gulp.src(config.devDir + '/js/plugin/fileupload/fileupload.js')
      .pipe(uglify())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/js/plugin/fileupload'));

  // Datepicker JS
  gulp.src(config.devDir + '/js/plugin/datepicker/ui/datepicker-zh-CN.js')
      .pipe(uglify())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/js/plugin/datepicker'));

  // Datepicker CSS
  gulp.src(config.devDir + '/css/datepicker/ui/**/*')
      .pipe(gulp.dest(config.publicDir + '/css/datepicker/ui/'));

  gulp.src(config.devDir + '/js/plugin/datepicker/ui/jquery-ui.min.js')
      .pipe(gulp.dest(config.publicDir + '/js/plugin/datepicker'));

  // Gallery
  gulp.src(config.devDir + '/js/plugin/gallery/**/*')
      .pipe(gulp.dest(config.publicDir + '/js/plugin/gallery/'));

  // Animate CSS
  gulp.src(config.devDir + '/css/animate/animate.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/css/animate/'));

  // Bootstrap DatetimePicker
  gulp.src(config.devDir + '/js/plugin/bootstrap-datetimepicker/build/**/*')
      .pipe(gulp.dest(config.publicDir + '/js/plugin/bootstrap-datetimepicker'));
});

// Clean Dist
gulp.task('clean:dist', function () {
  del(config.publicDir);
});

// Clean All
gulp.task('clean', ['clean:dev', 'clean:dist']);

// Web Server
gulp.task('browserSync', function () {
  browserSync.init({
    server: config.devDir,
    port: '8160'
  })
});

// Concat and Minify CSS
gulp.task('createSkin', function() {
  return gulp.src(['src/dev/css/double_column.css','src/dev/css/footer.css','src/dev/css/navbar.css'])
      .pipe(concat('skin2.css'))
      .pipe(gulp.dest('src/dev/css/skin'))
      .pipe(rename({suffix: '.min'}))
      .pipe(minifycss())
      .pipe(gulp.dest('src/dev/css/skin'))
});

// Watch change
gulp.task('watch', ['browserSync'], function () {
  gulp.watch(config.devDir + '/**/*.html', browserSync.reload);

  gulp.watch(config.devDir + '/sass/**/*.scss', function () {
    runSequence('clean:dev', 'dev:build', browserSync.reload);
  });
});

// Default task
gulp.task('default', function () {
  runSequence('clean:dev', 'dev:build', 'watch');
});<commit_msg>ADD：生成文档所需css<commit_after>var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var minifycss = require('gulp-minify-css');
var del = require('del');
var uglify = require('gulp-uglify');
var runSequence = require('run-sequence');

// Path config
var config = {
  bootstrapDir: './node_modules/bootstrap-sass',
  publicDir: './dist',
  devDir: './src/dev'
};

// Dev Bootstrap Sass
gulp.task('dev:bootstrapcss', function () {
  return gulp.src(config.devDir + '/sass/bootstrap.scss')
      .pipe(sass({
        includePaths: [config.bootstrapDir + '/assets/stylesheets']
      }))
      .pipe(gulp.dest(config.devDir + '/bootstrap/css'));
});

// Dist Bootstrap CSS
gulp.task('dist:bootstrapcss', function () {
  return gulp.src(config.devDir + '/bootstrap/css/bootstrap.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/bootstrap/css'));
});

// Dev Bootstrap Fonts
gulp.task('dev:fonts', function () {
  return gulp.src(config.bootstrapDir + '/assets/fonts/bootstrap/**/*')
      .pipe(gulp.dest(config.devDir + '/bootstrap/fonts'));
});

// Dist Bootstrap Fonts
gulp.task('dist:fonts', function () {
  return gulp.src(config.devDir + '/bootstrap/fonts/*')
      .pipe(gulp.dest(config.publicDir + '/bootstrap/fonts'));
});

// Dist Bootstrap Fonts
gulp.task('dist:fonts', function () {
  return gulp.src(config.bootstrapDir + '/assets/fonts/bootstrap/**/*')
      .pipe(gulp.dest(config.devDir + '/bootstrap/fonts'));
});

// Dev Front CSS
gulp.task('dev:frontcss', function () {
  gulp.src(config.devDir + '/sass/doc.scss')
      .pipe(sass())
      .pipe(autoprefixer())
      .pipe(gulp.dest(config.devDir + '/css'));

  return gulp.src(config.devDir + '/sass/front.scss')
      .pipe(sass())
      .pipe(autoprefixer())
      .pipe(gulp.dest(config.devDir + '/css'));
});

// Dist Front CSS
gulp.task('dist:frontcss', ['dev:frontcss'], function () {
  return gulp.src(config.sourceDir + '/css/front.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/css'));
});

// Dev JS
gulp.task('dev:js', function () {
  // Front JS
  gulp.src([config.devDir + '/js/common/*.js', '!' + config.devDir + '/js/common/front.js'])
      .pipe(concat('front.js'))
      .pipe(gulp.dest(config.devDir + '/js/common'));
});

// Build For Dev
gulp.task('dev:build', ['dev:bootstrapcss', 'dev:fonts', 'dev:frontcss', 'dev:js']);

// Build Clean
gulp.task('clean:dev', function () {
  return del([
    config.devDir + '/css/front.css',
    config.devDir + '/js/common/front.js',
    config.devDir + '/bootstrap/css',
    config.devDir + '/bootstrap/fonts'
  ]);
});

// Dist
gulp.task('dist:build', ['dev:build'], function () {
  // Bootstrap CSS
  gulp.src(config.devDir + '/bootstrap/css/bootstrap.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/bootstrap/css'));

  // Bootstrap Fonts
  gulp.src(config.devDir + '/bootstrap/fonts/*')
      .pipe(gulp.dest(config.publicDir + '/bootstrap/fonts'));

  // Front CSS
  gulp.src(config.devDir + '/css/front.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/css'));

  // Theme CSS
  gulp.src(config.devDir + '/css/theme/*.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/css/theme'));

  // Bootstrap JS
  gulp.src(config.devDir + '/bootstrap/js/bootstrap.js')
      .pipe(uglify())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/bootstrap/js'));

  // Front JS
  gulp.src(config.devDir + '/js/common/front.js')
      .pipe(uglify())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/js/common'));

  // JQuery JS
  gulp.src(config.devDir + '/js/jquery/jquery.min.js')
      .pipe(gulp.dest(config.publicDir + '/js/jquery'));

  // FileUpload JS
  gulp.src(config.devDir + '/js/plugin/fileupload/fileupload.js')
      .pipe(uglify())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/js/plugin/fileupload'));

  // Datepicker JS
  gulp.src(config.devDir + '/js/plugin/datepicker/ui/datepicker-zh-CN.js')
      .pipe(uglify())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/js/plugin/datepicker'));

  // Datepicker CSS
  gulp.src(config.devDir + '/css/datepicker/ui/**/*')
      .pipe(gulp.dest(config.publicDir + '/css/datepicker/ui/'));

  gulp.src(config.devDir + '/js/plugin/datepicker/ui/jquery-ui.min.js')
      .pipe(gulp.dest(config.publicDir + '/js/plugin/datepicker'));

  // Gallery
  gulp.src(config.devDir + '/js/plugin/gallery/**/*')
      .pipe(gulp.dest(config.publicDir + '/js/plugin/gallery/'));

  // Animate CSS
  gulp.src(config.devDir + '/css/animate/animate.css')
      .pipe(minifycss())
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest(config.publicDir + '/css/animate/'));

  // Bootstrap DatetimePicker
  gulp.src(config.devDir + '/js/plugin/bootstrap-datetimepicker/build/**/*')
      .pipe(gulp.dest(config.publicDir + '/js/plugin/bootstrap-datetimepicker'));
});

// Clean Dist
gulp.task('clean:dist', function () {
  del(config.publicDir);
});

// Clean All
gulp.task('clean', ['clean:dev', 'clean:dist']);

// Web Server
gulp.task('browserSync', function () {
  browserSync.init({
    server: config.devDir,
    port: '8160'
  })
});

// Concat and Minify CSS
gulp.task('createSkin', function() {
  return gulp.src(['src/dev/css/double_column.css','src/dev/css/footer.css','src/dev/css/navbar.css'])
      .pipe(concat('skin2.css'))
      .pipe(gulp.dest('src/dev/css/skin'))
      .pipe(rename({suffix: '.min'}))
      .pipe(minifycss())
      .pipe(gulp.dest('src/dev/css/skin'))
});

// Watch change
gulp.task('watch', ['browserSync'], function () {
  gulp.watch(config.devDir + '/**/*.html', browserSync.reload);

  gulp.watch(config.devDir + '/sass/**/*.scss', function () {
    runSequence('clean:dev', 'dev:build', browserSync.reload);
  });
});

// Default task
gulp.task('default', function () {
  runSequence('clean:dev', 'dev:build', 'watch');
});<|endoftext|>


<commit_before>// inspired by https://gist.github.com/dmitruksergey/8441752

var gulp = require('gulp'),
    jade = require('gulp-jade'),
    sass = require('gulp-sass'),
    gulpif = require('gulp-if'),
    autoprefixer = require('gulp-autoprefixer'),
    minifyCSS = require('gulp-minify-css'),
    imagemin = require('gulp-imagemin'),
    browsersync = require('browser-sync').create(),
    del = require('del'),
    runSequence = require('run-sequence'),
    nodemon = require('gulp-nodemon'),
    ghPages = require('gulp-gh-pages'),
    replace = require('gulp-replace');

var isDev = false;
var staticMode = false;
var output_path = 'resources/public';
var deployed_path = 'deployed';
var dev_path = {
  sass: ['assets/stylesheets/*.scss', '!assets/stylesheets/_*.scss'],
  jadedev: ['assets/jade/**/*.jade', '!assets/jade/_*.jade'],
  jade: ['assets/jade/**/*.jade', '!assets/jade/_*.jade', '!assets/jade/layout/*', '!assets/jade/mixins/*'],
  js: ['assets/javascripts/**/*.js'],
  images: ['assets/images/**/*', '!assets/images/dev-*'],
  favicons: ['assets/icons/favicon.*'],
  fonts: ['assets/stylesheets/fonts/*','node_modules/font-awesome/fonts/fontawesome-webfont.*'],
  port: 7777
};
var build_path = {
  css: output_path + '/stylesheets/',
  html: output_path + '/',
  js: output_path + '/javascripts/',
  images: output_path + '/images',
  fonts: output_path + '/fonts/',
  library: output_path + '/library/'
};

gulp.task('jade', function () {
  var jadeSrc = isDev ? dev_path.jadedev : dev_path.jade;
  return gulp.src(jadeSrc)
      .pipe(jade({
        pretty: true,
        locals: {
          "javascriptsBase": "javascripts",
          "stylesheetsBase": "stylesheets",
          "imagesBase": "images",
          "initData": "",
          "applicationName": "Stonecutter",
          "staticMode": staticMode
        }
      }))
      .on('error', function(err) {
        console.log(err);
        this.emit('end');
      })
      .pipe(gulpif(staticMode, replace(/>!/g, '>')))
      .pipe(gulp.dest(build_path.html))
      .pipe(browsersync.stream());
});

gulp.task('sass', function () {
  return gulp.src(dev_path.sass)
      .pipe(sass({style: 'expanded', errLogToConsole: true}))
      .on('error', function(err) {
        console.log(err);
        this.emit('end');
      })
      .pipe(autoprefixer())
      .pipe(gulpif(!isDev, minifyCSS({noAdvanced: true}))) // minify if Prod
      .pipe(gulp.dest(build_path.css))
      .pipe(browsersync.stream());
});

gulp.task('js', function () {
  return gulp.src(dev_path.js)
      .on('error', function(err) {
        console.log(err);
        this.emit('end');
      })
      .pipe(gulp.dest(build_path.js))
      .pipe(browsersync.stream());
});

gulp.task('images', function () {
  return gulp.src(dev_path.images)
      .pipe(imagemin({optimizationLevel: 3}))
      .pipe(gulp.dest(build_path.images))
      .pipe(browsersync.stream());
});

gulp.task('favicons', function () {
  return gulp.src(dev_path.favicons)
      .pipe(imagemin({optimizationLevel: 3}))
      .pipe(gulp.dest(build_path.html))
      .pipe(browsersync.stream());
});

gulp.task('fonts', function () {
  return gulp.src(dev_path.fonts)
      .pipe(gulp.dest(build_path.fonts));
});

gulp.task('browser-sync', ['nodemon'], function () {
  return browsersync.init({
    proxy: "localhost:7069",  // local node app address
    port: dev_path.port,  // use *different* port than above
    notify: true,
    open: true,
    ui: {
      port: 7079
    }
  })
});

gulp.task('clean-build', function (cb) {
  del([output_path], cb);
});
gulp.task('clean-deployed', function (cb) {
  del([deployed_path], cb);
});

gulp.task('watch', function () {
  gulp.watch('assets/jade/**/*.jade', browsersync.reload);
  gulp.watch('assets/stylesheets/**/*.scss', ['sass']);
  gulp.watch(dev_path.images, ['images']);
  gulp.watch(dev_path.js, ['js']);
});

gulp.task('clj', function () {
  gulp.watch('assets/jade/**/*.jade', browsersync.reload);
  gulp.watch('assets/stylesheets/**/*.scss', ['sass']);
  gulp.watch(dev_path.images, ['images']);
  gulp.watch(dev_path.favicons, ['favicons']);
  gulp.watch(dev_path.js, ['js']);
});

gulp.task('server', function (callback) {
  isDev = true;
  runSequence('clean-build',
      ['sass', 'js', 'images', 'favicons', 'fonts', 'browser-sync', 'watch'],
      callback);
});

gulp.task('build', function (callback) {
  runSequence('clean-build',
      ['jade', 'sass', 'js', 'images', 'favicons', 'fonts'],
      callback);
});

gulp.task('ghpages', function() {
  return gulp.src('./resources/public/**/*')
      .pipe(ghPages({cacheDir:deployed_path}));
});

gulp.task('deploy', function (callback) {
  staticMode = true;
  runSequence(['build'],
      ['ghpages'],
      ['clean-deployed'], callback);
});

gulp.task('nodemon', function (cb) {
  var called = false;
  return nodemon({
    script: 'static-server.js',
    ignore: [
      'gulpfile.js',
      'node_modules/'
    ]
  })
  .on('start', function () {
    if (!called) {
      called = true;
      cb();
    }
  })
  .on('restart', function () {
    setTimeout(function () {
      browsersync.stream();
    }, 1000);
  });
});

gulp.task('default', function () {
  gulp.start('server');
});<commit_msg>Change gulpfile dev dependencies to only be required in server mode<commit_after>// inspired by https://gist.github.com/dmitruksergey/8441752

var gulp = require('gulp'),
    jade = require('gulp-jade'),
    sass = require('gulp-sass'),
    gulpif = require('gulp-if'),
    autoprefixer = require('gulp-autoprefixer'),
    minifyCSS = require('gulp-minify-css'),
    imagemin = require('gulp-imagemin'),
    del = require('del'),
    replace = require('gulp-replace'),
    runSequence = require('run-sequence'),
    browsersync = '',
    nodemon = '',
    ghPages = '';

var isDev = false;
var staticMode = false;
var output_path = 'resources/public';
var deployed_path = 'deployed';
var dev_path = {
  sass: ['assets/stylesheets/*.scss', '!assets/stylesheets/_*.scss'],
  jadedev: ['assets/jade/**/*.jade', '!assets/jade/_*.jade'],
  jade: ['assets/jade/**/*.jade', '!assets/jade/_*.jade', '!assets/jade/layout/*', '!assets/jade/mixins/*'],
  js: ['assets/javascripts/**/*.js'],
  images: ['assets/images/**/*', '!assets/images/dev-*'],
  favicons: ['assets/icons/favicon.*'],
  fonts: ['assets/stylesheets/fonts/*','node_modules/font-awesome/fonts/fontawesome-webfont.*'],
  port: 7777
};
var build_path = {
  css: output_path + '/stylesheets/',
  html: output_path + '/',
  js: output_path + '/javascripts/',
  images: output_path + '/images',
  fonts: output_path + '/fonts/',
  library: output_path + '/library/'
};

gulp.task('jade', function () {
  var jadeSrc = isDev ? dev_path.jadedev : dev_path.jade;
  return gulp.src(jadeSrc)
      .pipe(jade({
        pretty: true,
        locals: {
          "javascriptsBase": "javascripts",
          "stylesheetsBase": "stylesheets",
          "imagesBase": "images",
          "initData": "",
          "applicationName": "Stonecutter",
          "staticMode": staticMode
        }
      }))
      .on('error', function(err) {
        console.log(err);
        this.emit('end');
      })
      .pipe(gulpif(staticMode, replace(/>!/g, '>')))
      .pipe(gulp.dest(build_path.html))
      .pipe(browsersync.stream());
});

gulp.task('sass', function () {
  return gulp.src(dev_path.sass)
      .pipe(sass({style: 'expanded', errLogToConsole: true}))
      .on('error', function(err) {
        console.log(err);
        this.emit('end');
      })
      .pipe(autoprefixer())
      .pipe(gulpif(!isDev, minifyCSS({noAdvanced: true}))) // minify if Prod
      .pipe(gulp.dest(build_path.css))
      .pipe(browsersync.stream());
});

gulp.task('js', function () {
  return gulp.src(dev_path.js)
      .on('error', function(err) {
        console.log(err);
        this.emit('end');
      })
      .pipe(gulp.dest(build_path.js))
      .pipe(browsersync.stream());
});

gulp.task('images', function () {
  return gulp.src(dev_path.images)
      .pipe(imagemin({optimizationLevel: 3}))
      .pipe(gulp.dest(build_path.images))
      .pipe(browsersync.stream());
});

gulp.task('favicons', function () {
  return gulp.src(dev_path.favicons)
      .pipe(imagemin({optimizationLevel: 3}))
      .pipe(gulp.dest(build_path.html))
      .pipe(browsersync.stream());
});

gulp.task('fonts', function () {
  return gulp.src(dev_path.fonts)
      .pipe(gulp.dest(build_path.fonts));
});

gulp.task('browser-sync', ['nodemon'], function () {
  return browsersync.init({
    proxy: "localhost:7069",  // local node app address
    port: dev_path.port,  // use *different* port than above
    notify: true,
    open: true,
    files: [build_path.images,
      dev_path.jade,
      dev_path.favicons,
      dev_path.js,
      build_path.css],
    ui: {
      port: 7079
    }
  })
});

gulp.task('clean-build', function (cb) {
  del([output_path], cb);
});
gulp.task('clean-deployed', function (cb) {
  del([deployed_path], cb);
});

gulp.task('watch', function () {
  gulp.watch('assets/jade/**/*.jade', browsersync.reload);
  gulp.watch('assets/stylesheets/**/*.scss', ['sass']);
  gulp.watch(dev_path.images, ['images']);
  gulp.watch(dev_path.js, ['js']);
});

gulp.task('clj', function () {
  gulp.watch('assets/jade/**/*.jade', browsersync.reload);
  gulp.watch('assets/stylesheets/**/*.scss', ['sass']);
  gulp.watch(dev_path.images, ['images']);
  gulp.watch(dev_path.favicons, ['favicons']);
  gulp.watch(dev_path.js, ['js']);
});

gulp.task('server', function (callback) {
  isDev = true;
  browsersync = require('browser-sync').create();
  nodemon = require('gulp-nodemon');
  ghPages = require('gulp-gh-pages');

  runSequence('clean-build',
      ['sass', 'js', 'images', 'favicons', 'fonts', 'browser-sync', 'watch'],
      callback);
});

gulp.task('build', function (callback) {
  runSequence('clean-build',
      ['jade', 'sass', 'js', 'images', 'favicons', 'fonts'],
      callback);
});

gulp.task('ghpages', function() {
  return gulp.src('./resources/public/**/*')
      .pipe(ghPages({cacheDir:deployed_path}));
});

gulp.task('deploy', function (callback) {
  staticMode = true;
  runSequence(['build'],
      ['ghpages'],
      ['clean-deployed'], callback);
});

gulp.task('nodemon', function (cb) {
  var called = false;
  return nodemon({
    script: 'static-server.js',
    ignore: [
      'gulpfile.js',
      'node_modules/'
    ]
  })
  .on('start', function () {
    if (!called) {
      called = true;
      cb();
    }
  })
  .on('restart', function () {
    setTimeout(function () {
      browsersync.stream();
    }, 1000);
  });
});

gulp.task('default', function () {
  gulp.start('server');
});<|endoftext|>


<commit_before>var Promise = (global || window).Promise = require('bluebird'); //Bluebird promise are way better than native
var fs = Promise.promisifyAll(require('fs')); //We just want promise seriously
var path = require('path');

var gulp = require('gulp');
// CSS Dep
var sass = require('gulp-sass');

// BROWSERIFY Dep
var browserify = require('browserify');
var shim = require('browserify-shim');
var babelify = require('babelify');
var watchify = require('watchify');
var envify = require('envify/custom');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');

//CSS Dep
var minifyCss = require('gulp-minify-css');

//Utils
var del = require('del');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync').create();
var assign = require('lodash.assign');
var filter = require('gulp-filter');
var autoprefixer = require('gulp-autoprefixer');
var through = require('through');

// Browserify setup
/* What we want right now :
 * - babelify experimental
 * - watchified bundle generation
 */

 customBrowserifyOpts = {
	entries: ['./app/scripts/main.js'],
	debug: gutil.env.type == 'prod' ? false : true,
	noParse: [
		path.resolve('node_modules/prototypo.js/dist/prototypo.js'),
		path.resolve('node_modules/prototypo-canvas/dist/prototypo-canvas.js')
	]
}

var opts = assign({}, watchify.args, customBrowserifyOpts);

gulp.task('images', function() {
	gulp.src('./app/images/*.*')
		.pipe(gulp.dest('./dist/assets/images/'));
});

gulp.task('cp-prototypo.js', function() {
	gulp.src('./node_modules/prototypo.js/dist/prototypo.js')
		.pipe(gulp.dest('./dist/prototypo.js/dist/'));
});

gulp.task('cp-genese', function() {
	gulp.src('./node_modules/genese.ptf/dist/font.json')
		.pipe(gulp.dest('./dist/genese.ptf/dist/'));
});

gulp.task('css-vendor', function() {
	//This is a bit hackish but right now i don't care
	gulp.src(['./node_modules/normalize.css/normalize.css','./node_modules/please-wait/build/please-wait.css'])
		.pipe(concat('vendor.css'))
		.pipe(gulp.dest('./dist/assets/'));
})

gulp.task('css-app', function() {
	gulp.src('./app/styles/**/*.scss')
		.pipe(sourcemaps.init())
		.pipe(sass())
		.pipe(concat('app.css'))
		.pipe(autoprefixer())
		.pipe(sourcemaps.write())
		//.pipe(gutil.env.type == 'prod' ? minifyCss() : gutil.noop())
		.pipe(gulp.dest('./dist/assets/'))
		.pipe(filter('**/*.css'))
		.pipe(browserSync.reload({stream:true}));
});

function bundle() {
	return b.then(function(b) {

		return b.bundle()
			.on('error', gutil.log.bind(gutil, 'Browserify Error'))
			.pipe(source('bundle.js'))
			.pipe(buffer())
			.pipe(sourcemaps.init({loadMaps:true}))
			.pipe(sourcemaps.write('./'))
//			.pipe(gutil.env.type == 'prod' ? uglify() :gutil.noop())
			.pipe(gulp.dest('./dist'))
	})
}

var readPrelude = fs.readFileAsync('./__prelude.js');

var bBase = readPrelude.then(function(prelude) {
	return browserify(opts)
		// adds __prelude.js to all files in app/scripts
		.transform(function(file) {
			if (file.indexOf('prototypo/app/scripts') != -1) {
				var data = prelude;
				return through(write, end);

				function write(buf) { data += buf }

				function end() {
					this.queue(data);
					this.queue(null);
				}
			} else {
				return through(function write(data) {
					this.queue(data);
				}, function end() {
					this.queue(null);
				});
			}
		})
		.transform(babelify.configure({
			stage: 0, //enabling that es7 goodness
			only: './app/scripts'
		}))
		.transform(envify({
			NODE_ENV: gutil.env.type === 'prod' ? 'production' : 'development'
		}));
});

var b = bBase.then(function(browserify) {
	var b = gutil.env.type == 'prod' ? browserify : watchify(browserify);
	b.on('update',bundle);
	b.on('log',gutil.log);
	return b;
});

gulp.task('clean',function() {
	del.sync(['dist']);
})

gulp.task('browserify', bundle);

gulp.task('build', ['images','css-vendor','css-app','browserify','cp-prototypo.js']);

gulp.task('serve', ['images','css-vendor','css-app', 'browserify'], function() {
	browserSync.init({
		server:['./dist','./node_modules'],
		port:9000,
		ghostMode:false
	});

	gulp.watch('./app/styles/**/*.scss',['css-app']);
	gulp.watch('./dist/bundle.js',browserSync.reload);
});

gulp.task('test-serve', function() {
	browserSync.init({
		server:['./dist','./node_modules'],
		port:9000,
		ghostMode:false
	});

	gulp.watch('./app/styles/**/*.scss',['css-app']);
	gulp.watch('./dist/bundle.js',browserSync.reload);

})

gulp.task('default',['serve']);
<commit_msg>added cp-genese to gulp build<commit_after>var Promise = (global || window).Promise = require('bluebird'); //Bluebird promise are way better than native
var fs = Promise.promisifyAll(require('fs')); //We just want promise seriously
var path = require('path');

var gulp = require('gulp');
// CSS Dep
var sass = require('gulp-sass');

// BROWSERIFY Dep
var browserify = require('browserify');
var shim = require('browserify-shim');
var babelify = require('babelify');
var watchify = require('watchify');
var envify = require('envify/custom');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');

//CSS Dep
var minifyCss = require('gulp-minify-css');

//Utils
var del = require('del');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync').create();
var assign = require('lodash.assign');
var filter = require('gulp-filter');
var autoprefixer = require('gulp-autoprefixer');
var through = require('through');

// Browserify setup
/* What we want right now :
 * - babelify experimental
 * - watchified bundle generation
 */

 customBrowserifyOpts = {
	entries: ['./app/scripts/main.js'],
	debug: gutil.env.type == 'prod' ? false : true,
	noParse: [
		path.resolve('node_modules/prototypo.js/dist/prototypo.js'),
		path.resolve('node_modules/prototypo-canvas/dist/prototypo-canvas.js')
	]
}

var opts = assign({}, watchify.args, customBrowserifyOpts);

gulp.task('images', function() {
	gulp.src('./app/images/*.*')
		.pipe(gulp.dest('./dist/assets/images/'));
});

gulp.task('cp-prototypo.js', function() {
	gulp.src('./node_modules/prototypo.js/dist/prototypo.js')
		.pipe(gulp.dest('./dist/prototypo.js/dist/'));
});

gulp.task('cp-genese', function() {
	gulp.src('./node_modules/genese.ptf/dist/font.json')
		.pipe(gulp.dest('./dist/genese.ptf/dist/'));
});

gulp.task('css-vendor', function() {
	//This is a bit hackish but right now i don't care
	gulp.src(['./node_modules/normalize.css/normalize.css','./node_modules/please-wait/build/please-wait.css'])
		.pipe(concat('vendor.css'))
		.pipe(gulp.dest('./dist/assets/'));
})

gulp.task('css-app', function() {
	gulp.src('./app/styles/**/*.scss')
		.pipe(sourcemaps.init())
		.pipe(sass())
		.pipe(concat('app.css'))
		.pipe(autoprefixer())
		.pipe(sourcemaps.write())
		//.pipe(gutil.env.type == 'prod' ? minifyCss() : gutil.noop())
		.pipe(gulp.dest('./dist/assets/'))
		.pipe(filter('**/*.css'))
		.pipe(browserSync.reload({stream:true}));
});

function bundle() {
	return b.then(function(b) {

		return b.bundle()
			.on('error', gutil.log.bind(gutil, 'Browserify Error'))
			.pipe(source('bundle.js'))
			.pipe(buffer())
			.pipe(sourcemaps.init({loadMaps:true}))
			.pipe(sourcemaps.write('./'))
//			.pipe(gutil.env.type == 'prod' ? uglify() :gutil.noop())
			.pipe(gulp.dest('./dist'))
	})
}

var readPrelude = fs.readFileAsync('./__prelude.js');

var bBase = readPrelude.then(function(prelude) {
	return browserify(opts)
		// adds __prelude.js to all files in app/scripts
		.transform(function(file) {
			if (file.indexOf('prototypo/app/scripts') != -1) {
				var data = prelude;
				return through(write, end);

				function write(buf) { data += buf }

				function end() {
					this.queue(data);
					this.queue(null);
				}
			} else {
				return through(function write(data) {
					this.queue(data);
				}, function end() {
					this.queue(null);
				});
			}
		})
		.transform(babelify.configure({
			stage: 0, //enabling that es7 goodness
			only: './app/scripts'
		}))
		.transform(envify({
			NODE_ENV: gutil.env.type === 'prod' ? 'production' : 'development'
		}));
});

var b = bBase.then(function(browserify) {
	var b = gutil.env.type == 'prod' ? browserify : watchify(browserify);
	b.on('update',bundle);
	b.on('log',gutil.log);
	return b;
});

gulp.task('clean',function() {
	del.sync(['dist']);
})

gulp.task('browserify', bundle);

gulp.task('build', ['images','css-vendor','css-app','browserify','cp-prototypo.js','cp-genese']);

gulp.task('serve', ['images','css-vendor','css-app', 'browserify'], function() {
	browserSync.init({
		server:['./dist','./node_modules'],
		port:9000,
		ghostMode:false
	});

	gulp.watch('./app/styles/**/*.scss',['css-app']);
	gulp.watch('./dist/bundle.js',browserSync.reload);
});

gulp.task('test-serve', function() {
	browserSync.init({
		server:['./dist','./node_modules'],
		port:9000,
		ghostMode:false
	});

	gulp.watch('./app/styles/**/*.scss',['css-app']);
	gulp.watch('./dist/bundle.js',browserSync.reload);

})

gulp.task('default',['serve']);
<|endoftext|>


<commit_before>/*!
 * gulp
 * $ npm install gulp-ruby-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-livereload gulp-cache del --save-dev
 */

// Load plugins
var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del');
    xml2json = require('gulp-xml2json');
    streamqueue = require('streamqueue');
    cssnano = require('gulp-cssnano');
    sourcemaps = require('gulp-sourcemaps');

// Copy
gulp.task('copyjson', function() {
  return gulp.src('themes/barricade/static/src/particlesjs-config.json')
    .pipe(gulp.dest('static/src/'))
    .pipe(notify({ message: 'Copy json task complete' }));
});
gulp.task('copyfonts', function() {
  return gulp.src('bower_components/font-awesome/fonts/*')
    .pipe(gulp.dest('static/src/fonts'))
    .pipe(notify({ message: 'Copy fonts task complete' }));
});
gulp.task('copy', function() {
    gulp.start('copyjson', 'copyfonts');
});

// Styles
gulp.task('styles', function() {
  return sass('themes/barricade/static/src/sass/styles.scss', { style: 'expanded' })
    .pipe(autoprefixer('last 2 version'))
    .pipe(gulp.dest('themes/barricade/static/src/css'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(sourcemaps.init())
    .pipe(cssnano())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('static/src/css'))
    .pipe(notify({ message: 'Styles task complete' }));
});

// Scripts
gulp.task('scriptconcat', function() {
  return gulp.src([
      'themes/barricade/static/src/js/custom/jquery.js',
      'themes/barricade/static/src/js/custom/foundation.js',
      'themes/barricade/static/src/js/custom/foundation.topbar.js',
      'themes/barricade/static/src/js/custom/foundation.offcanvas.js',
      'themes/barricade/static/src/js/custom/foundation.accordion.js',
      'themes/barricade/static/src/js/custom/foundation.dropdown.js',
      'themes/barricade/static/src/js/custom/foundation.slider.js',
      'themes/barricade/static/src/js/custom/foundation.tooltip.js',
      'themes/barricade/static/src/js/custom/particles.min.js',
      'themes/barricade/static/src/js/custom/headroom.min.js',
      'themes/barricade/static/src/js/custom/init.js'
    ])
    .pipe(concat('main.js'))
    .pipe(gulp.dest('themes/barricade/static/src/js'))
    .pipe(notify({ message: 'Script concat task complete' }));
});
gulp.task('scriptminify', function() {
  return gulp.src([
      'themes/barricade/static/src/js/main.js',
      'themes/barricade/static/src/js/analytics.js'
    ])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    // .pipe(concat())
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest('static/src/js'))
    .pipe(notify({ message: 'Script minify task complete' }));
});
gulp.task('scripts', function() {
    gulp.start('scriptconcat', 'scriptminify');
});

// Images
gulp.task('images', function() {
  return streamqueue({ objectMode: true },
    gulp.src('themes/barricade/static/src/img/**/*{.jpg,.png,.gif}')
    .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
    .pipe(notify({ message: 'Images minifed' })),
    gulp.src('themes/barricade/static/src/img/**/*')
    .pipe(notify({ message: 'Images task complete' }))
    .pipe(gulp.dest('static/src/img'))
  )
});

// JSON
gulp.task('json', function () {
  return gulp.src('static/index.xml')
    .pipe(xml2json())
    .pipe(rename({extname: '.json'}))
    .pipe(gulp.dest('static/'))
    .pipe(notify({ message: 'JSON updated' }));
});

// Clean
gulp.task('clean', function() {
  return del('static/src/**/*');
});

// Default task
gulp.task('default', ['clean'],  function() {
  gulp.start('styles', 'scripts', 'images', 'json', 'copy');
});

// Watch
gulp.task('watch', function() {

  // Watch .scss files
  gulp.watch('themes/barricade/static/src/sass/**/*.scss', ['styles']);

  // Watch .js files
  gulp.watch('themes/barricade/static/src/js/custom/init.js', ['scripts']);

  // Watch image files
  gulp.watch('themes/barricade/static/img/src/**/*.{png,gif,jpg}', ['images']);

  // Create LiveReload server
  livereload.listen();

  // Watch any files in static/, reload on change
  gulp.watch(['static/**', 'static/src/**']).on('change', livereload.changed);

});
<commit_msg>Fix font path issue in gulpfile<commit_after>/*!
 * gulp
 * $ npm install gulp-ruby-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-livereload gulp-cache del --save-dev
 */

// Load plugins
var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del');
    xml2json = require('gulp-xml2json');
    streamqueue = require('streamqueue');
    cssnano = require('gulp-cssnano');
    sourcemaps = require('gulp-sourcemaps');

// Copy
gulp.task('copyjson', function() {
  return gulp.src('themes/barricade/static/src/particlesjs-config.json')
    .pipe(gulp.dest('static/src/'))
    .pipe(notify({ message: 'Copy json task complete' }));
});
gulp.task('copyfonts', function() {
  return gulp.src('themes/barricade/static/src/fonts/*')
    .pipe(gulp.dest('static/src/fonts'))
    .pipe(notify({ message: 'Copy fonts task complete' }));
});
gulp.task('copy', function() {
    gulp.start('copyjson', 'copyfonts');
});

// Styles
gulp.task('styles', function() {
  return sass('themes/barricade/static/src/sass/styles.scss', { style: 'expanded' })
    .pipe(autoprefixer('last 2 version'))
    .pipe(gulp.dest('themes/barricade/static/src/css'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(sourcemaps.init())
    .pipe(cssnano())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('static/src/css'))
    .pipe(notify({ message: 'Styles task complete' }));
});

// Scripts
gulp.task('scriptconcat', function() {
  return gulp.src([
      'themes/barricade/static/src/js/custom/jquery.js',
      'themes/barricade/static/src/js/custom/foundation.js',
      'themes/barricade/static/src/js/custom/foundation.topbar.js',
      'themes/barricade/static/src/js/custom/foundation.offcanvas.js',
      'themes/barricade/static/src/js/custom/foundation.accordion.js',
      'themes/barricade/static/src/js/custom/foundation.dropdown.js',
      'themes/barricade/static/src/js/custom/foundation.slider.js',
      'themes/barricade/static/src/js/custom/foundation.tooltip.js',
      'themes/barricade/static/src/js/custom/particles.min.js',
      'themes/barricade/static/src/js/custom/headroom.min.js',
      'themes/barricade/static/src/js/custom/init.js'
    ])
    .pipe(concat('main.js'))
    .pipe(gulp.dest('themes/barricade/static/src/js'))
    .pipe(notify({ message: 'Script concat task complete' }));
});
gulp.task('scriptminify', function() {
  return gulp.src([
      'themes/barricade/static/src/js/main.js',
      'themes/barricade/static/src/js/analytics.js'
    ])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    // .pipe(concat())
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest('static/src/js'))
    .pipe(notify({ message: 'Script minify task complete' }));
});
gulp.task('scripts', function() {
    gulp.start('scriptconcat', 'scriptminify');
});

// Images
gulp.task('images', function() {
  return streamqueue({ objectMode: true },
    gulp.src('themes/barricade/static/src/img/**/*{.jpg,.png,.gif}')
    .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
    .pipe(notify({ message: 'Images minifed' })),
    gulp.src('themes/barricade/static/src/img/**/*')
    .pipe(notify({ message: 'Images task complete' }))
    .pipe(gulp.dest('static/src/img'))
  )
});

// JSON
gulp.task('json', function () {
  return gulp.src('static/index.xml')
    .pipe(xml2json())
    .pipe(rename({extname: '.json'}))
    .pipe(gulp.dest('static/'))
    .pipe(notify({ message: 'JSON updated' }));
});

// Clean
gulp.task('clean', function() {
  return del('static/src/**/*');
});

// Default task
gulp.task('default', ['clean'],  function() {
  gulp.start('styles', 'scripts', 'images', 'json', 'copy');
});

// Watch
gulp.task('watch', function() {

  // Watch .scss files
  gulp.watch('themes/barricade/static/src/sass/**/*.scss', ['styles']);

  // Watch .js files
  gulp.watch('themes/barricade/static/src/js/custom/init.js', ['scripts']);

  // Watch image files
  gulp.watch('themes/barricade/static/img/src/**/*.{png,gif,jpg}', ['images']);

  // Create LiveReload server
  livereload.listen();

  // Watch any files in static/, reload on change
  gulp.watch(['static/**', 'static/src/**']).on('change', livereload.changed);

});
<|endoftext|>


<commit_before>'use strict';

/**
 * Convert HTML in even better HTML.
 * @param {String} string
 * @return {String}
 * @constructor
 */
var markyMark = function markyMark (string) {
  var internal = {};
  var external = {};

  external.chunks = [];
  internal.mode   = '';

  /**
   * Do actual conversion
   * @param {String} string
   * @return {String}
   */
  external.convert = function convert (string) {
    external.chunks = [];
    internal.mode   = '';
    var currentChunk = '';
    for (var i = 0, len = string.length; i < len; i++) {
      var c = string[i];

      if (internal.mode === '<>' || internal.mode === '</>') {
        internal.pushChunk(currentChunk, '');
        currentChunk = '';
      }
      if (c === '<') {
        internal.pushChunk(currentChunk, c);
        currentChunk = '';
      }
      else if (internal.mode === '<' && c === '/') {
        internal.mode += c;
      }
      else if (c === '>') {
        internal.mode += c;
      }
      currentChunk += c;
    }
    internal.pushChunk(currentChunk);
    return external.chunks.join('');
  };

  /**
   * Push a single chunk to the chunk array, but convert chunks by looking at the current mode
   * @param {String} chunk
   * @param {String} mode
   * @return {Boolean}
   */
  internal.pushChunk = function pushChunk (chunk, newMode) {
    newMode = newMode || '';
    if (chunk) {
      switch (internal.mode) {
        case '':
          // Text node
          chunk = internal.convertText(chunk);
          break;
        case '':
          chunk = internal.convertCode(chunk);
          break;
        case '<css>':
          chunk = internal.convertCss(chunk);
          break;
        case '':
          chunk = internal.convertHtml(chunk);
          break;
        case '<>':
          if (chunk.match(/<code class/)) {
            var lang = chunk.match(/(css|html)/);
            if (lang && lang[1]) {
              newMode = '<'+lang[1]+'>';
            }
            else {
              newMode = '';
            }
          }
          break;
      }
      external.chunks.push(chunk);
    }
    internal.mode = newMode;
    return newMode;
  };

  /**
   * Convert text node
   * @param {String} string
   * @return {String}
   */
  internal.convertText = function convertText(string) {
    var entityMap = {
      '...': '…',
      '… …': '…',
      '(C)': '©',
      '(R)': '®',
      '(TM)': '™',
      '(+-)': '±',
      '(1/4)': '¼',
      '(1/2)': '½',
      '(3/4)': '¾',
      '->': '→',
      '=>': '⇒',
      '<-': '←',
      '<=': '⇐'
    };
    string = string.replace(/(\.\.\.|… …|\(C\)|\(R\)|\(TM\)|\(+-\)|\(1\/4\)|\(1\/2\)|\(3\/4\)|->|=>|<-|<=)/g, function(s) {
      return entityMap[s];
    });
    return string
      .replace(/\s--\s/g, ' — ')
      .replace(/(\d)\s*-\s*(\d)/g,'$1–$2')
      .replace(/(\s)-(\s)/g,'$1–$2')
      .replace(/(\d\s*)(x|\*)(\s*\d)/g,'$1×$3')
      .replace(/(^|[^\S])"(\S.*?\S)"([^\S]|$)/g,'$1„$2“$3')
      .replace(/^"/, '„')
      .replace(/"$/, '“')
      .replace(/(^|[^\S])(?:'|')(\S.*?\S)(?:'|')([^\S]|$)/g,'$1‚$2‘$3')
    ;
  };

  /**
   * Convert code text node
   * @param {String} string
   * @return {String}
   */
  internal.convertCode = function convertCode(string) {
    return string
      .replace(/(\b)(var|function|method|class|const|external|internal|protected|use)(\b)/gi, '$1$2$3')
      .replace(/(\b)(and|array|break|case|die|do|echo|else(if)?|elsif|final|for(each)?|global|if|include(_once)?|length|list|map|new|or|require(_once)?|return|self|switch|this|throw|while)(\b)/gi, '$1$2$3')
      .replace(/([^\\])("|'|')(.*?)("|'|')/g,'$1$2$3$4')
      .replace(/([\s|=|;])([\d\.]+)([\s|=|;])/g, '$1$2$3')
      .replace(/((?:\/\/|#).+?(?:\n|$))/g, '$1')
      .replace(/(\/\*[\s\S]+\*\/)/g, '$1')
    ;
  };

  /**
   * Convert code text node
   * @param {String} string
   * @return {String}
   */
  internal.convertCss = function convertCss(string) {
    return string
      .replace(/(\b)(color|background-color|float|text-align|position|display)(\b)/gi, '$1$2$3')
      .replace(/(\b)(inherit|top|bottom|left|right|auto|center|middle|block|inline|inline-block|none)(\b)/gi, '$1$2$3')
      .replace(/(\b)((?:\.|#)[a-z0-9_\-]+)(\b)/gi, '$1$2$3')
      .replace(/(\b)((?:$)[a-z0-9_\-]+)(\b)/gi, '$1$2$3')
      .replace(/(\b)(@(?:include|if|extend|mixin|function|else|elseif))(\b)/gi, '$1$2$3')
      .replace(/([^\\])("|'|')(.*?)("|'|')/g,'$1$2$3$4')
      .replace(/([\d\.]+[a-z]+)/g, '$1$2$3')
      .replace(/(\/\/.+?(?:\n|$))/g, '$1')
      .replace(/(\/\*[\s\S]+\*\/)/g, '$1')
      ;
  };

  /**
   * Convert code text node
   * @param {String} string
   * @return {String}
   */
  internal.convertHtml = function convertHtml(string) {
    return string
      .replace(/(<\/?)([a-zA-Z0-9]+)/g, '$1$2')
      .replace(/(&[a-z0-9]+?;)/g, '$1')
      .replace(/(\s)([a-z0-9_\-]+?)(=")(.+?)(")/gi, '$1$2$3$4$5')
      .replace(/(<--.+?-->)/g, '$1')
    ;
  };

  return external.convert(string);
};

module.exports = markyMark;
<commit_msg>Improved code parser<commit_after>'use strict';

/**
 * Convert HTML in even better HTML.
 * @param {String} string
 * @return {String}
 * @constructor
 */
var markyMark = function markyMark (string) {
  var internal = {};
  var external = {};

  external.chunks = [];
  internal.mode   = '';

  /**
   * Do actual conversion
   * @param {String} string
   * @return {String}
   */
  external.convert = function convert (string) {
    external.chunks = [];
    internal.mode   = '';
    var currentChunk = '';
    for (var i = 0, len = string.length; i < len; i++) {
      var c = string[i];

      if (internal.mode === '<>' || internal.mode === '</>') {
        internal.pushChunk(currentChunk, '');
        currentChunk = '';
      }
      if (c === '<') {
        internal.pushChunk(currentChunk, c);
        currentChunk = '';
      }
      else if (internal.mode === '<' && c === '/') {
        internal.mode += c;
      }
      else if (c === '>') {
        internal.mode += c;
      }
      currentChunk += c;
    }
    internal.pushChunk(currentChunk);
    return external.chunks.join('');
  };

  /**
   * Push a single chunk to the chunk array, but convert chunks by looking at the current mode
   * @param {String} chunk
   * @param {String} mode
   * @return {Boolean}
   */
  internal.pushChunk = function pushChunk (chunk, newMode) {
    newMode = newMode || '';
    if (chunk) {
      switch (internal.mode) {
        case '':
          // Text node
          chunk = internal.convertText(chunk);
          break;
        case '':
          chunk = internal.convertCode(chunk);
          break;
        case '<css>':
          chunk = internal.convertCss(chunk);
          break;
        case '':
          chunk = internal.convertHtml(chunk);
          break;
        case '<>':
          if (chunk.match(/<code class/)) {
            var lang = chunk.match(/(css|html)/);
            if (lang && lang[1]) {
              newMode = '<'+lang[1]+'>';
            }
            else {
              newMode = '';
            }
          }
          break;
      }
      external.chunks.push(chunk);
    }
    internal.mode = newMode;
    return newMode;
  };

  /**
   * Convert text node
   * @param {String} string
   * @return {String}
   */
  internal.convertText = function convertText(string) {
    var entityMap = {
      '...': '…',
      '… …': '…',
      '(C)': '©',
      '(R)': '®',
      '(TM)': '™',
      '(+-)': '±',
      '(1/4)': '¼',
      '(1/2)': '½',
      '(3/4)': '¾',
      '->': '→',
      '=>': '⇒',
      '<-': '←',
      '<=': '⇐'
    };
    string = string.replace(/(\.\.\.|… …|\(C\)|\(R\)|\(TM\)|\(+-\)|\(1\/4\)|\(1\/2\)|\(3\/4\)|->|=>|<-|<=)/g, function(s) {
      return entityMap[s];
    });
    return string
      .replace(/\s--\s/g, ' — ')
      .replace(/(\d)\s*-\s*(\d)/g,'$1–$2')
      .replace(/(\s)-(\s)/g,'$1–$2')
      .replace(/(\d\s*)(x|\*)(\s*\d)/g,'$1×$3')
      .replace(/(^|[^\S])"(\S.*?\S)"([^\S]|$)/g,'$1„$2“$3')
      .replace(/^"/, '„')
      .replace(/"$/, '“')
      .replace(/(^|[^\S])(?:'|')(\S.*?\S)(?:'|')([^\S]|$)/g,'$1‚$2‘$3')
    ;
  };

  /**
   * Convert code text node
   * @param {String} string
   * @return {String}
   */
  internal.convertCode = function convertCode(string) {
    return string
      .replace(/(\b)(var|function|method|class|const|external|internal|protected|use)(\b)/gi, '$1$2$3')
      .replace(/(\b)(and|array|break|case|die|do|echo|else(if)?|elsif|final|for(each)?|global|if|include(_once)?|length|list|map|new|or|require(_once)?|return|self|switch|this|throw|while)(\b)/gi, '$1$2$3')
      .replace(/([^\\])("|'|')(.*?)("|'|')/g,'$1$2$3$4')
      .replace(/([\s|=|;])([\d\.]+)([\s|=|;])/g, '$1$2$3')
      .replace(/((?:\/\/|\s#).+?(?:\n|$))/g, '$1')
      .replace(/(\/\*[\s\S]+?\*\/)/g, '$1')
    ;
  };

  /**
   * Convert code text node
   * @param {String} string
   * @return {String}
   */
  internal.convertCss = function convertCss(string) {
    return string
      .replace(/(\b)(color|background-color|float|text-align|position|display)(\b)/gi, '$1$2$3')
      .replace(/(\b)(inherit|top|bottom|left|right|auto|center|middle|block|inline|inline-block|none)(\b)/gi, '$1$2$3')
      .replace(/(\b)((?:\.|#)[a-z0-9_\-]+)(\b)/gi, '$1$2$3')
      .replace(/(\b)((?:$)[a-z0-9_\-]+)(\b)/gi, '$1$2$3')
      .replace(/(\b)(@(?:include|if|extend|mixin|function|else|elseif))(\b)/gi, '$1$2$3')
      .replace(/([^\\])("|'|')(.*?)("|'|')/g,'$1$2$3$4')
      .replace(/([\d\.]+[a-z]+)/g, '$1$2$3')
      .replace(/(\/\/.+?(?:\n|$))/g, '$1')
      .replace(/(\/\*[\s\S]+?\*\/)/g, '$1')
      ;
  };

  /**
   * Convert code text node
   * @param {String} string
   * @return {String}
   */
  internal.convertHtml = function convertHtml(string) {
    return string
      .replace(/(<\/?)([a-zA-Z0-9]+)/g, '$1$2')
      .replace(/(&[a-z0-9]+?;)/g, '$1')
      .replace(/(\s)([a-z0-9_\-]+?)(=")(.+?)(")/gi, '$1$2$3$4$5')
      .replace(/(<--.+?-->)/g, '$1')
    ;
  };

  return external.convert(string);
};

module.exports = markyMark;
<|endoftext|>


<commit_before>var del = require('del');
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var Server = require('karma').Server;

/**
 * Paths
 */
var bowerFolder = 'bower_components/';
var destFolder = 'dist/';
var srcFolder = 'src/';

/**
 * Clean all destination folders
 */
gulp.task('clean', function(cb) {
  return del([
    destFolder,
  ], cb)

  return gulp.pipe(plugins.if(isMac, plugins.notify('Clean task complete')));
});

/**
 * Install Bower components
 */
gulp.task('bower', function() {
  return plugins.bower();
});

/**
 * Main site scripts
 */
gulp.task('scripts', function() {
  return gulp
    .src([
      srcFolder + '**/*.js',
      '!' + srcFolder + 'tests/**/*'
    ])
    .pipe(plugins.plumber())
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('default'))
    .pipe(plugins.jscs())
    .pipe(plugins.jscs.reporter())
    .pipe(plugins.concat('angular-rest-support.js'))
    .pipe(gulp.dest(destFolder))
    .pipe(plugins.uglify())
    .pipe(plugins.rename({suffix: '.min'}))
    .pipe(gulp.dest(destFolder));
});

/**
 * Run test once and exit
 */
gulp.task('test', function (done) {
  return new Server({
    autoWatch: false,
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

/**
 * Run scripts then test
 */
gulp.task('tested-scripts', function (done) {
  return runSequence(
    'scripts',
    'test'
  );
});

/**
 * Watch various files and run appropriate task
 */
gulp.task('watch', function() {
  // Watch this file
  gulp.watch('gulpfile.js', ['dev']);

  // Watch .js files
  gulp.watch(srcFolder + '**/*.js', ['tested-scripts']);

});

/**
 * Default task. Runs all other tasks.
 */
gulp.task('default', ['clean'], function() {
  return runSequence(
    'bower',
    'tested-scripts'
  );
});
<commit_msg>chore(gulp): autowatch property not needed. Implied by singleRun<commit_after>var del = require('del');
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var Server = require('karma').Server;

/**
 * Paths
 */
var bowerFolder = 'bower_components/';
var destFolder = 'dist/';
var srcFolder = 'src/';

/**
 * Clean all destination folders
 */
gulp.task('clean', function(cb) {
  return del([
    destFolder,
  ], cb)

  return gulp.pipe(plugins.if(isMac, plugins.notify('Clean task complete')));
});

/**
 * Install Bower components
 */
gulp.task('bower', function() {
  return plugins.bower();
});

/**
 * Main site scripts
 */
gulp.task('scripts', function() {
  return gulp
    .src([
      srcFolder + '**/*.js',
      '!' + srcFolder + 'tests/**/*'
    ])
    .pipe(plugins.plumber())
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('default'))
    .pipe(plugins.jscs())
    .pipe(plugins.jscs.reporter())
    .pipe(plugins.concat('angular-rest-support.js'))
    .pipe(gulp.dest(destFolder))
    .pipe(plugins.uglify())
    .pipe(plugins.rename({suffix: '.min'}))
    .pipe(gulp.dest(destFolder));
});

/**
 * Run test once and exit
 */
gulp.task('test', function (done) {
  return new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

/**
 * Run scripts then test
 */
gulp.task('tested-scripts', function (done) {
  return runSequence(
    'scripts',
    'test'
  );
});

/**
 * Watch various files and run appropriate task
 */
gulp.task('watch', function() {
  // Watch this file
  gulp.watch('gulpfile.js', ['dev']);

  // Watch .js files
  gulp.watch(srcFolder + '**/*.js', ['tested-scripts']);

});

/**
 * Default task. Runs all other tasks.
 */
gulp.task('default', ['clean'], function() {
  return runSequence(
    'bower',
    'tested-scripts'
  );
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "editors", "ui", "settings", "tabManager", "ace", "menus", "commands",
        "console", "ace.status"
    ];
    main.provides = ["immediate"];
    return main;

    function main(options, imports, register) {
        var editors = imports.editors;
        var tabs = imports.tabManager;
        var ui = imports.ui;
        var menus = imports.menus;
        var commands = imports.commands;
        var c9console = imports.console;
        var aceHandle = imports.ace;
        var aceStatus = imports["ace.status"];

        var Repl = require("plugins/c9.ide.ace.repl/repl").Repl;
        var markup = require("text!./immediate.xml");

        var counter = 0;

        /***** Initialization *****/

        var extensions = [];

        var handle = editors.register("immediate", "Immediate Window",
                                      Immediate, extensions);
        var emit = handle.getEmitter();

        var replTypes = {}; //Shared across Immediate windows
        var theme, defaultEvaluator;

        handle.on("load", function(){
            handle.addElement(
                tabs.getElement("mnuEditors").appendChild(
                    new ui.item({
                        caption: "New Immediate Window",
                        onclick: function(e) {
                            tabs.open({
                                active: true,
                                pane: this.parentNode.pane,
                                editorType: "immediate"
                            }, function(){});
                        }
                    })
                )
            );

            menus.addItemByPath("Window/New Immediate Window", new ui.item({
                onclick: function(){
                    tabs.open({
                        active: true,
                        pane: this.parentNode.pane,
                        editorType: "immediate"
                    }, function(){});
                }
            }), 31, handle);

            commands.addCommand({
                name: "showimmediate",
                group: "Panels",
                exec: function (editor, args) {
                    // Search for the output pane
                    if (search(done)) return;

                    // If not found show the console
                    c9console.show();

                    // Search again
                    if (search(done)) return;

                    // Else open the output panel in the console
                    tabs.open({
                        editorType: "immediate",
                        active: true,
                        pane: c9console.getPanes()[0],
                    }, done);

                    function done(err, tab) {
                        if (args && args.evaluator)
                            tab.editor.setActiveEvaluator(args.evaluator);
                    }
                }
            }, handle);

            // Insert some CSS
            ui.insertCss(require("text!./style.css"), options.staticPrefix, handle);
        });

        //Search through pages
        function search(cb) {
            return !tabs.getTabs().every(function(tab) {
                if (tab.editorType == "immediate") {
                    tabs.focusTab(tab);
                    if (cb) cb(null, tab);
                    return false;
                }
                return true;
            });
        }

        function Immediate(){
            var Baseclass = editors.findEditor("ace");

            var deps = main.consumes.splice(0, main.consumes.length - 1);
            var plugin = new Baseclass(true, [], deps);
            // var emit = plugin.getEmitter();

            var ddType, btnClear, ace, menu;

            plugin.on("draw", function(e) {
                aceStatus.draw();

                // Create UI elements
                ui.insertMarkup(e.tab, markup, plugin);

                ddType = plugin.getElement("ddType");
                btnClear = plugin.getElement("btnClear");
                menu = plugin.getElement("menu");

                ace = plugin.ace;

                ace.setOption("printMargin", false);
                ace.setOption("scrollPastEnd", 0);
                ace.setOption("showFoldWidgets", false);
                ace.setOption("highlightActiveLine", false);
                ace.setOption("highlightGutterLine", false);
                // ace.setOption("fontSize", 11);
                // ace.container.style.lineHeight = "17px";

                e.htmlNode.className += " immediate";

                // Allow Selection (APF)
                e.tab.textselect = true;

                ddType.on("afterchange", function(){
                    if (currentDocument)
                        currentDocument.getSession().changeType(ddType.selectedType);
                });
                btnClear.on("click", function(){
                    plugin.clear();
                    btnClear.blur();
                });

                for (var type in replTypes) {
                    var t = replTypes[type];
                    addType(t.caption, type, t.plugin);
                }

                handle.on("addEvaluator", function(e) {
                    addType(e.caption, e.id, e.plugin);
                });

                menu.on("itemclick", function(e) {
                    var value = e.relatedNode.getAttribute("value");
                    ddType.setType(value);
                });

                function update(e) {
                    if (e && !e.value)
                        return;
                    var items = menu.childNodes;
                    var value = ddType.selectedType || items[0].value;
                    var selectedItem;
                    items.forEach(function(item) {
                        var selected = item.value == value ? true :  false;
                        if (selected) selectedItem = item;
                        item.setAttribute("selected", selected);
                    });

                    ddType.setType(value);
                }

                ddType.setAttribute("submenu", menu);
                ddType.setType = function (type) {
                    if (type == ddType.selectedType || !replTypes[type])
                        return;
                    ddType.selectedType = type;
                    ddType.setAttribute("caption", replTypes[type].caption);
                    ddType.dispatchEvent("afterchange");
                };

                function setTheme(e) {
                    theme = e.theme;
                    if (!theme) return;

                    btnClear.parentNode.$ext.className = "bar-status "
                        + (theme.isDark ? "ace_dark" : "");
                }

                aceHandle.on("themeChange", setTheme, plugin);
                setTheme({theme: aceHandle.theme});

                menu.on("prop.visible", update);
                update();
            });

            /***** Method *****/

            function addType(caption, value, plugin) {
                var item = menu.appendChild(new ui.item({
                    caption: caption,
                    value: value,
                    type: "radio"
                }));

                plugin.addElement(item);
            }

            function setActiveEvaluator(value) {
                ddType.setType(value);
            }

            function getActiveEvaluator() {
                return ddType.selectedType;
            }

            // Set the tab in loading state - later this could be the output block
            // currentDocument.tab.classList.add("loading");
            // settings.save();

            /***** Lifecycle *****/

            plugin.on("load", function(){
            });

            var currentDocument;
            plugin.on("documentLoad", function(e) {
                var doc = e.doc;
                var session = doc.getSession();

                doc.undoManager.on("change", function(e) {
                    if (!doc.undoManager.isAtBookmark())
                        doc.undoManager.bookmark();
                });

                doc.tooltip =
                doc.title = "Immediate";

                if (session.repl) return;

                session.changeType = function(type, noMessage) {
                    handle.findEvaluator(type, function(type, evaluator) {
                        session.type = type;

                        if (!session.repl) {
                            session.repl = new Repl(session.session, {
                                mode: evaluator.mode,
                                evaluator: evaluator,
                                message: evaluator.message
                            });

                            if (currentDocument
                              && currentDocument.getSession() == session)
                                session.repl.attach(ace);
                        }

                        session.repl.clear();

                        if (!noMessage) {
                            var cell = session.repl.insertCell(
                                { row: 0, column: 0 }, { type: "comment" }, true);
                            cell.setValue(evaluator.message + "\n");
                        }

                        session.repl.ensureLastInputCell();
                        session.repl.setEvaluator(evaluator);
                        session.repl.session.setMode(evaluator.mode);

                        doc.tooltip =
                        doc.title = "Immediate (" + evaluator.caption + ")";
                    });
                };

                doc.value = "";

                session.changeType(session.type || defaultEvaluator || ddType.selectedType);
            });
            plugin.on("documentActivate", function(e) {
                currentDocument = e.doc;
                var session = e.doc.getSession();

                if (session.type) {
                    ddType.setType(session.type);
                }

                if (session.repl)
                    session.repl.attach(ace);
            });
            plugin.on("documentUnload", function(e) {
                var session = e.doc.getSession();
                if (session.repl)
                    session.repl.detach();
                // TODO: this breaks moving repl between splits
                // delete session.repl;
            });
            plugin.on("getState", function(e) {
                // @todo at one for each value container
                var session = e.doc.getSession();
                if (!session.repl) return;

                e.state.type = session.type;
                var data = session.repl.history._data;
                var pos = session.repl.history.position;
                if (data.length > 1000)
                    data = data.slice(-500);
                e.state.history = data;
                e.state.pos = pos;
            });
            plugin.on("setState", function(e) {
                if (e.state.type) {
                    var session = e.doc.getSession();
                    session.type = e.state.type;
                    session.repl.history._data = e.state.history || [];
                    if (typeof e.state.pos === "number")
                        session.repl.history.position = e.state.pos;
                    if (e.doc == currentDocument)
                        ddType.setType(e.state.type);
                }
            });
            plugin.on("clear", function(){
                if (currentDocument) {
                    var session = currentDocument.getSession();
                    session.changeType(session.type, true);
                    plugin.focus();
                }
            });
            plugin.on("focus", function(){
            });
            plugin.on("enable", function(){
            });
            plugin.on("disable", function(){
            });
            plugin.on("unload", function(){
            });

            /***** Register and define API *****/

            /**
             * Immediate Pane for Cloud9
             * @class immediate.Immediate
             * @extends Editor
             */
            /**
             * The type of editor. Use this to create an immediate pane using
             * {@link tabManager#openEditor} or {@link editors#createEditor}.
             * @property {"immediate"} type
             * @readonly
             */
            plugin.freezePublicAPI({
                /**
                 *
                 */
                setActiveEvaluator: setActiveEvaluator,

                /**
                 *
                 */
                getActiveEvaluator: getActiveEvaluator
            });

            plugin.load("immediate" + counter++);

            return plugin;
        }

        /**
         * The immediate handle, provides an API for adding
         * {@link Evaluator evaluators} to the immediate panes.
         * An evaluator is a plugin that can take the expressions from the
         * multi-line REPL and return resuls. The results can be
         * rendered as HTML and are fully interactive.
         *
         * This is the object you get when you request the immediate service
         * in your plugin.
         *
         * Example:
         *
         *     define(function(require, exports, module) {
         *         main.consumes = ["immediate", "Plugin"];
         *         main.provides = ["myplugin"];
         *         return main;
         *
         *         function main(options, imports, register) {
         *             var immediate = imports.immediate;
         *             var plugin = new imports.Plugin("Your Name", main.consumes);
         *
         *             plugin.on("load", function(){
         *                 var evaluator = {
         *                     mode        : "ace/mode/go",
         *                     message     : "",
         *                     canEvaluate : function(str) { return str.trim() ? true : false; },
         *                     evaluate    : function(expression, cell, done) {
         *
         *                         executeCommand(expression, function(result) {
         *                             cell.addWidget({
         *                                 html       : "
"
         *                                     + result + "
",
         *                                 coverLine  : true,
         *                                 fixedWidth : true
         *                             });
         *
         *                             done();
         *                         });
         *
         *                     }
         *                 };
         *
         *                 immediate.addEvaluator("Go Language", "go", evaluator, plugin);
         *             });
         *         });
         *     });
         *
         *
         * @class immediate
         * @extends Plugin
         * @singleton
         */
        handle.freezePublicAPI({
            get defaultEvaluator(){ return defaultEvaluator; },
            set defaultEvaluator(value){ defaultEvaluator = value; },

            _events: [
                /**
                 * Fires when an evaluator is added.
                 * @event addEvaluator
                 * @param {Object}              e
                 * @param {String}              e.caption     The caption of the evaluator.
                 * @param {String}              e.id          The unique identifier of the evaluator.
                 * @param {Evaluator} e.evaluator   The evaluator.
                 * @param {Plugin}              e.plugin      The plugin responsible for adding the evaluator.
                 */
                "addEvaluator",
                /**
                 * Fires when an evaluator is removed.
                 * @event removeEvaluator
                 * @param {Object}              e
                 * @param {String}              e.caption     The caption of the evaluator.
                 * @param {String}              e.id          The unique identifier of the evaluator.
                 * @param {Evaluator} e.evaluator   The evaluator.
                 * @param {Plugin}              e.plugin      The plugin responsible for adding the evaluator.
                 */
                "removeEvaluator"
            ],

            /**
             * Adds a new evaluator to all immediate panes. The user is able
             * to choose the evaluator from a dropdown in the UI of the
             * immediate pane.
             * @param {String}              caption     The caption in the dropdown.
             * @param {String}              id          The unique identifier of this evaluator.
             * @param {Evaluator} evaluator   The evaluator for your runtime.
             * @param {Plugin}              plugin      The plugin responsible for adding the evaluator.
             * @fires addEvaluator
             */
            addEvaluator: function(caption, id, evaluator, plugin) {
                if (replTypes[id])
                    throw new Error("An evaluator is already registered with "
                        + "the id '" + id + "'");

                replTypes[id] = {
                    caption: caption,
                    id: id,
                    evaluator: evaluator,
                    plugin: plugin
                };
                emit("addEvaluator", replTypes[id]);

                plugin.addOther(function(){
                    handle.removeEvaluator(id);
                });
            },

            /**
             * Retrieves an evaluator based on it's id. When the evaluator is
             * not yet registered, the callback will be returned when the
             * evaluator is registered.
             * @param {String}              id                  The id of the evaluator to retrieve.
             * @param {Function}            callback            Called when the evaluator is available.
             * @param {Error}               callback.id         The id of the requested evaluator.
             * @param {Evaluator} callback.evaluator  The evaluator requested.
             */
            findEvaluator: function(id, callback) {
                if (!id || !replTypes[id]) {
                    handle.on("addEvaluator", function wait(e) {
                        if (!id || e.id == id)
                            callback(e.id, replTypes[e.id].evaluator);

                        handle.off("addEvaluator", wait);
                    });
                }
                else {
                    callback(id, replTypes[id].evaluator);
                }
            },

            /**
             * Removes an evaluator from all immediate panes.
             * @param {String} id  The unique identifier of the evaluator to remove.
             */
            removeEvaluator: function(id) {
                emit("removeEvaluator", replTypes[id]);
                delete replTypes[id];
            }
        });

        register(null, {
            immediate: handle
        });
    }
});
<commit_msg>remove special handling of tabManager in plugin deps<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "editors", "ui", "settings", "tabManager", "ace", "menus", "commands",
        "console", "ace.status"
    ];
    main.provides = ["immediate"];
    return main;

    function main(options, imports, register) {
        var editors = imports.editors;
        var tabs = imports.tabManager;
        var ui = imports.ui;
        var menus = imports.menus;
        var commands = imports.commands;
        var c9console = imports.console;
        var aceHandle = imports.ace;
        var aceStatus = imports["ace.status"];

        var Repl = require("plugins/c9.ide.ace.repl/repl").Repl;
        var markup = require("text!./immediate.xml");

        var counter = 0;

        /***** Initialization *****/

        var extensions = [];

        var handle = editors.register("immediate", "Immediate Window",
                                      Immediate, extensions);
        var emit = handle.getEmitter();

        var replTypes = {}; //Shared across Immediate windows
        var theme, defaultEvaluator;

        handle.on("load", function(){
            handle.addElement(
                tabs.getElement("mnuEditors").appendChild(
                    new ui.item({
                        caption: "New Immediate Window",
                        onclick: function(e) {
                            tabs.open({
                                active: true,
                                pane: this.parentNode.pane,
                                editorType: "immediate"
                            }, function(){});
                        }
                    })
                )
            );

            menus.addItemByPath("Window/New Immediate Window", new ui.item({
                onclick: function(){
                    tabs.open({
                        active: true,
                        pane: this.parentNode.pane,
                        editorType: "immediate"
                    }, function(){});
                }
            }), 31, handle);

            commands.addCommand({
                name: "showimmediate",
                group: "Panels",
                exec: function (editor, args) {
                    // Search for the output pane
                    if (search(done)) return;

                    // If not found show the console
                    c9console.show();

                    // Search again
                    if (search(done)) return;

                    // Else open the output panel in the console
                    tabs.open({
                        editorType: "immediate",
                        active: true,
                        pane: c9console.getPanes()[0],
                    }, done);

                    function done(err, tab) {
                        if (args && args.evaluator)
                            tab.editor.setActiveEvaluator(args.evaluator);
                    }
                }
            }, handle);

            // Insert some CSS
            ui.insertCss(require("text!./style.css"), options.staticPrefix, handle);
        });

        //Search through pages
        function search(cb) {
            return !tabs.getTabs().every(function(tab) {
                if (tab.editorType == "immediate") {
                    tabs.focusTab(tab);
                    if (cb) cb(null, tab);
                    return false;
                }
                return true;
            });
        }

        function Immediate(){
            var Baseclass = editors.findEditor("ace");

            var plugin = new Baseclass(true, [], main.consumes);
            // var emit = plugin.getEmitter();

            var ddType, btnClear, ace, menu;

            plugin.on("draw", function(e) {
                aceStatus.draw();

                // Create UI elements
                ui.insertMarkup(e.tab, markup, plugin);

                ddType = plugin.getElement("ddType");
                btnClear = plugin.getElement("btnClear");
                menu = plugin.getElement("menu");

                ace = plugin.ace;

                ace.setOption("printMargin", false);
                ace.setOption("scrollPastEnd", 0);
                ace.setOption("showFoldWidgets", false);
                ace.setOption("highlightActiveLine", false);
                ace.setOption("highlightGutterLine", false);
                // ace.setOption("fontSize", 11);
                // ace.container.style.lineHeight = "17px";

                e.htmlNode.className += " immediate";

                // Allow Selection (APF)
                e.tab.textselect = true;

                ddType.on("afterchange", function(){
                    if (currentDocument)
                        currentDocument.getSession().changeType(ddType.selectedType);
                });
                btnClear.on("click", function(){
                    plugin.clear();
                    btnClear.blur();
                });

                for (var type in replTypes) {
                    var t = replTypes[type];
                    addType(t.caption, type, t.plugin);
                }

                handle.on("addEvaluator", function(e) {
                    addType(e.caption, e.id, e.plugin);
                });

                menu.on("itemclick", function(e) {
                    var value = e.relatedNode.getAttribute("value");
                    ddType.setType(value);
                });

                function update(e) {
                    if (e && !e.value)
                        return;
                    var items = menu.childNodes;
                    var value = ddType.selectedType || items[0].value;
                    var selectedItem;
                    items.forEach(function(item) {
                        var selected = item.value == value ? true :  false;
                        if (selected) selectedItem = item;
                        item.setAttribute("selected", selected);
                    });

                    ddType.setType(value);
                }

                ddType.setAttribute("submenu", menu);
                ddType.setType = function (type) {
                    if (type == ddType.selectedType || !replTypes[type])
                        return;
                    ddType.selectedType = type;
                    ddType.setAttribute("caption", replTypes[type].caption);
                    ddType.dispatchEvent("afterchange");
                };

                function setTheme(e) {
                    theme = e.theme;
                    if (!theme) return;

                    btnClear.parentNode.$ext.className = "bar-status "
                        + (theme.isDark ? "ace_dark" : "");
                }

                aceHandle.on("themeChange", setTheme, plugin);
                setTheme({theme: aceHandle.theme});

                menu.on("prop.visible", update);
                update();
            });

            /***** Method *****/

            function addType(caption, value, plugin) {
                var item = menu.appendChild(new ui.item({
                    caption: caption,
                    value: value,
                    type: "radio"
                }));

                plugin.addElement(item);
            }

            function setActiveEvaluator(value) {
                ddType.setType(value);
            }

            function getActiveEvaluator() {
                return ddType.selectedType;
            }

            // Set the tab in loading state - later this could be the output block
            // currentDocument.tab.classList.add("loading");
            // settings.save();

            /***** Lifecycle *****/

            plugin.on("load", function(){
            });

            var currentDocument;
            plugin.on("documentLoad", function(e) {
                var doc = e.doc;
                var session = doc.getSession();

                doc.undoManager.on("change", function(e) {
                    if (!doc.undoManager.isAtBookmark())
                        doc.undoManager.bookmark();
                });

                doc.tooltip =
                doc.title = "Immediate";

                if (session.repl) return;

                session.changeType = function(type, noMessage) {
                    handle.findEvaluator(type, function(type, evaluator) {
                        session.type = type;

                        if (!session.repl) {
                            session.repl = new Repl(session.session, {
                                mode: evaluator.mode,
                                evaluator: evaluator,
                                message: evaluator.message
                            });

                            if (currentDocument
                              && currentDocument.getSession() == session)
                                session.repl.attach(ace);
                        }

                        session.repl.clear();

                        if (!noMessage) {
                            var cell = session.repl.insertCell(
                                { row: 0, column: 0 }, { type: "comment" }, true);
                            cell.setValue(evaluator.message + "\n");
                        }

                        session.repl.ensureLastInputCell();
                        session.repl.setEvaluator(evaluator);
                        session.repl.session.setMode(evaluator.mode);

                        doc.tooltip =
                        doc.title = "Immediate (" + evaluator.caption + ")";
                    });
                };

                doc.value = "";

                session.changeType(session.type || defaultEvaluator || ddType.selectedType);
            });
            plugin.on("documentActivate", function(e) {
                currentDocument = e.doc;
                var session = e.doc.getSession();

                if (session.type) {
                    ddType.setType(session.type);
                }

                if (session.repl)
                    session.repl.attach(ace);
            });
            plugin.on("documentUnload", function(e) {
                var session = e.doc.getSession();
                if (session.repl)
                    session.repl.detach();
                // TODO: this breaks moving repl between splits
                // delete session.repl;
            });
            plugin.on("getState", function(e) {
                // @todo at one for each value container
                var session = e.doc.getSession();
                if (!session.repl) return;

                e.state.type = session.type;
                var data = session.repl.history._data;
                var pos = session.repl.history.position;
                if (data.length > 1000)
                    data = data.slice(-500);
                e.state.history = data;
                e.state.pos = pos;
            });
            plugin.on("setState", function(e) {
                if (e.state.type) {
                    var session = e.doc.getSession();
                    session.type = e.state.type;
                    session.repl.history._data = e.state.history || [];
                    if (typeof e.state.pos === "number")
                        session.repl.history.position = e.state.pos;
                    if (e.doc == currentDocument)
                        ddType.setType(e.state.type);
                }
            });
            plugin.on("clear", function(){
                if (currentDocument) {
                    var session = currentDocument.getSession();
                    session.changeType(session.type, true);
                    plugin.focus();
                }
            });
            plugin.on("focus", function(){
            });
            plugin.on("enable", function(){
            });
            plugin.on("disable", function(){
            });
            plugin.on("unload", function(){
            });

            /***** Register and define API *****/

            /**
             * Immediate Pane for Cloud9
             * @class immediate.Immediate
             * @extends Editor
             */
            /**
             * The type of editor. Use this to create an immediate pane using
             * {@link tabManager#openEditor} or {@link editors#createEditor}.
             * @property {"immediate"} type
             * @readonly
             */
            plugin.freezePublicAPI({
                /**
                 *
                 */
                setActiveEvaluator: setActiveEvaluator,

                /**
                 *
                 */
                getActiveEvaluator: getActiveEvaluator
            });

            plugin.load("immediate" + counter++);

            return plugin;
        }

        /**
         * The immediate handle, provides an API for adding
         * {@link Evaluator evaluators} to the immediate panes.
         * An evaluator is a plugin that can take the expressions from the
         * multi-line REPL and return resuls. The results can be
         * rendered as HTML and are fully interactive.
         *
         * This is the object you get when you request the immediate service
         * in your plugin.
         *
         * Example:
         *
         *     define(function(require, exports, module) {
         *         main.consumes = ["immediate", "Plugin"];
         *         main.provides = ["myplugin"];
         *         return main;
         *
         *         function main(options, imports, register) {
         *             var immediate = imports.immediate;
         *             var plugin = new imports.Plugin("Your Name", main.consumes);
         *
         *             plugin.on("load", function(){
         *                 var evaluator = {
         *                     mode        : "ace/mode/go",
         *                     message     : "",
         *                     canEvaluate : function(str) { return str.trim() ? true : false; },
         *                     evaluate    : function(expression, cell, done) {
         *
         *                         executeCommand(expression, function(result) {
         *                             cell.addWidget({
         *                                 html       : "
"
         *                                     + result + "
",
         *                                 coverLine  : true,
         *                                 fixedWidth : true
         *                             });
         *
         *                             done();
         *                         });
         *
         *                     }
         *                 };
         *
         *                 immediate.addEvaluator("Go Language", "go", evaluator, plugin);
         *             });
         *         });
         *     });
         *
         *
         * @class immediate
         * @extends Plugin
         * @singleton
         */
        handle.freezePublicAPI({
            get defaultEvaluator(){ return defaultEvaluator; },
            set defaultEvaluator(value){ defaultEvaluator = value; },

            _events: [
                /**
                 * Fires when an evaluator is added.
                 * @event addEvaluator
                 * @param {Object}              e
                 * @param {String}              e.caption     The caption of the evaluator.
                 * @param {String}              e.id          The unique identifier of the evaluator.
                 * @param {Evaluator} e.evaluator   The evaluator.
                 * @param {Plugin}              e.plugin      The plugin responsible for adding the evaluator.
                 */
                "addEvaluator",
                /**
                 * Fires when an evaluator is removed.
                 * @event removeEvaluator
                 * @param {Object}              e
                 * @param {String}              e.caption     The caption of the evaluator.
                 * @param {String}              e.id          The unique identifier of the evaluator.
                 * @param {Evaluator} e.evaluator   The evaluator.
                 * @param {Plugin}              e.plugin      The plugin responsible for adding the evaluator.
                 */
                "removeEvaluator"
            ],

            /**
             * Adds a new evaluator to all immediate panes. The user is able
             * to choose the evaluator from a dropdown in the UI of the
             * immediate pane.
             * @param {String}              caption     The caption in the dropdown.
             * @param {String}              id          The unique identifier of this evaluator.
             * @param {Evaluator} evaluator   The evaluator for your runtime.
             * @param {Plugin}              plugin      The plugin responsible for adding the evaluator.
             * @fires addEvaluator
             */
            addEvaluator: function(caption, id, evaluator, plugin) {
                if (replTypes[id])
                    throw new Error("An evaluator is already registered with "
                        + "the id '" + id + "'");

                replTypes[id] = {
                    caption: caption,
                    id: id,
                    evaluator: evaluator,
                    plugin: plugin
                };
                emit("addEvaluator", replTypes[id]);

                plugin.addOther(function(){
                    handle.removeEvaluator(id);
                });
            },

            /**
             * Retrieves an evaluator based on it's id. When the evaluator is
             * not yet registered, the callback will be returned when the
             * evaluator is registered.
             * @param {String}              id                  The id of the evaluator to retrieve.
             * @param {Function}            callback            Called when the evaluator is available.
             * @param {Error}               callback.id         The id of the requested evaluator.
             * @param {Evaluator} callback.evaluator  The evaluator requested.
             */
            findEvaluator: function(id, callback) {
                if (!id || !replTypes[id]) {
                    handle.on("addEvaluator", function wait(e) {
                        if (!id || e.id == id)
                            callback(e.id, replTypes[e.id].evaluator);

                        handle.off("addEvaluator", wait);
                    });
                }
                else {
                    callback(id, replTypes[id].evaluator);
                }
            },

            /**
             * Removes an evaluator from all immediate panes.
             * @param {String} id  The unique identifier of the evaluator to remove.
             */
            removeEvaluator: function(id) {
                emit("removeEvaluator", replTypes[id]);
                delete replTypes[id];
            }
        });

        register(null, {
            immediate: handle
        });
    }
});
<|endoftext|>