「
Mery 電卓
」を編集中
2025年3月18日 (火) 10:27時点における
Yuko
(
トーク
|
投稿記録
)
による版
(
→
ソースコード
)
(
差分
)
← 古い版
|
最新版
(
差分
) |
新しい版 →
(
差分
)
ナビゲーションに移動
検索に移動
警告: このページの古い版を編集しています。
公開すると、この版以降になされた変更がすべて失われます。
警告:
ログインしていません。編集を行うと、あなたの IP アドレスが公開されます。
ログイン
または
アカウントを作成
すれば、あなたの編集はその利用者名とともに表示されるほか、さまざまなメリットもあります。
スパム攻撃防止用のチェックです。 決して、ここには、値の入力は
しない
でください!
== 概要 == 「Mery 電卓」は、Meryエディタ上で数式を計算するためのマクロです。標準的な数学関数をサポートしており、カーソル位置の行または選択したテキストを数式として解釈し、結果を表示します。計算結果は自動的にクリップボードにコピーされ、カンマ区切りの数値として表示されます。 本マクロをショートカットキーに設定し、いつでも起動できるようにしておくと日常シーンで何かと便利です。作者は「Ctrl + Alt + Enter」キーに割り当てて利用しています。 == 注意事項 == * Mery Ver 3.7.12 で動作確認しています。 == 使い方 == 1. '''行全体を計算する場合''': * 計算したい数式が書かれた行にカーソルを置きます。 * マクロを実行すると、次の行に「= 計算結果」が表示されます。 * 既に結果行がある場合は、その行が更新されます。 2. '''選択範囲を計算する場合''': * 計算したい数式部分を選択します。 * マクロを実行すると、選択範囲の後ろに「計算式 = 計算結果」が挿入されます。 3. '''サポートされている演算子''': * 四則演算(+, -, *, /) * べき乗(^) * 剰余(%) * 比較演算子(<, >, <=, >=, ==, !=) * 論理演算子(and, or, not) 4. '''サポートされている関数''': * 三角関数(sin, cos, tan, asin, acos, atan) * 双曲線関数(sinh, cosh, tanh, asinh, acosh, atanh) * 対数関数(log, log10, log2, ln) * その他の数学関数(sqrt, cbrt, abs, ceil, floor, round, trunc など) 5. '''特別な機能''': * カンマ区切り表示: 計算結果は読みやすいようにカンマ区切りで表示されます。変数「COMMA」を設定することで調整可能です。 * 自動コピー: 計算結果は自動的にクリップボードにコピーされます。変数「COPY」を設定することで調整可能です。 * 計算結果の再利用: 行頭の「= 」は入力から無視されるため、計算結果の位置からスムーズに次の数式として利用できます。 * 変数の利用: 複数行、または「;」で区切ることで、変数を使った数式が利用できます。変数形式は「$[a-zA-Z][a-zA-Z0-9]*」に対応しています。例えば「$a = 2; $a * 3」として実行すると、結果は「6」と出力されます。 * メモ書きから計算: 数字や関数以外の文字はできるだけ除外した上で計算をします。例えば「月100円 * 12ヶ月」のようなメモ書きに対して実行すると「1,200」と出力されます。 [ と ] で囲まれた文字列は丸ごと除外するため、コメントに最適です。 == ソースコード == <syntaxhighlight lang="javascript"> #title = "Mery 電卓" #include "Common.js" #language = "v8" Redraw = false; BeginUndoGroup(); // 結果をクリップボードにコピー var COPY = true; // 出力結果をカンマ区切りにする var COMMA = true; // expr-eval ライブラリ // from: https://cdn.jsdelivr.net/npm/expr-eval@2.0.2/dist/bundle.min.js !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).exprEval={})}(this,function(t){"use strict";var y="INUMBER",x="IOP1",w="IOP2",d="IOP3",g="IVAR",M="IVARNAME",E="IFUNCALL",m="IFUNDEF",A="IEXPR",b="IEXPREVAL",k="IMEMBER",O="IENDSTATEMENT",T="IARRAY";function C(t,e){this.type=t,this.value=null!=e?e:0}function c(t){return new C(x,t)}function f(t){return new C(w,t)}function l(t){return new C(d,t)}function N(t,i,o){var e,r,s,n,a,p,h=[];if(I(t))return P(t,o);for(var u=t.length,c=0;c<u;c++){var f=t[c],l=f.type;if(l===y||l===M)h.push(f.value);else if(l===w)r=h.pop(),e=h.pop(),"and"===f.value?h.push(!!e&&!!N(r,i,o)):"or"===f.value?h.push(!!e||!!N(r,i,o)):"="===f.value?(n=i.binaryOps[f.value],h.push(n(e,N(r,i,o),o))):(n=i.binaryOps[f.value],h.push(n(P(e,o),P(r,o))));else if(l===d)s=h.pop(),r=h.pop(),e=h.pop(),"?"===f.value?h.push(N(e?r:s,i,o)):(n=i.ternaryOps[f.value],h.push(n(P(e,o),P(r,o),P(s,o))));else if(l===g)if(f.value in i.functions)h.push(i.functions[f.value]);else if(f.value in i.unaryOps&&i.parser.isOperatorEnabled(f.value))h.push(i.unaryOps[f.value]);else{var v=o[f.value];if(void 0===v)throw new Error("undefined variable: "+f.value);h.push(v)}else if(l===x)e=h.pop(),n=i.unaryOps[f.value],h.push(n(P(e,o)));else if(l===E){for(p=f.value,a=[];0<p--;)a.unshift(P(h.pop(),o));if(!(n=h.pop()).apply||!n.call)throw new Error(n+" is not a function");h.push(n.apply(void 0,a))}else if(l===m)h.push(function(){for(var s=h.pop(),n=[],t=f.value;0<t--;)n.unshift(h.pop());function e(){for(var t=Object.assign({},o),e=0,r=n.length;e<r;e++)t[n[e]]=arguments[e];return N(s,i,t)}var r=h.pop();return Object.defineProperty(e,"name",{value:r,writable:!1}),o[r]=e}());else if(l===A)h.push(S(f,i));else if(l===b)h.push(f);else if(l===k)e=h.pop(),h.push(e[f.value]);else if(l===O)h.pop();else{if(l!==T)throw new Error("invalid Expression");for(p=f.value,a=[];0<p--;)a.unshift(h.pop());h.push(a)}}if(1<h.length)throw new Error("invalid Expression (parity)");return 0===h[0]?0:P(h[0],o)}function S(e,r){return I(e)?e:{type:b,value:function(t){return N(e.value,r,t)}}}function I(t){return t&&t.type===b}function P(t,e){return I(t)?t.value(e):t}function v(t,e){for(var r,s,n,i,o,a,p=[],h=0;h<t.length;h++){var u=t[h],c=u.type;if(c===y)"number"==typeof u.value&&u.value<0?p.push("("+u.value+")"):Array.isArray(u.value)?p.push("["+u.value.map(F).join(", ")+"]"):p.push(F(u.value));else if(c===w)s=p.pop(),r=p.pop(),i=u.value,e?"^"===i?p.push("Math.pow("+r+", "+s+")"):"and"===i?p.push("(!!"+r+" && !!"+s+")"):"or"===i?p.push("(!!"+r+" || !!"+s+")"):"||"===i?p.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+s+")))"):"=="===i?p.push("("+r+" === "+s+")"):"!="===i?p.push("("+r+" !== "+s+")"):"["===i?p.push(r+"[("+s+") | 0]"):p.push("("+r+" "+i+" "+s+")"):"["===i?p.push(r+"["+s+"]"):p.push("("+r+" "+i+" "+s+")");else if(c===d){if(n=p.pop(),s=p.pop(),r=p.pop(),"?"!==(i=u.value))throw new Error("invalid Expression");p.push("("+r+" ? "+s+" : "+n+")")}else if(c===g||c===M)p.push(u.value);else if(c===x)r=p.pop(),"-"===(i=u.value)||"+"===i?p.push("("+i+r+")"):e?"not"===i?p.push("(!"+r+")"):"!"===i?p.push("fac("+r+")"):p.push(i+"("+r+")"):"!"===i?p.push("("+r+"!)"):p.push("("+i+" "+r+")");else if(c===E){for(a=u.value,o=[];0<a--;)o.unshift(p.pop());i=p.pop(),p.push(i+"("+o.join(", ")+")")}else if(c===m){for(s=p.pop(),a=u.value,o=[];0<a--;)o.unshift(p.pop());r=p.pop(),e?p.push("("+r+" = function("+o.join(", ")+") { return "+s+" })"):p.push("("+r+"("+o.join(", ")+") = "+s+")")}else if(c===k)r=p.pop(),p.push(r+"."+u.value);else if(c===T){for(a=u.value,o=[];0<a--;)o.unshift(p.pop());p.push("["+o.join(", ")+"]")}else if(c===A)p.push("("+v(u.value,e)+")");else if(c!==O)throw new Error("invalid Expression")}return 1<p.length&&(p=e?[p.join(",")]:[p.join(";")]),String(p[0])}function F(t){return"string"==typeof t?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function a(t,e){for(var r=0;r<t.length;r++)if(t[r]===e)return!0;return!1}function p(t,e,r){for(var s=!!(r=r||{}).withMembers,n=null,i=0;i<t.length;i++){var o=t[i];o.type===g||o.type===M?s||a(e,o.value)?n=(null!==n&&(a(e,n)||e.push(n)),o.value):e.push(o.value):o.type===k&&s&&null!==n?n+="."+o.value:o.type===A?p(o.value,e,r):null!==n&&(a(e,n)||e.push(n),n=null)}null===n||a(e,n)||e.push(n)}function s(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}C.prototype.toString=function(){switch(this.type){case y:case x:case w:case d:case g:case M:case O:return this.value;case E:return"CALL "+this.value;case m:return"DEF "+this.value;case T:return"ARRAY "+this.value;case k:return"."+this.value;default:return"Invalid Instruction"}},s.prototype.simplify=function(t){return t=t||{},new s(function t(e,r,s,n,i){for(var o,a,p,h,u=[],c=[],f=0;f<e.length;f++){var l=e[f],v=l.type;if(v===y||v===M)Array.isArray(l.value)?u.push.apply(u,t(l.value.map(function(t){return new C(y,t)}).concat(new C(T,l.value.length)),r,s,n,i)):u.push(l);else if(v===g&&i.hasOwnProperty(l.value))l=new C(y,i[l.value]),u.push(l);else if(v===w&&1<u.length)a=u.pop(),o=u.pop(),h=s[l.value],l=new C(y,h(o.value,a.value)),u.push(l);else if(v===d&&2<u.length)p=u.pop(),a=u.pop(),o=u.pop(),"?"===l.value?u.push(o.value?a.value:p.value):(h=n[l.value],l=new C(y,h(o.value,a.value,p.value)),u.push(l));else if(v===x&&0<u.length)o=u.pop(),h=r[l.value],l=new C(y,h(o.value)),u.push(l);else if(v===A){for(;0<u.length;)c.push(u.shift());c.push(new C(A,t(l.value,r,s,n,i)))}else if(v===k&&0<u.length)o=u.pop(),u.push(new C(y,o.value[l.value]));else{for(;0<u.length;)c.push(u.shift());c.push(l)}}for(;0<u.length;)c.push(u.shift());return c}(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)},s.prototype.substitute=function(t,e){return e instanceof s||(e=this.parser.parse(String(e))),new s(function t(e,r,s){for(var n=[],i=0;i<e.length;i++){var o=e[i],a=o.type;if(a===g&&o.value===r)for(var p=0;p<s.tokens.length;p++){var h,u=s.tokens[p];h=u.type===x?c(u.value):u.type===w?f(u.value):u.type===d?l(u.value):new C(u.type,u.value),n.push(h)}else a===A?n.push(new C(A,t(o.value,r,s))):n.push(o)}return n}(this.tokens,t,e),this.parser)},s.prototype.evaluate=function(t){return t=t||{},N(this.tokens,this,t)},s.prototype.toString=function(){return v(this.tokens,!1)},s.prototype.symbols=function(t){t=t||{};var e=[];return p(this.tokens,e,t),e},s.prototype.variables=function(t){t=t||{};var e=[];p(this.tokens,e,t);var r=this.functions;return e.filter(function(t){return!(t in r)})},s.prototype.toJSFunction=function(t,e){var r=this,s=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+v(this.simplify(e).tokens,!0)+"; }");return function(){return s.apply(r,arguments)}};var n="TEOF",h="TOP",u="TNUMBER",i="TSTRING",o="TPAREN",R="TBRACKET",L="TCOMMA",j="TNAME",U="TSEMICOLON";function q(t,e,r){this.type=t,this.value=e,this.index=r}function B(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}q.prototype.toString=function(){return this.type+": "+this.value},B.prototype.newToken=function(t,e,r){return new q(t,e,null!=r?r:this.pos)},B.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current},B.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent},B.prototype.next=function(){return this.pos>=this.expression.length?this.newToken(n,"EOF"):this.isWhitespace()||this.isComment()?this.next():this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName()?this.current:void this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')},B.prototype.isString=function(){var t=!1,e=this.pos,r=this.expression.charAt(e);if("'"===r||'"'===r)for(var s=this.expression.indexOf(r,e+1);0<=s&&this.pos<this.expression.length;){if(this.pos=s+1,"\\"!==this.expression.charAt(s-1)){var n=this.expression.substring(e+1,s);this.current=this.newToken(i,this.unescape(n),e),t=!0;break}s=this.expression.indexOf(r,s+1)}return t},B.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return("("===t||")"===t)&&(this.current=this.newToken(o,t),this.pos++,!0)},B.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return!("["!==t&&"]"!==t||!this.isOperatorEnabled("["))&&(this.current=this.newToken(R,t),this.pos++,!0)},B.prototype.isComma=function(){return","===this.expression.charAt(this.pos)&&(this.current=this.newToken(L,","),this.pos++,!0)},B.prototype.isSemicolon=function(){return";"===this.expression.charAt(this.pos)&&(this.current=this.newToken(U,";"),this.pos++,!0)},B.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()&&(e===this.pos||"_"!==r&&"."!==r&&(r<"0"||"9"<r)))break}if(t<e){var s=this.expression.substring(t,e);if(s in this.consts)return this.current=this.newToken(u,this.consts[s]),this.pos+=s.length,!0}return!1},B.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()&&(e===this.pos||"_"!==r&&(r<"0"||"9"<r)))break}if(t<e){var s=this.expression.substring(t,e);if(this.isOperatorEnabled(s)&&(s in this.binaryOps||s in this.unaryOps||s in this.ternaryOps))return this.current=this.newToken(h,s),this.pos+=s.length,!0}return!1},B.prototype.isName=function(){for(var t=this.pos,e=t,r=!1;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()){if(e===this.pos&&("$"===s||"_"===s)){"_"===s&&(r=!0);continue}if(e===this.pos||!r||"_"!==s&&(s<"0"||"9"<s))break}else r=!0}if(r){var n=this.expression.substring(t,e);return this.current=this.newToken(j,n),this.pos+=n.length,!0}return!1},B.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);!(" "!==e&&"\t"!==e&&"\n"!==e&&"\r"!==e||(t=!0,this.pos++,this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var V=/^[0-9a-f]{4}$/i;function _(t,e,r){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=!1!==r.allowMemberAccess}B.prototype.unescape=function(t){var e=t.indexOf("\\");if(e<0)return t;for(var r=t.substring(0,e);0<=e;){var s=t.charAt(++e);switch(s){case"'":r+="'";break;case'"':r+='"';break;case"\\":r+="\\";break;case"/":r+="/";break;case"b":r+="\b";break;case"f":r+="\f";break;case"n":r+="\n";break;case"r":r+="\r";break;case"t":r+="\t";break;case"u":var n=t.substring(e+1,e+5);V.test(n)||this.parseError("Illegal escape sequence: \\u"+n),r+=String.fromCharCode(parseInt(n,16)),e+=4;break;default:throw this.parseError('Illegal escape sequence: "\\'+s+'"')}++e;var i=t.indexOf("\\",e);r+=t.substring(e,i<0?t.length:i),e=i}return r},B.prototype.isComment=function(){return"/"===this.expression.charAt(this.pos)&&"*"===this.expression.charAt(this.pos+1)&&(this.pos=this.expression.indexOf("*/",this.pos)+2,1===this.pos&&(this.pos=this.expression.length),!0)},B.prototype.isRadixInteger=function(){var t,e,r=this.pos;if(r>=this.expression.length-2||"0"!==this.expression.charAt(r))return!1;if(++r,"x"===this.expression.charAt(r))t=16,e=/^[0-9a-f]$/i,++r;else{if("b"!==this.expression.charAt(r))return!1;t=2,e=/^[01]$/i,++r}for(var s=!1,n=r;r<this.expression.length;){var i=this.expression.charAt(r);if(!e.test(i))break;r++,s=!0}return s&&(this.current=this.newToken(u,parseInt(this.expression.substring(n,r),t)),this.pos=r),s},B.prototype.isNumber=function(){for(var t,e=!1,r=this.pos,s=r,n=r,i=!1,o=!1;r<this.expression.length&&("0"<=(t=this.expression.charAt(r))&&t<="9"||!i&&"."===t);)"."===t?i=!0:o=!0,r++,e=o;if(e&&(n=r),"e"===t||"E"===t){r++;for(var a=!0,p=!1;r<this.expression.length;){if(t=this.expression.charAt(r),!a||"+"!==t&&"-"!==t){if(!("0"<=t&&t<="9"))break;a=!(p=!0)}else a=!1;r++}p||(r=n)}return e?(this.current=this.newToken(u,parseFloat(this.expression.substring(s,r))),this.pos=r):this.pos=n,e},B.prototype.isOperator=function(){var t=this.pos,e=this.expression.charAt(this.pos);if("+"===e||"-"===e||"*"===e||"/"===e||"%"===e||"^"===e||"?"===e||":"===e||"."===e)this.current=this.newToken(h,e);else if("∙"===e||"•"===e)this.current=this.newToken(h,"*");else if(">"===e)"="===this.expression.charAt(this.pos+1)?(this.current=this.newToken(h,">="),this.pos++):this.current=this.newToken(h,">");else if("<"===e)"="===this.expression.charAt(this.pos+1)?(this.current=this.newToken(h,"<="),this.pos++):this.current=this.newToken(h,"<");else if("|"===e){if("|"!==this.expression.charAt(this.pos+1))return!1;this.current=this.newToken(h,"||"),this.pos++}else if("="===e)"="===this.expression.charAt(this.pos+1)?(this.current=this.newToken(h,"=="),this.pos++):this.current=this.newToken(h,e);else{if("!"!==e)return!1;"="===this.expression.charAt(this.pos+1)?(this.current=this.newToken(h,"!="),this.pos++):this.current=this.newToken(h,e)}return this.pos++,!!this.isOperatorEnabled(this.current.value)||(this.pos=t,!1)},B.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)},B.prototype.getCoordinates=function(){for(var t,e=0,r=-1;e++,t=this.pos-r,0<=(r=this.expression.indexOf("\n",r+1))&&r<this.pos;);return{line:e,column:t}},B.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)},_.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()},_.prototype.tokenMatches=function(t,e){return void 0===e||(Array.isArray(e)?a(e,t.value):"function"==typeof e?e(t):t.value===e)},_.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()},_.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken},_.prototype.accept=function(t,e){return!(this.nextToken.type!==t||!this.tokenMatches(this.nextToken,e))&&(this.next(),!0)},_.prototype.expect=function(t,e){if(!this.accept(t,e)){var r=this.tokens.getCoordinates();throw new Error("parse error ["+r.line+":"+r.column+"]: Expected "+(e||t))}},_.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;if(this.accept(j)||this.accept(h,function(t){return t.value in e}))t.push(new C(g,this.current.value));else if(this.accept(u))t.push(new C(y,this.current.value));else if(this.accept(i))t.push(new C(y,this.current.value));else if(this.accept(o,"("))this.parseExpression(t),this.expect(o,")");else{if(!this.accept(R,"["))throw new Error("unexpected "+this.nextToken);if(this.accept(R,"]"))t.push(new C(T,0));else{var r=this.parseArrayList(t);t.push(new C(T,r))}}},_.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),this.parseUntilEndStatement(t,e)||this.pushExpression(t,e))},_.prototype.pushExpression=function(t,e){for(var r=0,s=e.length;r<s;r++)t.push(e[r])},_.prototype.parseUntilEndStatement=function(t,e){return!!this.accept(U)&&(!this.nextToken||this.nextToken.type===n||this.nextToken.type===o&&")"===this.nextToken.value||e.push(new C(O)),this.nextToken.type!==n&&this.parseExpression(e),t.push(new C(A,e)),!0)},_.prototype.parseArrayList=function(t){for(var e=0;!this.accept(R,"]");)for(this.parseExpression(t),++e;this.accept(L);)this.parseExpression(t),++e;return e},_.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(h,"=");){var e=t.pop(),r=[],s=t.length-1;if(e.type!==E){if(e.type!==g&&e.type!==k)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(r),t.push(new C(M,e.value)),t.push(new C(A,r)),t.push(f("="))}else{if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var n=0,i=e.value+1;n<i;n++){var o=s-n;t[o].type===g&&(t[o]=new C(M,t[o].value))}this.parseVariableAssignmentExpression(r),t.push(new C(A,r)),t.push(new C(m,e.value))}}},_.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(h,"?");){var e=[],r=[];this.parseConditionalExpression(e),this.expect(h,":"),this.parseConditionalExpression(r),t.push(new C(A,e)),t.push(new C(A,r)),t.push(l("?"))}},_.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(h,"or");){var e=[];this.parseAndExpression(e),t.push(new C(A,e)),t.push(f("or"))}},_.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(h,"and");){var e=[];this.parseComparison(e),t.push(new C(A,e)),t.push(f("and"))}};var r=["==","!=","<","<=",">=",">","in"];_.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(h,r);){var e=this.current;this.parseAddSub(t),t.push(f(e.value))}};var $=["+","-","||"];_.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(h,$);){var e=this.current;this.parseTerm(t),t.push(f(e.value))}};var D=["*","/","%"];function e(t,e){return Number(t)+Number(e)}function G(t,e){return t-e}function J(t,e){return t*e}function W(t,e){return t/e}function X(t,e){return t%e}function Y(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function K(t,e){return t===e}function z(t,e){return t!==e}function H(t,e){return e<t}function Q(t,e){return t<e}function Z(t,e){return e<=t}function tt(t,e){return t<=e}function et(t,e){return Boolean(t&&e)}function rt(t,e){return Boolean(t||e)}function st(t,e){return a(e,t)}function nt(t){return(Math.exp(t)-Math.exp(-t))/2}function it(t){return(Math.exp(t)+Math.exp(-t))/2}function ot(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function at(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function pt(t){return Math.log(t+Math.sqrt(t*t-1))}function ht(t){return Math.log((1+t)/(1-t))/2}function ut(t){return Math.log(t)*Math.LOG10E}function ct(t){return-t}function ft(t){return!t}function lt(t){return t<0?Math.ceil(t):Math.floor(t)}function vt(t){return Math.random()*(t||1)}function yt(t){return dt(t+1)}_.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(h,D);){var e=this.current;this.parseFactor(t),t.push(f(e.value))}},_.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;if(this.save(),this.accept(h,function(t){return t.value in e})){if("-"!==this.current.value&&"+"!==this.current.value){if(this.nextToken.type===o&&"("===this.nextToken.value)return this.restore(),void this.parseExponential(t);if(this.nextToken.type===U||this.nextToken.type===L||this.nextToken.type===n||this.nextToken.type===o&&")"===this.nextToken.value)return this.restore(),void this.parseAtom(t)}var r=this.current;this.parseFactor(t),t.push(c(r.value))}else this.parseExponential(t)},_.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(h,"^");)this.parseFactor(t),t.push(f("^"))},_.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(h,"!");)t.push(c("!"))},_.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;if(this.accept(h,function(t){return t.value in e})){var r=this.current;this.parseAtom(t),t.push(c(r.value))}else for(this.parseMemberExpression(t);this.accept(o,"(");)if(this.accept(o,")"))t.push(new C(E,0));else{var s=this.parseArgumentList(t);t.push(new C(E,s))}},_.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(o,")");)for(this.parseExpression(t),++e;this.accept(L);)this.parseExpression(t),++e;return e},_.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(h,".")||this.accept(R,"[");){var e=this.current;if("."===e.value){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(j),t.push(new C(k,this.current.value))}else{if("["!==e.value)throw new Error("unexpected symbol: "+e.value);if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(R,"]"),t.push(f("["))}}};var xt=4.7421875,wt=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function dt(t){var e,r;if(function(t){return isFinite(t)&&t===Math.round(t)}(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(171<t)return 1/0;for(var s=t-2,n=t-1;1<s;)n*=s,s--;return 0===n&&(n=1),n}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*dt(1-t));if(171.35<=t)return 1/0;if(85<t){var i=t*t,o=i*t,a=o*t,p=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*i)-139/(51840*o)-571/(2488320*a)+163879/(209018880*p)+5246819/(75246796800*p*t))}--t,r=wt[0];for(var h=1;h<wt.length;++h)r+=wt[h]/(t+h);return e=t+xt+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*r}function gt(t){return Array.isArray(t)?t.length:String(t).length}function Mt(){for(var t=0,e=0,r=0;r<arguments.length;r++){var s,n=Math.abs(arguments[r]);e<n?(t=t*(s=e/n)*s+1,e=n):t+=0<n?(s=n/e)*s:n}return e===1/0?1/0:e*Math.sqrt(t)}function Et(t,e,r){return t?e:r}function mt(t,e){return void 0===e||0==+e?Math.round(t):(t=+t,e=-+e,isNaN(t)||"number"!=typeof e||e%1!=0?NaN:(t=t.toString().split("e"),+((t=(t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e)))).toString().split("e"))[0]+"e"+(t[1]?+t[1]+e:e))))}function At(t,e,r){return r&&(r[t]=e),e}function bt(t,e){return t[0|e]}function kt(t){return 1===arguments.length&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function Ot(t){return 1===arguments.length&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function Tt(r,t){if("function"!=typeof r)throw new Error("First argument to map is not a function");if(!Array.isArray(t))throw new Error("Second argument to map is not an array");return t.map(function(t,e){return r(t,e)})}function Ct(s,t,e){if("function"!=typeof s)throw new Error("First argument to fold is not a function");if(!Array.isArray(e))throw new Error("Second argument to fold is not an array");return e.reduce(function(t,e,r){return s(t,e,r)},t)}function Nt(r,t){if("function"!=typeof r)throw new Error("First argument to filter is not a function");if(!Array.isArray(t))throw new Error("Second argument to filter is not an array");return t.filter(function(t,e){return r(t,e)})}function St(t,e){if(!Array.isArray(e)&&"string"!=typeof e)throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function It(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function Pt(t){return(0<t)-(t<0)||+t}var Ft=1/3;function Rt(t){return t<0?-Math.pow(-t,Ft):Math.pow(t,Ft)}function Lt(t){return Math.exp(t)-1}function jt(t){return Math.log(1+t)}function Ut(t){return Math.log(t)/Math.LN2}function qt(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||nt,cosh:Math.cosh||it,tanh:Math.tanh||ot,asinh:Math.asinh||at,acosh:Math.acosh||pt,atanh:Math.atanh||ht,sqrt:Math.sqrt,cbrt:Math.cbrt||Rt,log:Math.log,log2:Math.log2||Ut,ln:Math.log,lg:Math.log10||ut,log10:Math.log10||ut,expm1:Math.expm1||Lt,log1p:Math.log1p||jt,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||lt,"-":ct,"+":Number,exp:Math.exp,not:ft,length:gt,"!":yt,sign:Math.sign||Pt},this.binaryOps={"+":e,"-":G,"*":J,"/":W,"%":X,"^":Math.pow,"||":Y,"==":K,"!=":z,">":H,"<":Q,">=":Z,"<=":tt,and:et,or:rt,in:st,"=":At,"[":bt},this.ternaryOps={"?":Et},this.functions={random:vt,fac:yt,min:Ot,max:kt,hypot:Math.hypot||Mt,pyt:Math.hypot||Mt,pow:Math.pow,atan2:Math.atan2,if:Et,gamma:dt,roundTo:mt,map:Tt,fold:Ct,filter:Nt,indexOf:St,join:It},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}qt.prototype.parse=function(t){var e=[],r=new _(this,new B(this,t),{allowMemberAccess:this.options.allowMemberAccess});return r.parseExpression(e),r.expect(n,"EOF"),new s(e,this)},qt.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var Bt=new qt;qt.parse=function(t){return Bt.parse(t)},qt.evaluate=function(t,e){return Bt.parse(t).evaluate(e)};var Vt={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};qt.prototype.isOperatorEnabled=function(t){var e=function(t){return Vt.hasOwnProperty(t)?Vt[t]:t}(t),r=this.options.operators||{};return!(e in r&&!r[e])};var _t={Parser:qt,Expression:s};t.Expression=s,t.Parser=qt,t.default=_t,Object.defineProperty(t,"__esModule",{value:!0})}); /** * 数式に数学関数以外の関数が含まれている場合のエラー */ class MathFunctionError extends Error { /** * @param {string} message - エラーメッセージ */ constructor(message) { super(message || "数学関数以外の関数が含まれています"); this.name = "MathFunctionError"; } } var sel = document.selection; doMultiEdit(main); function main() { var isEmpty = sel.IsEmpty; var activePointY = sel.GetActivePointY(mePosLogical); if (isEmpty) { var exp = document.GetLine(activePointY); } else { var exp = sel.Text; } // 空白行の場合は何もしない if (exp.match(/^\s*$/)) { return; } try { var exp_replaced = replaceExpression(exp); const Parser = exprEval.Parser; let r = Parser.evaluate(exp_replaced); try { r = r.toFixed(15); const intPart = r.match(/([0-9]+)\./); const fractionalPart = r.match(/\.([0-9]+$)/); if (intPart && fractionalPart) { // 小数点以下は12桁で切る const f = fractionalPart[1].slice(0,12).replace(/[0]+$/, "") r = intPart[1] + (f ? `.${f}` : ""); } } catch(e) {} var result_str = String(r); } catch (e) { if (e instanceof MathFunctionError) { alert(e.message) } else { alert(e + "\n入力: " + exp + "\n入力変換後: " + exp_replaced) } return; } // 小数点以上のみカンマ区切り if (COMMA) { var result_parts = result_str.split("."); result_parts[0] = result_parts[0].replace(/(\d)(?=(\d{3})+$)/g, "$1,"); if (result_parts.length > 1) { result_str = result_parts.join("."); } else { result_str = result_parts[0]; } } // 計算行が = 始まりの場合、= を削除する if (isEmpty && exp.match(/^= /)) { sel.SetActivePoint(mePosLogical, 1, activePointY, false); sel.EndOfLine(true, mePosLogical); sel.Text = sel.Text.replace(/^= /, ""); } // 既存の計算結果を上書きするか判定 var pattern = /^=\s*(-?[0-9.,]|true|false)*\s*$/; var nextLine = document.GetLine(activePointY + 1); if (isEmpty && nextLine.match(pattern)) { sel.SetActivePoint(mePosLogical, 1, activePointY + 1, false); sel.EndOfLine(true, mePosLogical); sel.Text = '= ' + result_str } else if (isEmpty) { sel.LineOpen(); sel.Text = '= ' + result_str } else { sel.CharRight(); const inputExp = exp.replace(/((?!;)\n)/mg, "; ").replace(/;\s*;/g, ";").replace(/ /g, " ").replace(/;\s*$/, "").trim(); if (exp.slice(-1) === "\n") { sel.Text = inputExp + ' = ' + result_str + '\n'; } else { sel.Text = '\n' + inputExp + ' = ' + result_str + '\n'; } sel.CharLeft(); } if (COPY) { ClipboardData.SetData(result_str); Status = "計算結果 " + result_str + " をコピーしました" } } /** * 数式を置換する */ function replaceExpression(exp) { const exp_replaced = exp.trim() // 先頭の = を削除 .replace(/^= /, "") // 改行を ; に置換 .replace(/(?<!;)\n/mg, ";") // 非ASCII文字を削除 .replace(/[^\x20-\x7e]/g, " ") // 全角スペースを半角スペースに変換 .replace(/ /g, " ") // 数字内のカンマを取り除く .replace(/(\d),(?! )/g, "$1") // 予約語を退避 .replace(/(?:^|\s)(PI|true|false)(?:$|\s)/g, " %%%$1%%% ") // 指数形式を退避 .replace(/([0-9]+(?:\.[0-9]+)?[eE][0-9]+)/g, " %%%$1%%% ") // 変数形式を退避 .replace(/\$([a-zA-Z][a-zA-Z0-9]*)/g, " %%%$1%%% ") // `/hour` などの文字列はスラッシュごと削除 .replace(/\/\s*[a-zA-Z\u0080-\uFFFF]/g, " ") // 不要な括弧書きを削除 .replace(/\[[^\]]*\]/g, " ") // その他の文字を削除。退避文字と関数の可能性がある abc( 形式は削除しない .replace(/[^0-9.+\-*/%^=()<>!;\s]+(?![a-zA-Z0-9]*%%% |[a-z0-9]*\s*\([^)])/g, " ") // 退避文字を復元 .replace(/ %%%([a-zA-Z][a-zA-Z0-9]*)%%% /g, "$1") // 数式が数学関数以外を含む場合はエラー if (containsNotMathFunction(exp_replaced)) { throw new MathFunctionError("数式に数学関数以外の関数が含まれています\n入力: " + exp + "\n入力変換後: " + exp_replaced); } return exp_replaced; } /** * 数学関数以外を含むかどうかを判定する * max(x, y, ...) のような複数の引数を受け取る関数もOK扱いにはするが、動作は保証しないものとする */ function containsNotMathFunction(exp) { var functions = [ "abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "cbrt", "ceil", "cos", "cosh", "exp", "expm1", "floor", "length", "ln", "log", "log10", "log2", "log1p", "not", "round", "sign", "sin", "sinh", "sqrt", "tan", "tanh", "trunc", "random", "fac", "min", "max", "hypot", "pyt", "pow", "atan2", "roundTo", "map", "fold", "filter", "indexOf", "join", "if", ] // 検査対象の文字列を取得 var match = exp.match(/([a-z][a-z0-9]+)\s*\(/g); if (!match) { return false; } // 検査対象の文字列が数学関数に含まれていない場合は true for (var i = 0; i < match.length; i++) { var func = match[i].replace(/\s*\(/, ""); if (functions.indexOf(func) == -1) { return true; } } // 検査対象の文字列が数学関数のみの場合は false return false; } </syntaxhighlight> == サードパーティライブラリ == [https://github.com/silentmatt/expr-eval/ expr-eval]
編集内容の要約:
MeryWikiへの投稿はすべて、他の投稿者によって編集、変更、除去される場合があります。 自分が書いたものが他の人に容赦なく編集されるのを望まない場合は、ここに投稿しないでください。
また、投稿するのは、自分で書いたものか、パブリック ドメインまたはそれに類するフリーな資料からの複製であることを約束してください(詳細は
MeryWiki:著作権
を参照)。
著作権保護されている作品は、許諾なしに投稿しないでください!
このページを編集するには、下記の数式を計算してその答えを欄に入力してください (
ヘルプ
):
いちたすには =
キャンセル
編集ヘルプ
(新しいウィンドウで開きます)
スポンサーリンク
ナビゲーション メニュー
個人用ツール
ログインしていません
トーク
投稿記録
アカウント作成
ログイン
名前空間
ページ
議論
日本語
表示
閲覧
編集
履歴表示
その他
検索
スポンサーリンク
スポンサーリンク
案内
メインページ
ヘルプ
よくある質問
マクロリファレンス
マクロライブラリ
プラグインライブラリ
構文ファイル
テーマ
寄付・開発支援
練習用ページ
開発室
開発者のブログ
ツール
スポンサーリンク