Переключение от python-mode.el до python.el

Это самокомпилированный гибрид bat / .net (должен быть сохранен как .BAT), который можно использовать в любой системе, на которой установлена ​​.NET-инфраструктура (редко можно увидеть окна без .NET framework даже для старейших установок XP / 2003). Он использует компилятор jscript.net для создания exe, способного печатать строки с различным цветом фона / переднего плана только для текущей строки.

@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal

for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
   set "jsc=%%v"
)

if not exist "%~n0.exe" (
    "%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)

%~n0.exe %*

endlocal & exit /b %errorlevel%

*/

import System;

var arguments:String[] = Environment.GetCommandLineArgs();

var newLine = false;
var output = "";
var foregroundColor = Console.ForegroundColor;
var backgroundColor = Console.BackgroundColor;
var evaluate = false;
var currentBackground=Console.BackgroundColor;
var currentForeground=Console.ForegroundColor;


//http://stackoverflow.com/a/24294348/388389
var jsEscapes = {
  'n': '\n',
  'r': '\r',
  't': '\t',
  'f': '\f',
  'v': '\v',
  'b': '\b'
};

function decodeJsEscape(_, hex0, hex1, octal, other) {
  var hex = hex0 || hex1;
  if (hex) { return String.fromCharCode(parseInt(hex, 16)); }
  if (octal) { return String.fromCharCode(parseInt(octal, 8)); }
  return jsEscapes[other] || other;
}

function decodeJsString(s) {
  return s.replace(
      // Matches an escape sequence with UTF-16 in group 1, single byte hex in group 2,
      // octal in group 3, and arbitrary other single-character escapes in group 4.
      /\\(?:u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([0-3][0-7]{0,2}|[4-7][0-7]?)|(.))/g,
      decodeJsEscape);
}


function printHelp( ) {
   print( arguments[0] + "  -s string [-f foreground] [-b background] [-n] [-e]" );
   print( " " );
   print( " string          String to be printed" );
   print( " foreground      Foreground color - a " );
   print( "                 number between 0 and 15." );
   print( " background      Background color - a " );
   print( "                 number between 0 and 15." );
   print( " -n              Indicates if a new line should" );
   print( "                 be written at the end of the ");
   print( "                 string(by default - no)." );
   print( " -e              Evaluates special character " );
   print( "                 sequences like \\n\\b\\r and etc ");
   print( "" );
   print( "Colors :" );
   for ( var c = 0 ; c < 16 ; c++ ) {

        Console.BackgroundColor = c;
        Console.Write( " " );
        Console.BackgroundColor=currentBackground;
        Console.Write( "-"+c );
        Console.WriteLine( "" );
   }
   Console.BackgroundColor=currentBackground;



}

function errorChecker( e:Error ) {
        if ( e.message == "Input string was not in a correct format." ) {
            print( "the color parameters should be numbers between 0 and 15" );
            Environment.Exit( 1 );
        } else if (e.message == "Index was outside the bounds of the array.") {
            print( "invalid arguments" );
            Environment.Exit( 2 );
        } else {
            print ( "Error Message: " + e.message );
            print ( "Error Code: " + ( e.number & 0xFFFF ) );
            print ( "Error Name: " + e.name );
            Environment.Exit( 666 );
        }
}

function numberChecker( i:Int32 ){
    if( i > 15 || i < 0 ) {
        print("the color parameters should be numbers between 0 and 15");
        Environment.Exit(1);
    }
}


if ( arguments.length == 1 || arguments[1].toLowerCase() == "-help" || arguments[1].toLowerCase() == "-help"   ) {
    printHelp();
    Environment.Exit(0);
}

for (var arg = 1; arg <= arguments.length-1; arg++ ) {
    if ( arguments[arg].toLowerCase() == "-n" ) {
        newLine=true;
    }

    if ( arguments[arg].toLowerCase() == "-e" ) {
        evaluate=true;
    }

    if ( arguments[arg].toLowerCase() == "-s" ) {
        output=arguments[arg+1];
    }


    if ( arguments[arg].toLowerCase() == "-b" ) {

        try {
            backgroundColor=Int32.Parse( arguments[arg+1] );
        } catch(e) {
            errorChecker(e);
        }
    }

    if ( arguments[arg].toLowerCase() == "-f" ) {
        try {
            foregroundColor=Int32.Parse(arguments[arg+1]);
        } catch(e) {
            errorChecker(e);
        }
    }
}

Console.BackgroundColor = backgroundColor ;
Console.ForegroundColor = foregroundColor ;

if ( evaluate ) {
    output=decodeJsString(output);
}

if ( newLine ) {
    Console.WriteLine(output);  
} else {
    Console.Write(output);

}

Console.BackgroundColor = currentBackground;
Console.ForegroundColor = currentForeground;

Пример coloroutput.bat -s "aa\nbb\n\u0025cc" -b 10 -f 3 -n -e

Вы также можете проверьте цветовую функцию carlos -> http://www.dostips.com/forum/viewtopic.php?f=3&t=4453

30
задан Alex Coventry 12 December 2008 в 11:37
поделиться

4 ответа

Если это имеет значение я не вижу поведения, Вы видите обсуждаемый № 1, "Каждый буфер, посещая файл Python получает свою собственную нижнюю интерактивную оболочку Python".

Это - то, что я сделал использование python.el от Emacs 22.2.

C-x C-f foo.py [вставьте: распечатайте "нечто"]

, C-x C-f bar.py [вставляет: распечатайте "панель"]

C-c C-z [*Python*, буфер появляется]

RET C-x o

C-c C-l ["панель" печатается в *Python*]

RET C-x b foo.py RET

C-c C-l ["нечто" печатается в том же *Python* буфер]

Поэтому, эти два файла совместно используют ту же нижнюю оболочку Python. Возможно, существует некоторое непредвиденное взаимодействие между Вашими персональными настройками режима Python и поведениями по умолчанию python.el. Вы попытались использовать python.el без своих .emacs настроек и проверить, ведет ли он себя тот же путь?

добавление основной функции python.el по режиму Python является полным символом Python функции завершения символа. Можно добавить что-то вроде этого

(define-key inferior-python-mode-map "\C-c\t" 'python-complete-symbol)

Затем ввод

>>> import os
>>> os.f[C-c TAB]

, Вы доберетесь *Завершения* буфер, содержащий

Click <mouse-2> on a completion to select it.
In this buffer, type RET to select the completion near point.

Possible completions are:
os.fchdir                          os.fdatasync
os.fdopen                          os.fork
os.forkpty                         os.fpathconf
os.fstat                           os.fstatvfs
os.fsync                           os.ftruncate

, Он будет работать в .py буферах файлов также.

4
ответ дан 28 November 2019 в 00:30
поделиться

python-mode.el записан сообществом Python. python.el записан emacs сообществом. Я использовал python-mode.el столько, сколько я могу помнить, и python.el даже не близко подходит к стандартам python-mode.el. Я доверяю сообществу Python лучше, чем сообщество Emacs для предложения достойного файла режима. Просто палка с python-mode.el, там действительно причина не к?

1
ответ дан 28 November 2019 в 00:30
поделиться

python-mode.el has no support triple-quoted strings, so if your program contains long docstrings, all the syntax coloring (and associated syntaxic features) tends to break down.

my .02

1
ответ дан 28 November 2019 в 00:30
поделиться
  1. Я не могу воспроизвести это поведение в Emacs v23.1, с тех пор это должно быть изменено.

  2. Забудьте о поддержке скелета любого режима и используйте вместо этого сверхсовременный и расширяемый yasnippet , это действительно стоит попробовать!

3
ответ дан 28 November 2019 в 00:30
поделиться
Другие вопросы по тегам:

Похожие вопросы: