prettify.js를 확장하여 Mathematica를 지원할 수 있습니까?
mathematica.SE는 비공개 베타 현재 몇 일에 공개됩니다. Stack Overflow 및 관련 사이트는 prettify.js를 사용 하지만 Mathematica는 지원되는 언어가 아닙니다. 우리 사이트에 대한 사용자 지정 강조 스크립트가 있으면 꽤 멋질 것입니다. 이러한 스크립트와 함께 제공되는 CSS를 개발하는 데 JavaScript 및 CSS 커뮤니티의 도움을 요청합니다.
Mathematica의 기본 강조 체계의 대부분의 기능을 캡처하는 몇 가지 기본 요구 사항을 아래에 나열했습니다 (내부 파서 만 알 수있는 항목 무시). 또한 일반적으로 색상 이름을 지정했습니다. 16 진수 색상 코드는 제가 제공 한 스크린 샷 (아래 참조)에서 선택할 수 있습니다. 또한 사람들이 테스트 할 수 있도록 스크린 샷과 함께 코드 샘플을 추가했습니다.
기본 요구 사항
주석
로 입력됩니다(* comment *)
. 따라서 이들 사이의 모든 것은 회색으로 강조 표시되어야합니다.문자열 (작은 따옴표는 지원되지 않음)
로 입력되며"string"
분홍색으로 강조 표시되어야합니다.연산자 / 속기 표기법
표준+, -, *, /, ^, ==
등을 제외하고 Mathematica에는 몇 가지 다른 연산자와 약자 표기법이 있습니다. 가장 일반적으로 발생하는 항목은 다음과 같습니다.@, @@, @@@, /@, //@, //, ~, /., //., ->, :>, /:, /;, :=, :^=, =., &, |, ||, &&, _, __, ___, ;;, [[, ]], <<, >>, ~~, <>
이것들과 괄호, 대괄호 및 중괄호는 모두 검은 색으로 강조 표시되어야합니다.
패턴 개체와 슬롯
패턴 객체는 문자로 시작하고이 중 하나_
또는__
또는___
예를 들어 같은 부착x_
,x__
및x___
. 밑줄 뒤에와 같이 추가 문자가있을 수도 있습니다x_abc
.이 모든 문자 는 녹색으로 강조 표시되어야합니다.구멍은 다음
#
과##
도 같은 정수가 될 수있다#1
,##4
등, 또한 녹색에 있어야한다.이 두 가지 (패턴 객체 및 슬롯)는 일반적으로 위의 3 번 지점에서 연산자 / 대괄호 / 짧은 형식으로 종료됩니다.
함수 / 변수
함수와 변수는 여기에서 다소 느슨한 용어이지만이 게시물의 목적을 위해 사용됩니다. 위의 4에 해당하지 않는 것은 검은 색으로 강조 표시 할 수 있습니다. Mathematica는 종종`
코드에서 백틱 을 사용 하며 함수 / 변수 이름의 일부로 간주되어야합니다. 예 :abcd`defg
.$
변수 이름의 달러 기호 는 문자처럼 취급해야합니다 (즉, 특별하지 않음).
위의 모든 항목에 대해 문자열 내부에 표시되는 경우 이와 같이 처리 "@~#
해야합니다. 즉, 분홍색으로 강조 표시해야합니다.
추가로 좋은 점 :
- 위의 3 번 항목의 패턴 개체에서 밑줄 뒤에 a가
?
있고 몇 개의 문자 가 나오면 다음 부분_
이 검은 색이어야합니다. 예를 들면,에서x__?abc
의x__
부분은 녹색으로에 있어야합니다?abc
검은 색이다. - 함수 / 변수가 대문자로 시작하면 검은 색으로 강조 표시됩니다. 소문자로 시작하면 파란색으로 강조 표시됩니다. 내부적으로 이것은 내장 함수와 사용자 정의 함수를 구별합니다. 그러나 mathematica 커뮤니티 (거의 모든 곳에서)는이 명명 규칙을 상당히 잘 고수하므로 둘을 구별하는 것이 어떤 목적에 부합합니다.
스크린 샷 및 코드 샘플 :
1. 간단한 예
다음은 Mathematica에서 어떻게 보이는지 마지막에 스크린 샷이있는 작은 예제 세트입니다.
(*simple pattern objects & operators*)
f[x_, y__] := x Times @@ y
(*pattern objects with chars at the end and strings*)
f[x_String] := x <> "hello@world"
(*pattern objects with ?xxx at the end*)
f[x_?MatrixQ] := x + Transpose@x
<< Combinatorica` (*example with backticks and inline comment*)
(*Slightly more complicated example with a mix of stuff*)
Developer`PartitionMap[Total, Range@1000, 3][[3 ;; -3]]~Partition~2 //
Times @@@ # &
2. 실제 사례
여기 에 내 대답의 예가 있는데, "추가로 좋은 것"섹션에서 내 요점 2를 나타냅니다. 즉, 소문자는 파란색으로 강조 표시됩니다.
또한 주황색으로 강조 표시된 일부 변수를 눈치 채 셨을 것입니다. Mathematica를 알고있는 파서 없이는 수행하기가 훨씬 더 어려울 것이라고 생각하기 때문에 일부러이를 요구 사항으로 포함하지 않았습니다.
prob = MapIndexed[#1/#2 &,
Accumulate[
EuclideanDistance[{0, 0}, #] < 1 & /@ arrows // Boole]]~N~4;
Manipulate[
Graphics[{White, Rectangle[{-5, -5}, {5, 5}], Red, Disk[{0, 0}, 1],
Black, Point[arrows[[;; i]]],
Text[Style[First@prob[[i]], Bold, 18, "Helvetica"], {-4.5, 4.5}]},
ImageSize -> 200], {i, Range[2, 20000, 1]},
ControlType -> Manipulator, SaveDefinitions -> True]
이것이 가능합니까? 너무 많이? 너무 열심히? 불가능한?
솔직히, 나는 그 어떤 것에 대한 답을 모릅니다. 저는 mathematica.SE의 모든 사람들이 갖고 싶어하는 몇 가지 기본 기능과 상단에 체리가 될 추가 기능을 나열했습니다. 그러나 구현하기가 너무 어려운 경우 알려주십시오. 더 작은 기능 하위 집합을 해결할 수 있습니다.
이 도움을 인정하여 여러분 모두는 Mathematica 커뮤니티의 영원한 감사를 받고 있으며, 여기 에 크게 기여한 각 사람에게 500 현상금을 수여 할 것 입니다 (다른 사람이 부분적으로 수행 한 경우). 중요한 것이 무엇인지 결정하기 위해 답변에 대한 투표 / 댓글 / 출력 (모든 작업을 수행하는 경우 한 사람에게 하나 이상의 현상금). "추가 좋은 것"을 구현하면 이전 현상금에 관계없이 자동으로 +500을받습니다., 그래서 당신은 또한 당신이 전반을하지 않더라도 다른 사람의 작업을 기반으로 할 수 있습니다. 또한이 질문을 보지 못한 사용자를 유치하기 위해 주기적으로 작은 현상금을 배치 할 수 있습니다. 따라서 이러한 현상금을 받으면 마지막에 결정될 "기존 답변에 대한 보상금"에 추가 될 것입니다. .
마지막으로 서두르지 않습니다. 그러므로이 질문에 시간을내어주십시오. 현상금은 SE에 의해 구현 될 때까지 (또는 기존 답변이 요구 사항을 완전히 충족한다고 결정된 경우) 항상 옵션입니다. 이상적으로는, 지금부터 2 개월 후 베타 버전으로 2/3가 구현되기를 희망합니다.
머리말
이후 티카 지원 구글 코드 싸게 치장을 위해 주로 새로운 개발 된 Mathematica.Stackexchange의 사이트도 논의를 참조하십시오 여기 .
소개
이 모든 것에 대한 깊은 지식은 없지만 Idea에 대한 cweb 플러그인을 작성하여 코드를 강조 표시하는 경우가있었습니다. IDE에서는이 모든 것이 한 단계 프로세스가 아닙니다. 여러 단계로 나뉘며 각 단계에는 더 많은 강조 기능이 있습니다. 나중에 우리가 여기에 필요한 코드 하이 라이터에 대해 어떤 일이 (imho) 불가능한 이유를 설명하기 위해 이것을 조금 설명하겠습니다.
처음에 코드는 프로그래밍 언어의 단일 부분 인 토큰으로 분할됩니다. 이 어휘 분석기를 사용하면 코드 간격을 공백, 리터럴, 문자열, 주석 등으로 분류 할 수 있습니다. 이 어휘 분석기 는 정규 표현식을 테스트하고, 텍스트 범위에 대한 토큰 유형을 저장하고, 코드에서 앞으로 나아감으로써 소스 코드를 먹 습니다.
이 어휘 스캔 후 프로그래밍 언어, 토큰 및 기본 코드의 규칙을 사용하여 소스 코드를 구문 분석 할 수 있습니다. 예를 들어 Plus
유형 의 토큰이 있는 Keyword
경우 대괄호와 매개 변수가 뒤에 와야한다는 것을 알고 있습니다. 그렇지 않은 경우 구문이 올바르지 않습니다. 이 파싱으로 구축 할 수있는 것은 AST, 추상 구문 트리라고하며 기본적으로 TreeForm
Mathematica 구문 과 비슷 합니다.
예를 들어 Java와 같이 멋지게 설계된 언어를 사용하면 입력하는 동안 코드를 확인할 수 있으며 구문 적으로 잘못된 코드를 작성하는 것이 거의 불가능합니다.
prettify.js 및 Mathematica 코드
첫째, prettify.js는 어휘 스캐너 만 구현하고 구문 분석기는 구현하지 않습니다. 나는 이것이 웹 페이지를 표시하는 시간 제한과 관련하여 어쨌든 불가능할 것이라고 확신합니다. 그래서 prettify.js로 어떤 기능이 가능하지 않은지 설명하겠습니다.
또한 주황색으로 강조 표시된 일부 변수를 눈치 채 셨을 것입니다. Mathematica를 알고있는 파서 없이는 수행하기가 훨씬 더 어려울 것이라고 생각하기 때문에 일부러이를 요구 사항으로 포함하지 않았습니다.
맞습니다. 이러한 변수의 강조 표시는 컨텍스트에 따라 달라지기 때문입니다. 당신은 당신이 Table
구조 안에 있다는 것을 알아야 합니다.
prettify.js 해킹
prettify.js의 확장 프로그램을 해킹하는 것은 그렇게 어렵지 않다고 생각합니다. 나는 절대 정규식 멍청이이므로 다음을 준비하십시오.
간단한 Mathematica 렉서에는 많은 것이 필요하지 않습니다. 공백, 주석, 문자열 리터럴, 중괄호, 많은 연산자, 변수와 같은 일반적인 리터럴 및 거대한 키워드 목록이 있습니다.
Java 스크립트 regexp-form의 키워드로 시작하겠습니다.
Export["google-code-prettify/keywordsmma.txt",
StringJoin @@ Riffle[Apply[StringJoin,
Partition[Riffle[Names[RegularExpression["[A-Z].*"]],
"|"], 100], {1}], "'+ \n '"], "TEXT"]
공백 및 문자열 리터럴에 대한 정규식은 다른 언어에서 복사 할 수 있습니다. 댓글은 다음과 같이 일치합니다.
/^\(\*[\s\S]*?\*\)/
댓글 안에 댓글이 있으면 잘못 실행되지만 지금은 신경 쓰지 않습니다. 우리는 중괄호와 괄호가 있습니다
/^(?:\[|\]|{|}|\(|\))/
blub_boing
개별적으로 일치해야하는 것과 같은 것이 있습니다.
/^[a-zA-Z$]+[a-zA-Z0-9$]*_+([a-zA-Z$]+[a-zA-Z0-9$]*)*/
슬롯 #, ##, # 1, ## 9가 있습니다 (현재는 한 자리 만 따를 수 있음)
/^#+[0-9]?/
변수 이름과 다른 리터럴이 있습니다. 문자 또는 $로 시작해야하며 문자, 숫자 및 $를 따를 수 있습니다. 현재 \[Gamma]
는 하나의 리터럴로 일치하지 않지만 현재 는 괜찮습니다.
/^[a-zA-Z$]+[a-zA-Z0-9$]*/
그리고 우리는 연산자를 가지고 있습니다 (이 목록이 완전한지 모르겠습니다).
/^(?:\+|\-|\*|\/|,|;|\.|:|@|~|=|\>|\<|&|\||_|`|\^)/
최신 정보
나는 물건을 약간 청소하고 디버깅을 수행하고 나에게 아름답게 보이는 색상 스타일을 만들었습니다. 다음 항목은 내가 올바르게 볼 수있는 한 작동합니다.
- 찾을 수있는 모든 시스템 기호
Names[RegularExpression["[A-Z].*"]]
가 일치하고 파란색으로 강조 표시됩니다. - 중괄호와 괄호는 검은 색이지만 굵은 글꼴 두께입니다. 이것은 Szabolcs의 제안 이며 코드의 외관에 에너지 를 확실히 추가하기 때문에 매우 좋아합니다.
- 기능 정의에 나타나는 패턴과 순수 기능의 슬롯은 녹색으로 강조 표시됩니다. 이것은 Yoda가 제안했으며 Mathematica 프런트 엔드의 형광펜과 함께 사용됩니다. 패턴에서 같은 변수와 함께 만 녹색
blub__Integer
,a1_
또는b34_Integer32
. in과 같은 패턴에 대한 테스트 기능은num_?NumericQ
물음표 앞에 녹색 만 있습니다. - 주석과 문자열은 같은 색입니다. 주석과 문자열은 여러 줄에 걸쳐있을 수 있습니다. 문자열에는 백 슬래시 따옴표가 포함될 수 있습니다. 주석은 중첩 될 수 없습니다.
- 채색
ColorData[1]
을 위해 나는 색상이 나란히 멋지게 보이도록 일관되게 사용 했습니다.
현재 다음과 같이 보입니다.
테스트 및 디버깅
Szabolcs asked whether and how it is possible to test this. This is easy: You need my google-code-prettify source (Where can I put this, so that everyone has access?). Unpack the sources and open the file tests/mathematica_test.html
in a webbrowser. This file loads by itself the files src/prettify.js
, src/lang-mma.js
and src/prettify-mma-1.css
.
- in
lang-mma.js
you find the regular expression the lexer is using when splitting the code into tokens. - in
prettify-mma-1.css
you find the style definitions I use
To test your own code, simply open mathematica_test.html
in an editor and paste your stuff between the pre
tags. Reload the page and your code should appear.
Debugging: If the highlighter is not working correctly, you can debug with an IDE or with Google-Chrome. In Chrome you mark the word where the highlighter starts to fail and make right-klick and Inspect Element
. What you see then is the underlying html-highlight code. There you can see every single token and you see which type the token is. This looks then like
<span class="tag">[</span>
You see the open bracket is of type tag
. This matches with the regexp definition I made in lang-mma.js
. In Chrome it is even possible to browse the JS code, set breakpoints and debug it while reloading your page.
Local installation for Google Chrome and Firefox
Tim Stone was so kind to write a script which injects the highlighter during the loading of sites under http://stackoverflow.com/questions/
. As soon as google-code-prettify is turned on for mathematica.stackexchange.com
it should work there too. I adapted this script to use my lexical scanning rules and colors. I heard that in Firefox the script is not always working, but this is how to install it:
- Chrome: Follow this link https://github.com/halirutan/Mathematica-Source-Highlighting/raw/master/mathematica-source-highlighter.user.js and you should be prompted whether you want to install this extension.
- Firefox: ensure you have the Greasemonkey plugin installed. Then download the same link as for Chrome.
- Now you are set up and when you reload this page, comments, kernel-functions, strings and patterns should be highlighted correctly.
Versions
Under https://github.com/halirutan/Mathematica-Source-Highlighting/raw/master/mathematica-source-highlighter.user.js you will always find the most recent version. Here is some change history. - 02/23/2013 Updated the lists of symbols and keywords to Mathematica version 9.0.1 - 09/02/2012 some minor issues with the coloring of Mathematica-patterns were fixed. For a detailed overview of features with Pattern
-operator :
see also the discussion here
- 02/02/2012 support of many number input formats like
.123`10.2
or1.2`100.3*^-12
, highlighting ofIn[23]
andOut[4]
,::usage
or other messages likeblub::boing
, highlighting of patterns likeProblemTest[prob:(findp_[pfun_, pvars_, {popts___}, ___]), opts___]
, bug-fixes (I checked the parser against 3500 lines of package code from the AddOns directory. It took about 3-4 sec to run, which should be more than fast enough for our purposes.) - 01/30/2012 Fixed missing '?' in the operator list. Included named-characters like
\\[Gamma]
to give a complete match for such symbols. Added $variables in the keyword list. Improved the matching of patterns. Added matching of context constructions like Developer`PackedArrayQ. Switch of the color-scheme due to many requests. Now it's like in the Mathematica-frontend. Keywords black, variables blue. - 01/29/2012 Tim hacked to injecting code. Now the highlighting works on mathematica.stackexchange too.
- 01/25/2012 Added the recognition of Mathematica-numbers. This should now highlight things like
{1, 1.0, 1., .12, 16^^1.34f, ...}
. Additionally it should recognize the backtick behind a number. I switched comments and strings to gray and use a dark red for the numbers. - 01/23/2012 Initial version. Capabilities are described under section Update.
Not exactly what you are asking for, but I created a similar extension for MATLAB (based on the excellent work already done here). The project is hosted on github.
The script should solve some of the issues common for MATLAB code on Stack Overflow:
- comments (no need to use tricks like
%# ..
) - transpose operator (single quote) is correctly recognized as such (confused with quoted strings by the default prettifier)
- highlighting of popular built-in functions
Keep in mind the syntax highlighting is not perfect; among other things, it fails on nested block comments (I can live with that for now). As always, comments/fixes/issues are welcome.
A separate userscript is included, it allows switching the language used as seen in the screenshot below:
--- before ---
--- after ---
For those interested, a third userscript is provided, adapted to work on "MATLAB Answers" website.
TL;DR
Install the userscript for SO directly from:
https://github.com/amroamroamro/prettify-matlab/raw/master/js/prettify-matlab.user.js
참조 URL : https://stackoverflow.com/questions/8957682/can-prettify-js-be-extended-to-support-mathematica
'Development Tip' 카테고리의 다른 글
Pandoc 및 외국 문자 (0) | 2020.12.31 |
---|---|
TypeScript 코딩 스타일 가이드? (0) | 2020.12.31 |
-webkit-overflow-scrolling : 터치; (0) | 2020.12.31 |
Visual Studio가 MSBuild에 전달하는 매개 변수는 무엇입니까? (0) | 2020.12.31 |
Sun VM에서 할 수있는 Dalvik VM (Android의 VM)에서 할 수없는 것은 무엇입니까? (0) | 2020.12.31 |