JScript

Programação & Desenvolvimento


Você não está conectado. Conecte-se ou registre-se

[Projeto] Syntax Highlighter "caseiro"!

3 participantes

Ir para baixo  Mensagem [Página 1 de 1]

1[Projeto] Syntax Highlighter "caseiro"! Empty [Projeto] Syntax Highlighter "caseiro"! Seg 13 Abr 2015, 9:54 pm

JScript

JScript
Administradores
Administradores

Todos nós já sabemos que existem vários códigos espalhados na web com essa finalidade, mas eu não estou aqui tentando reinventar a roda, eu estou apenas aprimorando conhecimentos em especial com regex!!!

Abaixo um pequeno código que adiciona contagem de linhas e alguns botões úteis na tag CODE:
Código:

console.clear();

var style = document.createElement("style");
style.type = "text/css";
style.innerHTML =
   'code.jsCode_block, pre.jsCode_block {' +
   '  background-color: #FAFAFA !important;' +
   '  border: 1px solid #C9C9C9 !important;' +
   '  color: #000000;' +
   '  font-family: Consolas,"Bitstream Vera Sans Mono","Andale Mono",Monaco,"DejaVu Sans Mono","Lucida Console",monospace !important;' +
   '  font-size: 11px !important;' +
   '  line-height: 110% !important;' +
   '   margin-top: 0 !important;' +
   '  max-height: 250px !important;' +
   '  overflow: auto !important;' +
   '  padding: 5px !important;' +
   '  white-space: pre-wrap !important;' +
   '  width: auto !important;' +
   '}' +
   '.jsCodetop {' +
   '  background-color: #FFDEAD !important;' +
   '  color: #1D3652;' +
   '  font-size: 10px;' +
   '  font-weight: bold;' +
   '  line-height: 100%;' +
   '  margin-top: 5px;' +
   '  padding: 2px 1px 2px 3px;' +
   '}' +
   '.jsCodetop button {' +
   '  background: -moz-linear-gradient(center top , #EDEDED 5%, #DFDFDF 100%) repeat scroll 0 0 #EDEDED;' +
   '  border: 1px solid #BBBBBB;' +
   '  border-radius: 3px 3px 3px 3px;' +
   '  color: #1D3652;' +
   '  cursor: pointer;' +
   '  display: inline-block;' +
   '  font-size: 10px;' +
   '  padding: 0 6px;' +
   '  text-decoration: none;' +
   '}' +
   '.jsCodetop button:hover {' +
   '  background: -moz-linear-gradient(center top , #DFDFDF 5%, #EDEDED 100%) repeat scroll 0 0 #DFDFDF;' +
   '  border-color: #9A9A9A;' +
   '  color: #3D70A3;' +
   '}' +
   '.jsCodetop button:active {' +
   '  position: relative;' +
   '  top: 1px;' +
   '}' +
   'pre.jsCode_block.expand, code.jsCode_block.expand {' +
   '  max-height: 100% !important;' +
   '}' +
   'pre ol.linenums {' +
    '   color: #afafaf;' +
    '   font-size: 12px;' +
    '   list-style: outside none decimal;' +
    '   padding: 5px 0 5px 42px !important;' +
    '   margin: -16px 0 0;' +
   '   width: auto;' +
   '}' +
   'pre ol.linenums li > span {' +
   '   color: #000000;' +
   '}' +
   'pre ol.linenums li {' +
   '   border-left: 3px solid #6ce26c;' +
   '   padding-left: 15px;' +
   '   list-style: inherit;' +
   '   font-size: inherit !important;' +
   '}';
document.getElementsByTagName("head")[0].appendChild(style);

  // Keyword lists for various languages.
  var FLOW_CONTROL_KEYWORDS =
      "break continue do else for if return while ";
  var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " +
      "double enum extern float goto int long register short signed sizeof " +
      "static struct switch typedef union unsigned void volatile ";
  var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " +
      "new operator private protected public this throw true try typeof ";
  var JSCRIPT_KEYWORDS = COMMON_KEYWORDS +
      "debugger eval export function get null set undefined var with " +
      "Infinity NaN ";

var temp = JSCRIPT_KEYWORDS.split(' ');
console.log(temp);

