自定义sublime text 2 build system

Introduction

Sublime Text build systems can be considered simplistic, but highly customizable. The basic idea is that each type of Build profile is powered by a “.sublime-build” file – a JSON representations of the commands, paths and configuration needed to build a project using a specific tool or set of tools.

Builds can be executed using a keyboard shortcut (Command+B on Mac is the default on Mac or F7 on Windows), via the Tools menu or when a file is saved. If a project is currently open, the build system we last selected (e.g grunt) will be remembered.

When Sublime is passed references to external tools/binaries via a “.sublime-build” files, it can execute these applications with any arguments or flags that may be necessary. It is also able to pipe back the output of calling any of these apps using the built-in console in Sublime. Effectively this allows us to easily build projects without the need to leave our editor.

Adding a custom Build System

Sublime populates its Tools/Build System menu based on the “.sublime-build” files stored in the Sublime “Packages” directory. Should one need to locate this, it can be found in “~/Library/Application Support/Sublime Text 2/Packages/User” (if using OS X) or the corresponding Packages/User directory on other platforms.

A basic “.sublime-build” file could be represented in key/value form as follows:

?
1
2
3
4
5
6
{
     "cmd" : [ "command" , "argument" , "--flag" ],
     "selector" : [ "source.js" ],
     "path" : "/usr/local/bin" ,
     "working_dir" : "/projects/"
}

Options

cmd

Array containing the command to run and its desired arguments. If you don’t specify an absolute path, the external program will be searched in your PATH, one of your system’s environmental variables.

On Windows, GUIs are supressed.

file_regex
Optional. Regular expression (Perl-style) to capture error output of  cmd. See the next section for details.
line_regex
Optional. If  file_regex doesn’t match on the current line, but  line_regex exists, and it does match on the current line, then walk backwards through the buffer until a line matching  file regex is found, and use these two matches to determine the file and line to go to.
selector
Optional. Used when  Tools | Build System | Automatic is set to  true. Sublime Text uses this scope selector to find the appropriate build system for the active view.
working_dir
Optional. Directory to change the current directory to before running  cmd. The original current directory is restored afterwards.
encoding
Optional. Output encoding of  cmd. Must be a valid Python encoding. Defaults to  UTF-8.
target

Optional. Sublime Text command to run. Defaults to exec (Packages/Default/exec.py). This command receives the configuration data specified in the .build-system file.

Used to override the default build system command. Note that if you choose to override the default command for build systems, you can add arbitrary variables in the .sublime-build file.

env

Optional. Dictionary of environment variables to be merged with the current process’ before passing them to cmd.

Use this element, for example, to add or modify environment variables without modifying your system’s settings.

shell
Optional. If  truecmd will be run through the shell ( cmd.exebash...).
path

Optional. This string will replace the current process’ PATH before calling cmd. The old PATH value will be restored after that.

Use this option to add directories to PATH without having to modify your system’s settings.

variants
Optional. A list of dictionaries of options to override the main build system’s options. Variant  ``name``s will appear in the Command Palette for easy access if the build system’s selector matches for the active file.
name
Only valid inside a variant (see  variants). Identifies variant build systems. If  name is  Run, the variant will show up under the  Tools | Build System menu and be bound to  Ctrl + Shift + B.

Capturing Error Output with file_regex

The file_regex option uses a Perl-style regular expression to capture up to four fields of error information from the build program’s output, namely: filenameline numbercolumn number and error message. Use groups in the pattern to capture this information. The filename field and the line number field are required.

When error information is captured, you can navigate to error instances in your project’s files with F4 and Shift+F4. If available, the captured error message will be displayed in the status bar.

Platform-specific Options

The windowsosx and linux elements let you provide platform-specific data in the build system. Here’s an example:

{
    "cmd": ["ant"],
    "file_regex": "^ *\\[javac\\] (.+):([0-9]+):() (.*)$",
    "working_dir": "${project_path:${folder}}",
    "selector": "source.java",

    "windows":
    {
        "cmd": ["ant.bat"]
    }
}

In this case, ant will be executed for every platform except Windows, where ant.bat will be used instead.

Variants

Here’s a contrived example of a build system with variants:

{
    "selector": "source.python",
    "cmd": ["date"],

    "variants": [

        { "cmd": ["ls -l *.py"],
          "name": "List Python Files",
          "shell": true
        },

        { "cmd": ["wc", "$file"],
          "name": "Word Count (current file)"
        },

        { "cmd": ["python", "-u", "$file"],
          "name": "Run"
        }
    ]
}

