1
0
Fork 0
mirror of https://github.com/janickiy/yii2-nomer synced 2025-03-09 15:39:59 +00:00

add files to project

This commit is contained in:
janickiy 2020-02-05 06:34:26 +03:00
commit 5cac498444
3729 changed files with 836998 additions and 0 deletions

View file

@ -0,0 +1,604 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("clike", function(config, parserConfig) {
var indentUnit = config.indentUnit,
statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
dontAlignCalls = parserConfig.dontAlignCalls,
keywords = parserConfig.keywords || {},
types = parserConfig.types || {},
builtin = parserConfig.builtin || {},
blockKeywords = parserConfig.blockKeywords || {},
defKeywords = parserConfig.defKeywords || {},
atoms = parserConfig.atoms || {},
hooks = parserConfig.hooks || {},
multiLineStrings = parserConfig.multiLineStrings,
indentStatements = parserConfig.indentStatements !== false,
indentSwitch = parserConfig.indentSwitch !== false,
namespaceSeparator = parserConfig.namespaceSeparator;
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
var curPunc, isDefKeyword;
function tokenBase(stream, state) {
var ch = stream.next();
if (hooks[ch]) {
var result = hooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null;
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
}
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
}
if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
stream.eatWhile(/[\w\$_\xa1-\uffff]/);
if (namespaceSeparator) while (stream.match(namespaceSeparator))
stream.eatWhile(/[\w\$_\xa1-\uffff]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
if (defKeywords.propertyIsEnumerable(cur)) isDefKeyword = true;
return "keyword";
}
if (types.propertyIsEnumerable(cur)) return "variable-3";
if (builtin.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "builtin";
}
if (atoms.propertyIsEnumerable(cur)) return "atom";
return "variable";
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next, end = false;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {end = true; break;}
escaped = !escaped && next == "\\";
}
if (end || !(escaped || multiLineStrings))
state.tokenize = null;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function isStatement(type) {
return type == "statement" || type == "switchstatement" || type == "namespace";
}
function pushContext(state, col, type) {
var indent = state.indented;
if (state.context && isStatement(state.context.type) && !isStatement(type))
indent = state.context.indented;
return state.context = new Context(indent, col, type, null, state.context);
}
function popContext(state) {
var t = state.context.type;
if (t == ")" || t == "]" || t == "}")
state.indented = state.context.indented;
return state.context = state.context.prev;
}
function typeBefore(stream, state) {
if (state.prevToken == "variable" || state.prevToken == "variable-3") return true;
if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, stream.start))) return true;
}
function isTopScope(context) {
for (;;) {
if (!context || context.type == "top") return true;
if (context.type == "}" && context.prev.type != "namespace") return false;
context = context.prev;
}
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: null,
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
indented: 0,
startOfLine: true,
prevToken: null
};
},
token: function(stream, state) {
var ctx = state.context;
if (stream.sol()) {
if (ctx.align == null) ctx.align = false;
state.indented = stream.indentation();
state.startOfLine = true;
}
if (stream.eatSpace()) return null;
curPunc = isDefKeyword = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":" || curPunc == ","))
while (isStatement(state.context.type)) popContext(state);
else if (curPunc == "{") pushContext(state, stream.column(), "}");
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == "}") {
while (isStatement(ctx.type)) ctx = popContext(state);
if (ctx.type == "}") ctx = popContext(state);
while (isStatement(ctx.type)) ctx = popContext(state);
}
else if (curPunc == ctx.type) popContext(state);
else if (indentStatements &&
(((ctx.type == "}" || ctx.type == "top") && curPunc != ";") ||
(isStatement(ctx.type) && curPunc == "newstatement"))) {
var type = "statement";
if (curPunc == "newstatement" && indentSwitch && stream.current() == "switch")
type = "switchstatement";
else if (style == "keyword" && stream.current() == "namespace")
type = "namespace";
pushContext(state, stream.column(), type);
}
if (style == "variable" &&
((state.prevToken == "def" ||
(parserConfig.typeFirstDefinitions && typeBefore(stream, state) &&
isTopScope(state.context) && stream.match(/^\s*\(/, false)))))
style = "def";
if (hooks.token) {
var result = hooks.token(stream, state, style);
if (result !== undefined) style = result;
}
if (style == "def" && parserConfig.styleDefs === false) style = "variable";
state.startOfLine = false;
state.prevToken = isDefKeyword ? "def" : style || curPunc;
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
if (isStatement(ctx.type) && firstChar == "}") ctx = ctx.prev;
var closing = firstChar == ctx.type;
var switchBlock = ctx.prev && ctx.prev.type == "switchstatement";
if (isStatement(ctx.type))
return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
if (ctx.align && (!dontAlignCalls || ctx.type != ")"))
return ctx.column + (closing ? 0 : 1);
if (ctx.type == ")" && !closing)
return ctx.indented + statementIndentUnit;
return ctx.indented + (closing ? 0 : indentUnit) +
(!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0);
},
electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
blockCommentStart: "/*",
blockCommentEnd: "*/",
lineComment: "//",
fold: "brace"
};
});
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var cKeywords = "auto if break case register continue return default do sizeof " +
"static else struct switch extern typedef float union for " +
"goto while enum const volatile";
var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t";
function cppHook(stream, state) {
if (!state.startOfLine) return false;
for (;;) {
if (stream.skipTo("\\")) {
stream.next();
if (stream.eol()) {
state.tokenize = cppHook;
break;
}
} else {
stream.skipToEnd();
state.tokenize = null;
break;
}
}
return "meta";
}
function pointerHook(_stream, state) {
if (state.prevToken == "variable-3") return "variable-3";
return false;
}
function cpp11StringHook(stream, state) {
stream.backUp(1);
// Raw strings.
if (stream.match(/(R|u8R|uR|UR|LR)/)) {
var match = stream.match(/"([^\s\\()]{0,16})\(/);
if (!match) {
return false;
}
state.cpp11RawStringDelim = match[1];
state.tokenize = tokenRawString;
return tokenRawString(stream, state);
}
// Unicode strings/chars.
if (stream.match(/(u8|u|U|L)/)) {
if (stream.match(/["']/, /* eat */ false)) {
return "string";
}
return false;
}
// Ignore this hook.
stream.next();
return false;
}
function cppLooksLikeConstructor(word) {
var lastTwo = /(\w+)::(\w+)$/.exec(word);
return lastTwo && lastTwo[1] == lastTwo[2];
}
// C#-style strings where "" escapes a quote.
function tokenAtString(stream, state) {
var next;
while ((next = stream.next()) != null) {
if (next == '"' && !stream.eat('"')) {
state.tokenize = null;
break;
}
}
return "string";
}
// C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
// <delim> can be a string up to 16 characters long.
function tokenRawString(stream, state) {
// Escape characters that have special regex meanings.
var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
if (match)
state.tokenize = null;
else
stream.skipToEnd();
return "string";
}
function def(mimes, mode) {
if (typeof mimes == "string") mimes = [mimes];
var words = [];
function add(obj) {
if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
words.push(prop);
}
add(mode.keywords);
add(mode.types);
add(mode.builtin);
add(mode.atoms);
if (words.length) {
mode.helperType = mimes[0];
CodeMirror.registerHelper("hintWords", mimes[0], words);
}
for (var i = 0; i < mimes.length; ++i)
CodeMirror.defineMIME(mimes[i], mode);
}
def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
name: "clike",
keywords: words(cKeywords),
types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " +
"int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " +
"uint32_t uint64_t"),
blockKeywords: words("case do else for if switch while struct"),
defKeywords: words("struct"),
typeFirstDefinitions: true,
atoms: words("null true false"),
hooks: {"#": cppHook, "*": pointerHook},
modeProps: {fold: ["brace", "include"]}
});
def(["text/x-c++src", "text/x-c++hdr"], {
name: "clike",
keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " +
"static_cast typeid catch operator template typename class friend private " +
"this using const_cast inline public throw virtual delete mutable protected " +
"alignas alignof constexpr decltype nullptr noexcept thread_local final " +
"static_assert override"),
types: words(cTypes + " bool wchar_t"),
blockKeywords: words("catch class do else finally for if struct switch try while"),
defKeywords: words("class namespace struct enum union"),
typeFirstDefinitions: true,
atoms: words("true false null"),
hooks: {
"#": cppHook,
"*": pointerHook,
"u": cpp11StringHook,
"U": cpp11StringHook,
"L": cpp11StringHook,
"R": cpp11StringHook,
token: function(stream, state, style) {
if (style == "variable" && stream.peek() == "(" &&
(state.prevToken == ";" || state.prevToken == null ||
state.prevToken == "}") &&
cppLooksLikeConstructor(stream.current()))
return "def";
}
},
namespaceSeparator: "::",
modeProps: {fold: ["brace", "include"]}
});
def("text/x-java", {
name: "clike",
keywords: words("abstract assert break case catch class const continue default " +
"do else enum extends final finally float for goto if implements import " +
"instanceof interface native new package private protected public " +
"return static strictfp super switch synchronized this throw throws transient " +
"try volatile while"),
types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " +
"Integer Long Number Object Short String StringBuffer StringBuilder Void"),
blockKeywords: words("catch class do else finally for if switch try while"),
defKeywords: words("class interface package enum"),
typeFirstDefinitions: true,
atoms: words("true false null"),
hooks: {
"@": function(stream) {
stream.eatWhile(/[\w\$_]/);
return "meta";
}
},
modeProps: {fold: ["brace", "import"]}
});
def("text/x-csharp", {
name: "clike",
keywords: words("abstract as async await base break case catch checked class const continue" +
" default delegate do else enum event explicit extern finally fixed for" +
" foreach goto if implicit in interface internal is lock namespace new" +
" operator out override params private protected public readonly ref return sealed" +
" sizeof stackalloc static struct switch this throw try typeof unchecked" +
" unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
" global group into join let orderby partial remove select set value var yield"),
types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" +
" Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" +
" UInt64 bool byte char decimal double short int long object" +
" sbyte float string ushort uint ulong"),
blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
defKeywords: words("class interface namespace struct var"),
typeFirstDefinitions: true,
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
if (stream.eat('"')) {
state.tokenize = tokenAtString;
return tokenAtString(stream, state);
}
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
function tokenTripleString(stream, state) {
var escaped = false;
while (!stream.eol()) {
if (!escaped && stream.match('"""')) {
state.tokenize = null;
break;
}
escaped = stream.next() == "\\" && !escaped;
}
return "string";
}
def("text/x-scala", {
name: "clike",
keywords: words(
/* scala */
"abstract case catch class def do else extends false final finally for forSome if " +
"implicit import lazy match new null object override package private protected return " +
"sealed super this throw trait try type val var while with yield _ : = => <- <: " +
"<% >: # @ " +
/* package scala */
"assert assume require print println printf readLine readBoolean readByte readShort " +
"readChar readInt readLong readFloat readDouble " +
":: #:: "
),
types: words(
"AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
"Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
"Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
"Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
"StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " +
/* package java.lang */
"Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
"Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
"Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
"StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
),
multiLineStrings: true,
blockKeywords: words("catch class do else finally for forSome if match switch try while"),
defKeywords: words("class def object package trait type val var"),
atoms: words("true false null"),
indentStatements: false,
indentSwitch: false,
hooks: {
"@": function(stream) {
stream.eatWhile(/[\w\$_]/);
return "meta";
},
'"': function(stream, state) {
if (!stream.match('""')) return false;
state.tokenize = tokenTripleString;
return state.tokenize(stream, state);
},
"'": function(stream) {
stream.eatWhile(/[\w\$_\xa1-\uffff]/);
return "atom";
}
},
modeProps: {closeBrackets: {triples: '"'}}
});
def(["x-shader/x-vertex", "x-shader/x-fragment"], {
name: "clike",
keywords: words("sampler1D sampler2D sampler3D samplerCube " +
"sampler1DShadow sampler2DShadow " +
"const attribute uniform varying " +
"break continue discard return " +
"for while do if else struct " +
"in out inout"),
types: words("float int bool void " +
"vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
"mat2 mat3 mat4"),
blockKeywords: words("for while do if else struct"),
builtin: words("radians degrees sin cos tan asin acos atan " +
"pow exp log exp2 sqrt inversesqrt " +
"abs sign floor ceil fract mod min max clamp mix step smoothstep " +
"length distance dot cross normalize ftransform faceforward " +
"reflect refract matrixCompMult " +
"lessThan lessThanEqual greaterThan greaterThanEqual " +
"equal notEqual any all not " +
"texture1D texture1DProj texture1DLod texture1DProjLod " +
"texture2D texture2DProj texture2DLod texture2DProjLod " +
"texture3D texture3DProj texture3DLod texture3DProjLod " +
"textureCube textureCubeLod " +
"shadow1D shadow2D shadow1DProj shadow2DProj " +
"shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
"dFdx dFdy fwidth " +
"noise1 noise2 noise3 noise4"),
atoms: words("true false " +
"gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
"gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
"gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
"gl_FogCoord gl_PointCoord " +
"gl_Position gl_PointSize gl_ClipVertex " +
"gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
"gl_TexCoord gl_FogFragCoord " +
"gl_FragCoord gl_FrontFacing " +
"gl_FragData gl_FragDepth " +
"gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
"gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
"gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
"gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
"gl_ProjectionMatrixInverseTranspose " +
"gl_ModelViewProjectionMatrixInverseTranspose " +
"gl_TextureMatrixInverseTranspose " +
"gl_NormalScale gl_DepthRange gl_ClipPlane " +
"gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
"gl_FrontLightModelProduct gl_BackLightModelProduct " +
"gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
"gl_FogParameters " +
"gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
"gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
"gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
"gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
"gl_MaxDrawBuffers"),
indentSwitch: false,
hooks: {"#": cppHook},
modeProps: {fold: ["brace", "include"]}
});
def("text/x-nesc", {
name: "clike",
keywords: words(cKeywords + "as atomic async call command component components configuration event generic " +
"implementation includes interface module new norace nx_struct nx_union post provides " +
"signal task uses abstract extends"),
types: words(cTypes),
blockKeywords: words("case do else for if switch while struct"),
atoms: words("null true false"),
hooks: {"#": cppHook},
modeProps: {fold: ["brace", "include"]}
});
def("text/x-objectivec", {
name: "clike",
keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginery BOOL Class bycopy byref id IMP in " +
"inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),
types: words(cTypes),
atoms: words("YES NO NULL NILL ON OFF true false"),
hooks: {
"@": function(stream) {
stream.eatWhile(/[\w\$]/);
return "keyword";
},
"#": cppHook
},
modeProps: {fold: "brace"}
});
def("text/x-squirrel", {
name: "clike",
keywords: words("base break clone continue const default delete enum extends function in class" +
" foreach local resume return this throw typeof yield constructor instanceof static"),
types: words(cTypes),
blockKeywords: words("case catch class else for foreach if switch try while"),
defKeywords: words("function local class"),
typeFirstDefinitions: true,
atoms: words("true false null"),
hooks: {"#": cppHook},
modeProps: {fold: ["brace", "include"]}
});
});