//jQuery(function() {
   var tagCode = jQuery('.cont_code, code'),
      codebox = null,
      memDiv = $('<div/>');

   for (var i = 0, len = tagCode.length; i < len; i++) {
      tagCode[i].innerHTML = tagCode[i].innerHTML
         //.replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g, ' <span style="color: black;">$1 = <span style="font-style: italic;">$2$3$4</span></span>')
         .replace(/("[^"\\\r\n]*(?:\\.[^"\\\r\n]*)*"|'[^'\\\r\n]*(?:\\.[^'\\\r\n]*)*')/g, '<span style="color: blue;">$1</span>')
         .replace(/(\/\/.*$|\/\*.*?\*\/)/g, '<span style="color: #008200;">$1</span>')
         .replace(/function /mg, '<span style="color: #069;font-weight: bold;">function </span>')
         .replace(/if \(/mg, '<span style="color: #069;font-weight: bold;">if </span>(')
         .replace(/var /mg, '<span style="color: #069;font-weight: bold;">var </span>')
      ;

      codebox = jQuery(tagCode[i]).closest('.codebox');
      codebox.before(
         '<div class="jsCodetop">Code &nbsp; &nbsp; &nbsp; &nbsp;<button onclick="jsCodeExpand(this); return false;">expand</button>' +
         '   <button style="display: none" onclick="jsCodeCollapse(this); return false;">collapse</button>&nbsp; ' +
         '   <button onclick="jsCodeSelect(this); return false;">select</button>&nbsp; ' +
         '   <button onclick="jsCodePopup(this); return false;">popup</button>&nbsp; ' +
         '   <button style="margin-right: 50px; float: right;" onclick="jsCodeAbout(this); return false;">?</button>' +
         '</div>' +
         '<pre class="jsCode_block">' +
         '   <ol class="linenums">' + tagCode[i].innerHTML.replace(/<br>/mg, '<li class="L1"><span>') + '</ol>' +
         '</pre>'
      );
      codebox.remove();
   }
//});

function jsCodeExpand(oThis) {
    jQuery(oThis).css('display', 'none');
    jQuery(oThis).next().css('display', '');
    jQuery(oThis).parent().next('pre.jsCode_block').addClass('expand');
}
function jsCodeCollapse(oThis) {
    jQuery(oThis).css('display', 'none');
    jQuery(oThis).prev().css('display', '');
    jQuery(oThis).parent().next('pre.jsCode_block').removeClass('expand');
}
function jsCodePopup(oThis) {
    var content = jQuery(oThis).parent().next('pre.jsCode_block').html();
    var my_window = window.open("", "JScript - Para selecionar o código: [Ctrl] + [A]", "scrollbars=1toolbar=no,menubar=no,personalbar=no,status=0,left=0,location=0,menubar=0,top=0,width=640,height=480");
    my_window.document.write('<pre>'+content+'</pre>');
}
function jsCodeAbout(oThis) {
    alert('Simple code to add line counter fuctionality for Forumotion\n\nBy JScript FROM Brazil - 2015/04/10\n');
}
function jsCodeSelect(oThis) {
    var doc = document;
    var text = jQuery(oThis).parent().next('pre.jsCode_block')[0];
    if (doc.body.createTextRange) {
        var range = doc.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();
        var range = doc.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

O código acima é baseado em outro código que eu fiz mas que adiciona um "verdadeiro" syntax highlighter, porém como uma forma de aprendizado eu estou tentando fazer algo parecido com um simples syntax highlighter...

Façam testes no console para ver o efeito!

Eu agradeço a todos que desejarem ajudar nesse projeto,

JS

http://autoitbrasil.com

waghcwb

waghcwb
Desenvolvedores
Desenvolvedores

Bom com o pouco tempo que sobra aqui, minha contribuição é básica, mas talvez já vale de alguma coisa

Código:
var PYTHON_KEYWORDS = 'and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try';

Outra coisa, isso aqui não é redundância?
Código:
var temp = JSCRIPT_KEYWORDS.split(' ');

Não seria melhor já fazer o código em array ali?

http://wagneraugusto.com.br/

JScript

JScript
Administradores
Administradores

Valeu amigo, tudo é contribuição!!!

Sobre a redundância, seria de que forma?

JS

http://autoitbrasil.com

waghcwb

waghcwb
Desenvolvedores
Desenvolvedores

Execute isso ai no console

Código:
var PYTHON_KEYWORDS = 'and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try';

console.info(typeof PYTHON_KEYWORDS);

PYTHON_KEYWORDS = PYTHON_KEYWORDS.split(' ');

console.info(typeof PYTHON_KEYWORDS);

var ARRAY_PYTHON = ["and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try"];

console.info(typeof PYTHON_KEYWORDS);

http://wagneraugusto.com.br/

joelson0007

joelson0007
Moderadores
Moderadores

Muito complexo isso Sad

JScript

JScript
Administradores
Administradores

@waghcwb
hummm, agora eu entendi, mas é que sendo string eu achava que ficaria mais fácil a manutenção, porém sendo logo um array, elimina-se linhas de código...

@joelson0007
Eu já vi como é feito em alguns códigos e usam vários métodos inclusive o de loops assíncronos, mas eu queria fazer algo bem simples mesmo que ficasse "universal" entende?

JS

http://autoitbrasil.com

joelson0007

joelson0007
Moderadores
Moderadores

Eu já pensei em fazer isso, mas achei que seria muito difícil, então não quis nem tentar, igual ASM, ao ver o primeiro code, falei, não é pra mim!

Mas vou acompanhar pra aprender, como vai fazer isso!

JScript

JScript
Administradores
Administradores

Boa parte já está feita, a numeração das linhas, botões de funções...

Agora basta somente uns regex para dar conta!

JS

http://autoitbrasil.com

Conteúdo patrocinado



Ir para o topo  Mensagem [Página 1 de 1]

Permissões neste sub-fórum
Não podes responder a tópicos