Given these settings, Ctrl + B would run the date command, Crtl + Shift + B would run the Python interpreter and the remaining variants would appear in the Command Palette whenever the build system was active.

For a comprehensive list of keys supported in Sublime build scripts, see the unofficial docs.

Build System Variables

Build systems expand the following variables in .sublime-build files:

$file_path The directory of the current file, e.g., C:\Files.
$file The full path to the current file, e.g., C:\Files\Chapter1.txt.
$file_name The name portion of the current file, e.g., Chapter1.txt.
$file_extension The extension portion of the current file, e.g., txt.
$file_base_name The name-only portion of the current file, e.g., Document.
$packages The full path to the Packages folder.
$project The full path to the current project file.
$project_path The directory of the current project file.
$project_name The name portion of the current project file.
$project_extension The extension portion of the current project file.
$project_base_name The name-only portion of the current project file.

A complete list of substitutions supported is also available.

Grouping build tasks

Some developers also like to group together tasks within an external bash script (or equivalent). For example, here’s a simple git-ftp deploy script you can use with Sublime to commit and push your latest changes with git and then upload your latest files to FTP.

Example: Commit, Push And Upload To FTP

deployment.sh:

?
1
2
#!/bin/bash
git add . && git commit -m 'deployment' && git push && git ftp init -u username  -p password - ftp: //host.example.com/public_html

deployment.sublime-build:

?
1
2
3
4
{
   "cmd" : [ "deployment" ],
   "working_dir" : "${project_path:${folder}}"
}

If you haven’t used git-ftp before, Alex Fluger has a solid article about using it that may be of interest.

Targeting Platforms:

Sublime build files also support specifying configuration data for specific platforms (namely, OS X, Windows and Linux). Targeting a platform can easily be done by specifying another element in our config with the name of the platform. e.g

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
     "cmd" : ...
     ...
     "windows" :
     {
         "cmd" :  ...
     },
     "osx" :
     {
             "cmd" : ...
     },
     "linux" :
     {
             "cmd" : ...
     }
}

Build files for popular front-end tools

To help you get started, I’ve written a collection of “.sublime-build” files for some of the front-end tools I’m aware web developers are using these days below.

Most of these will function fine without the need to specify path, but if you run into an issue with paths, try including it to your config (e.g "path": "/usr/local/bin").

grunt:

?
1
2
3
4
{
     "cmd" : [ "grunt" , "--no-color" ],
     "selector" : [ "source.js" , "source.less" , "source.json" ]
}

Node Build Script:

?
1
2
3
4
{
     "cmd" : [ "h5bp" , "--no-color" ],
     "selector" : [ "source.js" , "source.less" , "source.json" ]
}

CoffeeScript:

?
1
2
3
4
{
     "cmd" : [ "coffee" , "-c" , "$file" ],
     "selector" : "source.coffee"
}

SASS:

?
1
2
3
4
5
{
     "cmd" : [ "sass" , "--watch" , ".:." ],
     "working_dir" : "$file_path" ,
     "selector" : [ "source.scss" , "source.sass" ]
}

Whilst a more verbose version with automatic minification and watch config could be written:

?
1
2
3
4
5
{
     "cmd" : [ "sass" , "--watch" , "sass:stylesheets" , "--style" , "compressed" ],
     "working_dir" : "$project_path" ,
     "selector" : [ "source.scss" , "source.sass" ]
}

LESS:

?
1
2
3
4
5
{
     "cmd" : [ "lessc" , "-x" , "$file" , "$file_path/$file_base_name.css" , "--verbose" ],
     "shell" : true ,
     "selector" : "source.css.less"
}

Stylus:

?
1
2
3
4
5
{
     "cmd" : [ "stylus" , "$file" ],
     "file_regex" : "." ,
     "selector" : "source.stylus"
}

(a more comprehensive version of this can be found in the LESS-build-sublimeproject.)

Jade:

?
1
2
3
4
{
    "cmd" : [ "cmd" , "/c" , "jade" , "$file" ],
    "selector" : "source.jade"
}

r.js (RequireJS Optimizer):

?
1
2
3
4
5
{
     "cmd" : [ "node" , "r.js" , "-o" , "app.build.js" ],
     "working_dir" : "$project_path" ,
     "selector" : "source.js"
}

UglifyJS:

?
1
2
3
4
{
    "cmd" : [ "node" , "uglifyjs" , "-o" , "${file_path}/${file_base_name}.min.js" , "$file" ],
    "selector" : "source.js"
}

Node (just passing in directly):

?
1
2
3
4
5
{
      "cmd" : [ "node" , "$file" ],
      "file_regex" : "^[ ]*File \"(...*?)\", line ([0-9]*)" ,
      "selector" : "source.js"
}