View file

@ -0,0 +1,125 @@
<!doctype html>
<title>CodeMirror: C-like mode</title>
<meta charset="utf-8" />
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/edit/matchbrackets.js"></script>
<link rel="stylesheet" href="../../addon/hint/show-hint.css">
<script src="../../addon/hint/show-hint.js"></script>
<script src="clike.js"></script>
<style>
.CodeMirror {
border: 2px inset #dee;
}
</style>
<div id=nav>
<a href="http://codemirror.net">
<h1>CodeMirror</h1>
<img id=logo src="../../doc/logo.png">
</a>
<ul>
<li>
<a href="../../index.html">Home</a>
<li>
<a href="../../doc/manual.html">Manual</a>
<li>
<a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li>
<a href="../index.html">Language modes</a>
<li>
<a class=active href="#">C-like</a>
</ul>
</div>
<article>
<h2>C-like mode</h2>
<div>
<textarea id="c-code"> /* C demo code */ #include
<zmq.h> #include
<pthread.h> #include
<semaphore.h> #include
<time.h> #include
<stdio.h> #include
<fcntl.h> #include
<malloc.h> typedef struct { void* arg_socket; zmq_msg_t* arg_msg; char* arg_string; unsigned long arg_len; int arg_int, arg_command; int signal_fd; int pad; void* context; sem_t sem; } acl_zmq_context; #define p(X) (context->arg_##X)
void* zmq_thread(void* context_pointer) { acl_zmq_context* context = (acl_zmq_context*)context_pointer; char ok = 'K', err = 'X'; int res; while (1) { while ((res = sem_wait(&amp;context->sem)) == EINTR); if (res)
{write(context->signal_fd, &amp;err, 1); goto cleanup;} switch(p(command)) { case 0: goto cleanup; case 1: p(socket) = zmq_socket(context->context, p(int)); break; case 2: p(int) = zmq_close(p(socket)); break; case
3: p(int) = zmq_bind(p(socket), p(string)); break; case 4: p(int) = zmq_connect(p(socket), p(string)); break; case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &amp;p(len)); break; case 6: p(int)
= zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break; case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break; case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break; case 9: p(int) = zmq_poll(p(socket),
p(int), p(len)); break; } p(command) = errno; write(context->signal_fd, &amp;ok, 1); } cleanup: close(context->signal_fd); free(context_pointer); return 0; } void* zmq_thread_init(void* zmq_context, int signal_fd)
{ acl_zmq_context* context = malloc(sizeof(acl_zmq_context)); pthread_t thread; context->context = zmq_context; context->signal_fd = signal_fd; sem_init(&amp;context->sem, 1, 0); pthread_create(&amp;thread, 0, &amp;zmq_thread,
context); pthread_detach(thread); return context; } </textarea>
</div>
<h2>C++ example</h2>
<div>
<textarea id="cpp-code"> #include
<iostream> #include "mystuff/util.h" namespace { enum Enum { VAL1, VAL2, VAL3 }; char32_t unicode_string = U"\U0010FFFF"; string raw_string = R"delim(anything you want)delim"; int Helper(const MyType& param) { return 0; } } // namespace class ForwardDec;
template
<class T, class V> class Class : public BaseClass { const MyType
<T, V> member_; public: const MyType
<T, V>& Method() const { return member_; } void Method2(MyType
<T, V>* value); } template
<class T, class V> void Class::Method2(MyType
<T, V>* value) { std::out
<< 1>> method(); value->Method3(member_); member_ = value; } </textarea>
</div>
<h2>Objective-C example</h2>
<div>
<textarea id="objectivec-code"> /* This is a longer comment That spans two lines */ #import
<Test/Test.h> @implementation YourAppDelegate // This is a one-line comment - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ char myString[] = "This is a C character array"; int test = 5; return
YES; } </textarea>
</div>
<h2>Java example</h2>
<div>
<textarea id="java-code"> import com.demo.util.MyType; import com.demo.util.MyInterface; public enum Enum { VAL1, VAL2, VAL3 } public class Class
<T, V> implements MyInterface { public static final MyType
<T, V> member; private class InnerClass { public int zero() { return 0; } } @Override public MyType method() { return member; } public void method2(MyType
<T, V> value) { method(); value.method3(); member = value; } } </textarea>
</div>
<h2>Scala example</h2>
<div>
<textarea id="scala-code"> object FilterTest extends App { def filter(xs: List[Int], threshold: Int) = { def process(ys: List[Int]): List[Int] = if (ys.isEmpty) ys else if (ys.head
< threshold) ys.head :: process(ys.tail) else process(ys.tail) process(xs) } println(filter(List(1,
9, 2, 8, 3, 7, 4), 5)) } </textarea>
</div>
<script>
var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code"),
{
lineNumbers: true,
matchBrackets: true,
mode: "text/x-csrc"
});
var cppEditor = CodeMirror.fromTextArea(document.getElementById("cpp-code"),
{
lineNumbers: true,
matchBrackets: true,
mode: "text/x-c++src"
});
var javaEditor = CodeMirror.fromTextArea(document.getElementById("java-code"),
{
lineNumbers: true,
matchBrackets: true,
mode: "text/x-java"
});
var objectivecEditor = CodeMirror.fromTextArea(document.getElementById("objectivec-code"),
{
lineNumbers: true,
matchBrackets: true,
mode: "text/x-objectivec"
});
var scalaEditor = CodeMirror.fromTextArea(document.getElementById("scala-code"),
{
lineNumbers: true,
matchBrackets: true,
mode: "text/x-scala"
});
var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault;
CodeMirror.keyMap.default[(mac ? "Cmd" : "Ctrl") + "-Space"] = "autocomplete";
</script>
<p>Simple mode that tries to handle C-like languages as well as it can. Takes two configuration parameters: <code>keywords</code>, an object whose property names are the keywords in the language, and <code>useCPP</code>, which determines whether C preprocessor
directives are recognized.</p>
<p>
<strong>MIME types defined:</strong> <code>text/x-csrc</code> (C), <code>text/x-c++src</code> (C++), <code>text/x-java</code> (Java), <code>text/x-csharp</code> (C#), <code>text/x-objectivec</code> (Objective-C), <code>text/x-scala</code> (Scala), <code>text/x-vertex</code> and <code>x-shader/x-fragment</code> (shader programs), <code>text/x-squirrel</code> (Squirrel).</p>
</article>

View file

@ -0,0 +1,173 @@
<!doctype html>
<title>CodeMirror: Scala mode</title>
<meta charset="utf-8" />
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<link rel="stylesheet" href="../../theme/ambiance.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/edit/matchbrackets.js"></script>
<script src="clike.js"></script>
<div id=nav>
<a href="http://codemirror.net">
<h1>CodeMirror</h1>
<img id=logo src="../../doc/logo.png">
</a>
<ul>
<li>
<a href="../../index.html">Home</a>
<li>
<a href="../../doc/manual.html">Manual</a>
<li>
<a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li>
<a href="../index.html">Language modes</a>
<li>
<a class=active href="#">Scala</a>
</ul>
</div>
<article>
<h2>Scala mode</h2>
<form>
<textarea id="code" name="code"> /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package scala.collection import generic._
import mutable.{ Builder, ListBuffer } import annotation.{tailrec, migration, bridge} import annotation.unchecked.{ uncheckedVariance => uV } import parallel.ParIterable /** A template trait for traversable collections of type `Traversable[A]`.
* * $traversableInfo * @define mutability * @define traversableInfo * This is a base trait of all kinds of $mutability Scala collections. It * implements the behavior common to all collections, in terms of a method * `foreach` with signature:
* {{{ * def foreach[U](f: Elem => U): Unit * }}} * Collection classes mixing in this trait provide a concrete * `foreach` method which traverses all the * elements contained in the collection, applying a given function to each. * They also
need to provide a method `newBuilder` * which creates a builder for collections of the same kind. * * A traversable class might or might not have two properties: strictness * and orderedness. Neither is represented as a type. * * The instances
of a strict collection class have all their elements * computed before they can be used as values. By contrast, instances of * a non-strict collection class may defer computation of some of their * elements until after the instance is available
as a value. * A typical example of a non-strict collection class is a *
<a href="../immutable/Stream.html" target="ContentFrame"> * `scala.collection.immutable.Stream`</a>. * A more general class of examples are `TraversableViews`. * * If a collection is an instance of an ordered collection class, traversing * its elements with `foreach` will always visit elements in
the * same order, even for different runs of the program. If the class is not * ordered, `foreach` can visit elements in different orders for * different runs (but it will keep the same order in the same run).' * * A typical example of a collection
class which is not ordered is a * `HashMap` of objects. The traversal order for hash maps will * depend on the hash codes of its elements, and these hash codes might * differ from one run to the next. By contrast, a `LinkedHashMap` * is ordered
because it's `foreach` method visits elements in the * order they were inserted into the `HashMap`. * * @author Martin Odersky * @version 2.8 * @since 2.8 * @tparam A the element type of the collection * @tparam Repr the type of the actual
collection containing the elements. * * @define Coll Traversable * @define coll traversable collection */ trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] with FilterMonadic[A, Repr] with TraversableOnce[A] with GenTraversableLike[A,
Repr] with Parallelizable[A, ParIterable[A]] { self => import Traversable.breaks._ /** The type implementing this traversable */ protected type Self = Repr /** The collection of type $coll underlying this `TraversableLike` object. * By default
this is implemented as the `TraversableLike` object itself, * but this can be overridden. */ def repr: Repr = this.asInstanceOf[Repr] /** The underlying collection seen as an instance of `$Coll`. * By default this is implemented as the current
collection object itself, * but this can be overridden. */ protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]] /** A conversion from collections of type `Repr` to `$Coll` objects. * By default this is implemented
as just a cast, but this can be overridden. */ protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]] /** Creates a new builder for this collection type. */ protected[this] def newBuilder: Builder[A,
Repr] protected[this] def parCombiner = ParIterable.newCombiner[A] /** Applies a function `f` to all elements of this $coll. * * Note: this method underlies the implementation of most other bulk operations. * It's important to implement this
method in an efficient way. * * * @param f the function that is applied for its side-effect to every element. * The result of function `f` is discarded. * * @tparam U the type parameter describing the result of function `f`. * This result
will always be ignored. Typically `U` is `Unit`, * but this is not necessary. * * @usecase def foreach(f: A => Unit): Unit */ def foreach[U](f: A => U): Unit /** Tests whether this $coll is empty. * * @return `true` if the $coll contain no
elements, `false` otherwise. */ def isEmpty: Boolean = { var result = true breakable { for (x
<- this) { result=f alse break } } result } /** Tests whether this $coll is known to have a finite size. * All strict collections are known to have
finite size. For a non-strict collection * such as `Stream`, the predicate returns `true` if all elements have been computed. * It returns `false` if the stream is not yet evaluated to the end. * * Note: many collection methods will not work
on collections of infinite sizes. * * @return `true` if this collection is known to have finite size, `false` otherwise. */ def hasDefiniteSize=t rue def ++[B>: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size) b ++= thisCollection b ++= that.seq b.result } @bridge
def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = ++(that: GenTraversableOnce[B])(bf) /** Concatenates this $coll with the elements of a traversable collection. * It differs from ++ in that
the right operand determines the type of the * resulting collection rather than the left one. * * @param that the traversable to append. * @tparam B the element type of the returned collection. * @tparam That $thatinfo * @param bf $bfinfo
* @return a new collection of type `That` which contains all elements * of this $coll followed by all elements of `that`. * * @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B] * * @return a new $coll which contains all elements of
this $coll * followed by all elements of `that`. */ def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)
b ++= that b ++= thisCollection b.result } /** This overload exists because: for the implementation of ++: we should reuse * that of ++ because many collections override it with more efficient versions. * Since TraversableOnce has no '++'
method, we have to implement that directly, * but Traversable and down can use the overload. */ def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = (that ++ seq)(breakOut) def map[B, That](f: A
=> B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) b.sizeHint(this) for (x
<- this) b +=f (x) b.result } def flatMap[B, That](f: A=> GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) for (x
<- this) b ++=f (x).seq b.result } /** Selects all elements of this $coll which satisfy a predicate. * * @param p the predicate used to
test elements. * @return a new $coll consisting of all elements of this $coll that satisfy the given * predicate `p`. The order of the elements is preserved. */ def filter(p: A=> Boolean): Repr = { val b = newBuilder for (x
<- this) if (p(x)) b +=x b.result } /** Selects all elements of this $coll which do not satisfy a predicate. * * @param p the predicate used to test elements. * @return a new $coll consisting
of all elements of this $coll that do not satisfy the given * predicate `p`. The order of the elements is preserved. */ def filterNot(p: A=> Boolean): Repr = filter(!p(_)) def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) for (x
<- this) if (pf.isDefinedAt(x)) b +=p f(x) b.result } /** Builds a new collection
by applying an option-valued function to all * elements of this $coll on which the function is defined. * * @param f the option-valued function which filters and maps the $coll. * @tparam B the element type of the returned
collection. * @tparam That $thatinfo * @param bf $bfinfo * @return a new collection of type `That` resulting from applying the option-valued function * `f` to each element and collecting all defined results. * The order of
the elements is preserved. * * @usecase def filterMap[B](f: A=> Option[B]): $Coll[B] * * @param pf the partial function which filters and maps the $coll. * @return a new $coll resulting from applying the given option-valued function * `f` to each element and collecting all defined results.
* The order of the elements is preserved. def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) for (x
<- this) f(x) match { case Some(y)=> b += y case _ => } b.result } */ /** Partitions this $coll in two ${coll}s according to a predicate. * * @param p the predicate on which to partition. * @return a pair of ${coll}s: the first $coll consists of all elements
that * satisfy the predicate `p` and the second $coll consists of all elements * that don't. The relative order of the elements in the resulting ${coll}s * is the same as in the original $coll. */ def partition(p: A
=> Boolean): (Repr, Repr) = { val l, r = newBuilder for (x
<- this) (if (p(x)) l else r) +=x (l.result, r.result) } def groupBy[K](f: A=> K): immutable.Map[K, Repr] = { val m = mutable.Map.empty[K, Builder[A, Repr]] for (elem
<- this) { val key=f (elem) val bldr=m .getOrElseUpdate(key, newBuilder) bldr +=e lem } val b=i mmutable.Map.newBuilder[K, Repr]
for ((k, v) <- m) b +=( (k, v.result)) b.result } /** Tests whether a predicate holds for all elements of this $coll. * * $mayNotTerminateInf * * @param p the predicate used to test elements. * @return `true` if
the given predicate `p` holds for all elements * of this $coll, otherwise `false`. */ def forall(p: A=> Boolean): Boolean = { var result = true breakable { for (x
<- this) if (!p(x)) { result=f alse; break } } result } /** Tests whether a predicate holds for some of the elements of this $coll. * * $mayNotTerminateInf
* * @param p the predicate used to test elements. * @return `true` if the given predicate `p` holds for some of the * elements of this $coll, otherwise `false`. */ def exists(p: A=> Boolean): Boolean = { var result = false breakable { for (x
<- this) if (p(x)) { result=t rue; break } } result } /** Finds the first element of the $coll satisfying a predicate, if any. * * $mayNotTerminateInf
* $orderDependent * * @param p the predicate used to test elements. * @return an option value containing the first element in the $coll * that satisfies `p`, or `None` if none exists. */ def find(p: A=>
Boolean): Option[A] = { var result: Option[A] = None breakable { for (x
<- this) if (p(x)) { result=S ome(x); break } } result } def scan[B>: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op) def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { val
b = bf(repr) b.sizeHint(this, 1) var acc = z b += acc for (x
<- this) { acc=o p(acc, x); b +=a cc } b.result } @migration(2, 9, "This scanRight definition has changed in 2.9.\n" +
"The previous behavior can be reproduced with scanRight.reverse." ) def scanRight[B, That](z: B)(op: (A, B)=> B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { var scanned = List(z) var acc = z for (x
<- reversed) { acc=o p(x, acc) scanned ::=a cc } val b=b f(repr) for (elem <- scanned) b +=e lem b.result
} /** Selects the first element of this $coll. * $orderDependent * @return the first element of this $coll. * @throws `NoSuchElementException` if the $coll is empty. */ def head: A={ var result:
()=> A = () => throw new NoSuchElementException breakable { for (x
<- this) { result=( )=> x break } } result() } /** Optionally selects the first element. * $orderDependent * @return the first element of this $coll if it is nonempty, `None` if it is empty. */ def headOption: Option[A]
= if (isEmpty) None else Some(head) /** Selects all elements except the first. * $orderDependent * @return a $coll consisting of all elements of this $coll * except the first one. * @throws
`UnsupportedOperationException` if the $coll is empty. */ override def tail: Repr = { if (isEmpty) throw new UnsupportedOperationException("empty.tail") drop(1) } /** Selects the last
element. * $orderDependent * @return The last element of this $coll. * @throws NoSuchElementException If the $coll is empty. */ def last: A = { var lst = head for (x
<- this) lst=x lst
} /** Optionally selects the last element. * $orderDependent * @return the last element of this $coll$ if it is nonempty, `None` if it is empty. */ def lastOption: Option[A]=i f (isEmpty)
None else Some(last) /** Selects all elements except the last. * $orderDependent * @return a $coll consisting of all elements of this $coll * except the last one. * @throws `UnsupportedOperationException`
if the $coll is empty. */ def init: Repr={ if (isEmpty) throw new UnsupportedOperationException( "empty.init") var lst=h ead var follow=f alse val b=n ewBuilder b.sizeHint(this, -1) for
(x <- this.seq) { if (follow) b +=l st else follow=t rue lst=x } b.result } def take(n: Int): Repr=s lice(0, n) def drop(n: Int): Repr=i f (n <=0 ) { val b=n ewBuilder b.sizeHint(this)
b ++=t hisCollection result } else sliceWithKnownDelta(n, Int.MaxValue, -n) def slice(from: Int, until: Int): Repr=s liceWithKnownBound(math.max(from, 0), until) // Precondition: from>= 0, until > 0, builder already configured for building. private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = { var i = 0 breakable { for (x
<- this.seq)
{ if (i>= from) b += x i += 1 if (i >= until) break } } b.result } // Precondition: from >= 0 private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = { val b = newBuilder
if (until
<=f rom) b.result else { b.sizeHint(this, delta) sliceInternal(from, until, b) } } // Precondition: from>= 0 private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = { val b = newBuilder if (until
<=f rom) b.result else { b.sizeHintBounded(until - from, this) sliceInternal(from,
until, b) } } def takeWhile(p: A=> Boolean): Repr = { val b = newBuilder breakable { for (x
<- this) { if (!p(x)) break b +=x } } b.result } def dropWhile(p: A=> Boolean): Repr = { val b = newBuilder var go = false for (x
<- this) { if (!p(x)) go=t rue if (go) b +=x } b.result } def span(p: A=> Boolean): (Repr, Repr) = { val l, r = newBuilder var toLeft = true for (x
<- this) { toLeft=t oLeft && p(x) (if (toLeft) l else r) +=x } (l.result, r.result) } def
splitAt(n: Int): (Repr, Repr)={ val l, r=n ewBuilder l.sizeHintBounded(n, this) if (n>= 0) r.sizeHint(this, -n) var i = 0 for (x
<- this) { (if (i < n) l else r) +=x i +=1 } (l.result, r.result) } /** Iterates over the tails of this $coll. The first
value will be this * $coll and the final one will be an empty $coll, with the intervening * values the results of successive applications of `tail`. * * @return
an iterator over all the tails of this $coll * @example `List(1,2,3).tails=I terator(List(1,2,3), List(2,3), List(3), Nil)` */ def tails: Iterator[Repr]=i
terateUntilEmpty(_.tail) /** Iterates over the inits of this $coll. The first value will be this * $coll and the final one will be an empty $coll, with the
intervening * values the results of successive applications of `init`. * * @return an iterator over all the inits of this $coll * @example `List(1,2,3).inits=I
terator(List(1,2,3), List(1,2), List(1), Nil)` */ def inits: Iterator[Repr]=i terateUntilEmpty(_.init) /** Copies elements of this $coll to an array. * Fills
the given array `xs` with at most `len` elements of * this $coll, starting at position `start`. * Copying will stop once either the end of the current $coll
is reached, * or the end of the array is reached, or `len` elements have been copied. * * $willNotTerminateInf * * @param xs the array to fill. * @param start
the starting index. * @param len the maximal number of elements to copy. * @tparam B the type of the elements of the array. * * * @usecase def copyToArray(xs:
Array[A], start: Int, len: Int): Unit */ def copyToArray[B>: A](xs: Array[B], start: Int, len: Int) { var i = start val end = (start + len) min xs.length breakable { for (x
<- this) { if (i>= end) break xs(i) = x i += 1 } } } def toTraversable: Traversable[A] = thisCollection def toIterator: Iterator[A] = toStream.iterator def toStream: Stream[A]
= toBuffer.toStream /** Converts this $coll to a string. * * @return a string representation of this collection. By default this * string consists
of the `stringPrefix` of this $coll, * followed by all elements separated by commas and enclosed in parentheses. */ override def toString = mkString(stringPrefix
+ "(", ", ", ")") /** Defines the prefix of this object's `toString` representation. * * @return a string representation which starts the result of
`toString` * applied to this $coll. By default the string prefix is the * simple name of the collection class $coll. */ def stringPrefix : String =
{ var string = repr.asInstanceOf[AnyRef].getClass.getName val idx1 = string.lastIndexOf('.' : Int) if (idx1 != -1) string = string.substring(idx1 +
1) val idx2 = string.indexOf('$') if (idx2 != -1) string = string.substring(0, idx2) string } /** Creates a non-strict view of this $coll. * * @return
a non-strict view of this $coll. */ def view = new TraversableView[A, Repr] { protected lazy val underlying = self.repr override def foreach[U](f:
A => U) = self foreach f } /** Creates a non-strict view of a slice of this $coll. * * Note: the difference between `view` and `slice` is that `view`
produces * a view of the current $coll, whereas `slice` produces a new $coll. * * Note: `view(from, to)` is equivalent to `view.slice(from, to)` *
$orderDependent * * @param from the index of the first element of the view * @param until the index of the element following the view * @return a non-strict
view of a slice of this $coll, starting at index `from` * and extending up to (but not including) index `until`. */ def view(from: Int, until: Int):
TraversableView[A, Repr] = view.slice(from, until) /** Creates a non-strict filter of this $coll. * * Note: the difference between `c filter p` and
`c withFilter p` is that * the former creates a new collection, whereas the latter only * restricts the domain of subsequent `map`, `flatMap`, `foreach`,
* and `withFilter` operations. * $orderDependent * * @param p the predicate used to test elements. * @return an object of class `WithFilter`, which
supports * `map`, `flatMap`, `foreach`, and `withFilter` operations. * All these operations apply to those elements of this $coll which * satisfy the
predicate `p`. */ def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p) /** A class supporting filtered operations. Instances
of this class are * returned by method `withFilter`. */ class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] { /** Builds a new collection
by applying a function to all elements of the * outer $coll containing this `WithFilter` instance that satisfy predicate `p`. * * @param f the function
to apply to each element. * @tparam B the element type of the returned collection. * @tparam That $thatinfo * @param bf $bfinfo * @return a new collection
of type `That` resulting from applying * the given function `f` to each element of the outer $coll * that satisfies predicate `p` and collecting the
results. * * @usecase def map[B](f: A => B): $Coll[B] * * @return a new $coll resulting from applying the given function * `f` to each element of the
outer $coll that satisfies * predicate `p` and collecting the results. */ def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
= { val b = bf(repr) for (x
<- self) if (p(x)) b +=f (x) b.result } /** Builds a new collection by applying a function to all elements of the * outer
$coll containing this `WithFilter` instance that satisfy * predicate `p` and concatenating the results. * * @param f the function to apply to each
element. * @tparam B the element type of the returned collection. * @tparam That $thatinfo * @param bf $bfinfo * @return a new collection of type `That`
resulting from applying * the given collection-valued function `f` to each element * of the outer $coll that satisfies predicate `p` and * concatenating
the results. * * @usecase def flatMap[B](f: A=> TraversableOnce[B]): $Coll[B] * * @return a new $coll resulting from applying the given collection-valued function * `f` to each element of the outer
$coll that satisfies predicate `p` and concatenating the results. */ def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr,
B, That]): That = { val b = bf(repr) for (x
<- self) if (p(x)) b ++=f (x).seq b.result } /** Applies a function `f` to all elements of the outer
$coll containing * this `WithFilter` instance that satisfy predicate `p`. * * @param f the function that is applied for its side-effect to every
element. * The result of function `f` is discarded. * * @tparam U the type parameter describing the result of function `f`. * This result will
always be ignored. Typically `U` is `Unit`, * but this is not necessary. * * @usecase def foreach(f: A=> Unit): Unit */ def foreach[U](f: A => U): Unit = for (x
<- self) if (p(x)) f(x) /** Further refines the filter for this $coll. * * @param q the
predicate used to test elements. * @return an object of class `WithFilter`, which supports * `map`, `flatMap`, `foreach`, and `withFilter`
operations. * All these operations apply to those elements of this $coll which * satisfy the predicate `q` in addition to the predicate `p`.
*/ def withFilter(q: A=> Boolean): WithFilter = new WithFilter(x => p(x) && q(x)) } // A helper for tails and inits. private def iterateUntilEmpty(f: Traversable[A
@uV] => Traversable[A @uV]): Iterator[Repr] = { val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty) it ++ Iterator(Nil)
map (newBuilder ++= _ result) } } </textarea>
</form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"),
{
lineNumbers: true,
matchBrackets: true,
theme: "ambiance",
mode: "text/x-scala"
});
</script>
</article>

View file

@ -0,0 +1,33 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-c");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
MT("indent",
"[variable-3 void] [def foo]([variable-3 void*] [variable a], [variable-3 int] [variable b]) {",
" [variable-3 int] [variable c] [operator =] [variable b] [operator +]",
" [number 1];",
" [keyword return] [operator *][variable a];",
"}");
MT("indent_switch",
"[keyword switch] ([variable x]) {",
" [keyword case] [number 10]:",
" [keyword return] [number 20];",
" [keyword default]:",
" [variable printf]([string \"foo %c\"], [variable x]);",
"}");
MT("def",
"[variable-3 void] [def foo]() {}",
"[keyword struct] [def bar]{}",
"[variable-3 int] [variable-3 *][def baz]() {}");
MT("double_block",
"[keyword for] (;;)",
" [keyword for] (;;)",
" [variable x][operator ++];",
"[keyword return];");
})();