A Syntax Highlighter built in PHP and jQuery that supports customizable languages and themes.
It can highlight from a URL, or WordPress post text. Crayon makes it easy to manage Language files and define
custom language elements with regular expressions.
It also supports some neat features like:
- Официальная страница WP (не поддерживается с 2017 года) https://ru.wordpress.org/plugins/crayon-syntax-highlighter/
- Неофициальная поддержка https://github.com/Crunchify/crayon-syntax-highlighter/releases
Опции
///
- Title - позволяет создать заголовок исходника
- Inline - оформляет в специальном inline-виде
- Don't Highlight - отключает подсветку синтаксиса
- Language Line Range - позволяет обозначить строки для подсветки синтаксиса (например одну: "3" или группу: "3-5")
- Marked Lines - позволяет специально выделить строки и группы строк (например: "1,5,8-15")
- Code - исходный код лучше вводить здесь, т.к. в редакторе возникают проблемы с тэгами
- URL
- SETTINGS
- Theme
- Font
- Custom Font Size 12 Pixels,
- Line Height 16 Pixels
- Metrics
- Height 500 Width 1400
- Top Margin 12 Pixels
- Bottom Margin 12 Pixels
- Left Margin 12 Pixels
- Right Margin 12 Pixels
- Horizontal Alignment
- Allow floating elements to surround Crayon
- Inline Margin 30 Pixels
- Toolbar
- Display the Toolbar
- Overlay the toolbar on code rather than push it down when possible
- Toggle the toolbar on single click when it is overlayed
- Delay hiding the toolbar on MouseOut
- Display the title when provided
- Display the language
- Lines
- Display striped code lines - Отображать полосатые строки кода
- Enable line marking for important lines - Включить маркировку линий для важных линий
- Enable line ranges for showing only parts of code - Включить линейные диапазоны для отображения только частей кода
- Display line numbers by default - Отображать номера строк по умолчанию
- Enable line number toggling - Включить переключение номера строки
- Wrap lines by default - Перенос строк по умолчанию
- Enable line wrap toggling - Включить переключение переноса строки
- Start line numbers from: 1 - Начать нумерацию строк со значения
- Code
- Enable plain code view and display - Включить просмотр и отображение простого кода
- Enable plain code toggling - Включить переключение простого кода
- Show the plain code by default - Показать простой код по умолчанию
- Enable code copy/paste - Включить копирование / вставку ко
- Enable opening code in a window - Включить открытие кода в окне
- Always display scrollbars - Всегда отображать полосы прокрутки
- Minimize code - Свернуть код ()
- Expand code beyond page borders on mouseover - Разверните код за пределами страницы при наведении мыши
- Enable code expanding toggling when possible - Включить код расширения, если это возможно
- Decode HTML entities in code - Декодировать HTML-объекты в коде
- Decode HTML entities in attributes - Декодировать сущности HTML в атрибутах
- Remove whitespace surrounding the shortcode content - Удалить пробелы вокруг содержимого шорткода
- Remove <code> tags surrounding the shortcode content - Удалить теги <code>, окружающие содержимое шорткода
- Allow Mixed Language Highlighting with delimiters and tags - Разрешить подсветку смешанного языка с разделителями и тегами
- Show Mixed Language Icon (+) - Показать значок смешанного языка (+)
- Convert tabs to spaces - Преобразовать табуляции в пробелы
- Tab size in spaces: 4 - Размер табуляции в пробелах
- Blank lines before code: 0 - Пустые строки перед кодом
- Blank lines after code: 0 - Пустые строки после кода
- Tags
- Capture Inline Tags - Захватить встроенные теги
- Wrap Inline Tags - Обернуть встроенные теги
- Capture <code> as - Захватить <code> как
- Capture
backquotes
as <code> - Захватить "обратные кавычки" как <code> - Capture <pre> tags as Crayons - Захватывать теги <pre> как карандаши
Использование этой разметки для мини-тегов и встроенных тегов теперь не рекомендуется! Вместо этого используйте редактор тегов и конвертируйте устаревшие теги. - Capture Mini Tags like [php][/php] as Crayons - Захватывайте мини-теги, такие как [php] [/ php], как Crayons
- Capture Inline Tags like {php}{/php} inside sentences - Захват встроенных тегов, таких как {php} {/ php} внутри предложений
- Enable [plain][/plain] tag - Включить тег [plain] [/ plain]
- Languages
- When no language is provided, use the fallback - Если язык не указан, использовать запасной вариант
Базовые темы оформления
Опция темы оформления Theme применяется, даже если подсветка синтаксиса отключена опцией Don't Highlight
1c-kod
1 2 3 4 5 6 |
Функция СредPHP(Строка, НачальныйНомер, ЧислоСимволов) Экспорт // уменьшает число символов на каждый двубайтный символ КурсорСтроки = НачальныйНомер; Пока КурсорСтроки < НачальныйНомер + ЧислоСимволов Цикл Если КодСимвола(Строка, КурсорСтроки) > 255 Тогда ЧислоСимволов = ЧислоСимволов - 1; |
1c-Zapros
1 2 3 4 5 6 7 |
ВЫБРАТЬ Процесс, КвалификационноеЗнание, Период ПОМЕСТИТЬ АктуальныеЗнания ИЗ ВсеЗнанияПроцессов ВНУТРЕННЕЕ СОЕДИНЕНИЕ КлючиАктуальныхЗнаний ПО (ВсеЗнанияПроцессов.Процесс = КлючиАктуальныхЗнаний.Процесс) И (ВсеЗнанияПроцессов.Период = КлючиАктуальныхЗнаний.Период) ГДЕ Процессы.Актуальность = ИСТИНА; |
Ado
1 2 3 4 5 6 7 8 9 10 11 |
try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine("\t{0}\t{1}\t{2}", reader[0], reader[1], reader[2]); } reader.Close(); } |
Arduino Ide
1 2 3 4 5 6 |
void setup() { // make pin 2 an input and turn on the pull-up resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); Keyboard.begin(); } |
Bncplusplus
1 2 3 4 5 6 7 |
int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } |
Capacitacionti
1 2 3 4 5 6 7 |
int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } |
Cg Cookie
1 2 3 4 5 6 7 8 |
# Python 2 syntax print 'Hello, world!' raw_input('What is your name?\n') self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7) # Unit testing with unittest copy[(size - 1) / 2] # access of a list index without casting to int xrange(BOARD_SIZE) # xrange exists cmp(1.0, 0.0) # cmp function exists iteratable.next() # list iteration |
Cisco Router
1 2 3 4 5 6 7 8 |
Router# tclsh Router(tcl)# exec "show interfaces" Ethernet 0 is up, line protocol is up Hardware is MCI Ethernet, address is 0000.0c00.750c (bia 0000.0c00.750c) Internet address is 10.108.28.8, subnet mask is 255.255.255.0 MTU 1500 bytes, BW 10000 Kbit, DLY 100000 usec, rely 255/255, load 1/255 Encapsulation ARPA, loopback not set, keepalive set (10 sec) ARP type: ARPA, ARP Timeout 4:00:00 |
Classic
1 2 3 4 5 6 7 8 9 10 11 |
function checkUserInput(userString: string): boolean; var valid: boolean; count: integer; begin valid := true; for count := 1 to length(userString) do if ((ord(userString[count]) < 65) or (ord(userString[count]) > 90)) and (userString[count] <> ' ') then valid := false; checkUserInput := valid; end; |
Dark Terminal
1 2 3 4 5 6 7 8 9 10 11 12 |
# this while loop iterates over all lines of the file while read LINE do # increase line counter ((count++)) # write current line to a tmp file with name $file (not needed for counting) echo $LINE > $file # this checks the return code of echo (not needed for writing; just for demo) if [ $? -ne 0 ] then echo "Error in writing to file ${file}; check its permissions!" fi done |
Familiar
1 2 3 4 5 6 7 8 |
10 print "Table of Squares" 20 print 30 print "How many values would you like?" 40 input num 50 for i=1 to num 60 print i, i*i 70 next i 80 end |
Github
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Scanner; class PalindromeCheck { public static void main(String[]args) { //For capturing user input Scanner scanner = new Scanner(System.in); System.out.println("Enter the String for check:"); String string = scanner.nextLine(); if(isPal(string)) System.out.println(string + " is a palindrome"); else System.out.println(string + " is not a palindrome"); } } |
Idle
1 2 3 4 5 6 7 8 9 10 11 12 13 |
(print"Lucrarea 3") (terpri) (setf a (make-array '(3 3) :initial-contents '((1 2 3) (4 5 6) (7 8 9)) ) ) (write a) (terpri) (defun afisare(i j) (print (aref a i j))) (afisare 1 2) (terpri) |
Iris Vfx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
.MODEL SMALL .CODE PUBLIC _chips _chips PROC control dw 0 ; control word needed for the NDP test push BP ; save where Ur at mov BP,SP ; going in..... push DI push SI push CX ; not really needed for MSC but kinda call cpu_type ; find out what kinda CPU you got and call ndp_type ; check for math coprocessor (NDP) type add AX,DX ; add the two results together and hold pop CX ; put things back the way that you pop SI ; found 'em when you started this pop DI ; little drill off..... pop BP ret |
Kayote
1 2 3 4 5 6 7 8 9 |
<title>Example</title> <style> .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); grid-gap: 20px; align-items: stretch; } </style> |
Monokai
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function setCookie() { document.cookie="username=Duke Martin;expires=Sun, 20 Aug 2030 12:00:00 UTC"; } function getCookie() { if(document.cookie.length!=0) { var array=document.cookie.split("="); alert("Name="+array[0]+" "+"Value="+array[1]); } else { alert("Cookie not available"); } } |
Neon
1 2 3 4 5 6 7 8 9 10 11 |
function wptexturize_primes( $haystack, $needle, $prime, $open_quote, $close_quote ) { $spaces = wp_spaces_regexp(); $flag = '<!--wp-prime-or-quote-->'; $quote_pattern = "/$needle(?=\\Z|[.,:;!?)}\\-\\]]|>|" . $spaces . ')/'; $prime_pattern = "/(?<=\\d)$needle/"; $sentences = explode( $open_quote, $haystack ); foreach ( $sentences as $key => &$sentence ) { if ( false === strpos( $sentence, $needle ) ) { continue; } elseif ( 0 !== $key && 0 === substr_count( $sentence, $close_quote ) ) { $sentence = preg_replace( $quote_pattern, $flag, $sentence, -1, $count ); |
Obsidian Light
1 2 3 4 5 6 |
Функция СредPHP(Строка, НачальныйНомер, ЧислоСимволов) Экспорт // уменьшает число символов на каждый двубайтный символ КурсорСтроки = НачальныйНомер; Пока КурсорСтроки < НачальныйНомер + ЧислоСимволов Цикл Если КодСимвола(Строка, КурсорСтроки) > 255 Тогда ЧислоСимволов = ЧислоСимволов - 1; |
Orange Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title> </title></head> <body> <form method="post" action="Default.aspx" id="form1"> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZEz/Fisf4pXOGIwh1k+T56F6UZDDdiElWxpws7onJEMM" /> </div> <div> <h1>Привет!</h1> <p>Это новая веб-форма!</p> </div> </form> </body> </html> |
Plain White
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<%@ Language= "VBScript" %> <html> <head> <title>Example 1</title> </head> <body> <font face="MS Gothic"> <H1>Welcome to my Home Page</H1> <% 'Create some variables. dim strDynamicDate dim strDynamicTime 'Get the date and time. strDynamicDate = Date() strDynamicTime = Time() 'Print out a greeting, depending on the time, by comparing the last 2 characters in strDymamicTime to "PM". If "PM" = Right(strDynamicTime, 2) Then Response.Write "<H3>Good Afternoon!</H3>" Else Response.Write "<H3>Good Morning!</H3>" End If %> Today's date is <%=strDynamicDate%> and the time is <%=strDynamicTime%> </font> </body> </html> |
Powershell
1 2 3 4 5 6 7 |
$value = Get-ItemProperty -Path HKCU:\Environment -Name Path $newpath = $value.Path += ";C:\src\bin\" Set-ItemProperty -Path HKCU:\Environment -Name Path -Value $newpath New-ItemProperty -Name PowerShellPath -PropertyType String -Value $PSHome ` -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion, HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PSHome Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath |
Solarized Light
1 2 3 4 5 6 7 8 |
USE AdventureWorks2012; GO SELECT Name, ProductNumber, ListPrice AS Price FROM Production.Product WHERE ProductLine = 'R' AND DaysToManufacture < 4 ORDER BY Name ASC; GO |
Terminal
1 2 3 4 5 6 7 8 9 |
# Python code to get the Cumulative sum of a list def Cumulative(lists): cu_list = [] length = len(lists) cu_list = [sum(lists[0 + 1]) for x in range(0, length)] return cu_list # Driver Code lists = [10, 20, 30, 40, 50] print (Cumulative(lists)) |
Tomorrow
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Opt("GUINotifyMode", 1) GuiCreate("MyGUI", 400,280,10,10,0x04CF0000) $button = GUISetControl("button", "Button 1", 24,24, 176,80) $edit = GUISetControl("edit", "Edit 1", 208,24, 104,80) GuiShow() While 1 sleep(100) $msg = GuiMsg(0) Select Case $msg = -3 Exit EndSelect WEnd Exit |
Tomorrow Night
1 2 3 4 5 6 7 8 9 10 |
use strict; # Counters to return. my $nblank = 0; my $ncomm = 0; # Read each line into the variable $line. while(my $line = <STDIN>) { if($line =~ /^\s*$/) { ++$nblank; } if($line =~ /^\s*\#/) { ++$ncomm; } } print "$nblank blank lines, $ncomm comments.\n"; |
Vs2012
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System.Threading.Tasks; using System.Windows.Forms; namespace SimpleCalculator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Double val = 0; string operation = ""; bool oper_pressed = false; int dotCount = 0; |
Vs2012 Black
1 2 3 4 5 6 7 8 |
private void operator_click(object sender, EventArgs e) { Button b = (Button)sender; operation = b.Text; val = Double.Parse(inputBox.Text); oper_pressed = true; equation.Text = val + " " + operation; } |
Xcode
1 2 3 4 5 |
@IBAction func showMessage(sender: UIButton) { let alertController = UIAlertController(title: "Welcome to My First App", message: "Hello World", preferredStyle: UIAlertController.Style.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) present(alertController, animated: true, completion: nil) } |
///
ReKS
1 2 3 4 5 6 7 8 9 10 11 |
Функция СредPHP(Строка, НачальныйНомер, ЧислоСимволов) Экспорт // уменьшает число символов на каждый двубайтный символ КурсорСтроки = НачальныйНомер; Пока КурсорСтроки < НачальныйНомер + ЧислоСимволов Цикл Если КодСимвола(Строка, КурсорСтроки) > 255 Тогда ЧислоСимволов = ЧислоСимволов - 1; КонецЕсли; КурсорСтроки = КурсорСтроки + 1; КонецЦикла; Возврат Сред(Строка, НачальныйНомер, ЧислоСимволов); КонецФункции |
Ошибки
Последний официальный релиз 2.8.4 содержит три ошибки проводящие к фатальным ошибкам PHP 7.3
В файле /public_html/wp-content/plugins/crayon-syntax-highlighter/crayon_langs.class.php
1 2 |
//return preg_replace('/[^\w-+#]/msi', '', $id); return preg_replace('/[^\w\-+#]/msi', '', $id); |
В файле /public_html/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php
1 2 3 4 |
//$toolbar_height = $font_size * 1.5 . 'px !important;'; $toolbar_height = $_font_size * 1.5 . 'px !important;'; //$info_height = $font_size * 1.4 . 'px !important;'; $info_height = $_font_size * 1.4 . 'px !important;'; |
В файле /public_html/wp-content/plugins/crayon-syntax-highlighter/crayon_settings.class.php
1 |
... |
Источник //crunchify.com
Примеры