Pandoc (Markdown to HTML):

?
1
2
3
4
{
     "cmd" : [ "pandoc" , "-S" , "-s" , "-f" , "markdown" , "-t" , "html" , "-o" , "$file_base_name.html" , "$file" ],
     "selector" : "text.html.markdown"
}

(and when it’s released, Yeoman):

?
1
2
3
4
{
      "cmd" : [ "yeoman" , "build" , "--no-color" ],
      "selector" : [ "source.js" , "source.scss" , "source.sass" , "source.html" ]
}

JSHint:

I imagine most web developers would want to run JSHint from within a broader build process, but if you’d also like to run it standalone via a Sublime build file, the sublime-jshint package has a build file that will work fine on both OS X and Windows.

Build files for specific programming languages

I also thought that while we were looking at build files, it would be useful to demonstrate how these can be used to build/compile with some popular programming languages. These may differ to those included with Sublime by default, but are useful for reference:

Ruby (using RVM):

?
1
2
3
4
5
{
     "cmd" : [ "~/.rvm/bin/rvm-auto-ruby" , "$file" ],
     "file_regex" : "^(...*?):([0-9]*):?([0-9]*)" ,
     "selector" : "source.ruby"
}

Python:

?
1
2
3
4
5
{
     "cmd" : [ "python" , "-u" , "$file" ],
     "file_regex" : "^[ ]*File \"(...*?)\", line ([0-9]*)" ,
     "selector" : "source.python"
}

PHP:

?
1
2
3
4
5
{
     "cmd" : [ "/usr/bin/php" , "-l" , "$file" ], <- Couldn't just use "php" ?
     "file_regex" : "^Parse error: .* in (.*?) on line ([0-9]*)" ,
     "selector" : "source.php"
}

Java:

?
1
2
3
4
5
6
{
     "cmd" : [ "javac" , "$file_name" , "&&" , "java" , "$file_base_name" ],
     "working_dir" : "${project_path:${folder}}" ,
     "selector" : "source.java" ,
     "shell" : true
}

.Net (Windows):

?
1
2
3
4
5
{
     "cmd" : [ "%WINDIR%\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild" , "${project_base_name}.sln" ],
     "shell" : true ,
     "working_dir" : "${project_path:${folder}}"
}

C:

?
1
2
3
4
5
{
     "cmd" : [ "make && ./a.out" ],
     "path" : "/usr/bin:/usr/local/bin:..." ,
     "shell" : true
}

C++ (via g++):

(Note that we’re also able to specify OS-specific configurations too, as in the below):

?
1
2
3
4
5
6
7
{
     "cmd" : [ "g++" , "$file" , "-o" , "$file_base_name" , "-I/usr/local/include" ],
     "selector" : "source.c++" ,
     "windows" : {
        "cmd" : [ "cl" , "/Fo${file_path}" , "/O2" , "$file" ]
     }
}

Haskell:

?
1
2
3
4
5
{
     "cmd" : [ "runhaskell" , "$file" ],
     "file_regex" : "^(...*?):([0-9]*):?([0-9]*)" ,
     "selector" : "source.haskell"
}

Conclusions

Sublime build systems are awesome and can help you avoid the need to manually switch between your editor and external build tools regularly. As you’ve hopefully now learned, putting together your own custom build systems is a straight-forward process and I’d recommend trying it out if Sublime happens to be your editor of choice.

Mutiple command

It seems that the Sublime Build System only allows for one cmd. The most common solution I've found is to make a bash script with multiple commands and run the bash script from the Sublime build system.

#!/bin/bash          
# compiles all java files within directory and runs first argument
for file in *.java
do
echo "Compiling $file"
javac $file
done
echo "Running $1"
java $1
{
    "cmd": ["build_java.sh", "$file_base_name"]
}

考至:http://addyosmani.com/blog/custom-sublime-text-build-systems-for-popular-tools-and-languages/

                 http://www.youtube.com/results?search_query=Sublime%20text%202%20project&oq=Sublime%20text%202%20project&gs_l=youtube.3...1485914.1490529.0.1491872.9.9.0.0.0.0.520.3182.2j1j4-3j3.9.0...0.0...1ac.1.11.youtube.pSdgI6sgT0k

                https://gist.github.com/DevinClark/1633819

                http://docs.sublimetext.info/en/latest/reference/build_systems.html#platform-specific-options

如有错误,欢迎指正

邮箱:[email protected]

猜你喜欢

转载自czmmiao.iteye.com/blog/1961667