Emmabuntüs Forum
Collectif pour le réemploi des ordinateurs et distribution Linux basée sur Debian

  Accueil -  Tutoriels -  Téléchargements -  Vidéos -  Interviews -  Qui sommes-nous -  Nous contacter -  Soutenir


je crée une nouvelle extension *.xst pour du texte ANSI!

0 Membres et 1 Invité sur ce sujet

oui

  • Jr. Member
  • **
    • Messages: 74
répondant à ce filtre en python3:

!/usr/bin/env python3
import sys
import re

ANSI_ON = {
    'center': '1',
    'b': '1', 'i': '3', 'u': '4', 'r': '7', 'c': '9',
    'k': '30', 'd': '31', 'n': '32', 'w': '33', 'e': '34', 'a': '35', 'y': '36', 'w': '37',
    '0': '40', '1': '41', '2': '42', '3': '43', '4': '44', '5': '45', '6': '46', '7': '47',
}

ANSI_RESET = {
    'center': '22',
    'b': '22', 'i': '23', 'u': '24', 'r': '27', 'c': '29',
    'k': '39', 'd': '39', 'n': '39', 'w': '39', 'e': '39', 'a': '39', 'y': '39', 'w': '39',
    '0': '49', '1': '49', '2': '49', '3': '49', '4': '49', '5': '49', '6': '49', '7': '49',
}

def to_ansi(text):
    text = re.sub(r' \.\|.*$', '', text, flags=re.MULTILINE)
    sorted_tags = sorted(ANSI_ON.keys(), key=len, reverse=True)
    tag_pattern = '|'.join(map(re.escape, sorted_tags))
   
    def repl_on(match): return f"\033[{ANSI_ON[match.group(1)]}m"
    def repl_reset(match): return f"\033[{ANSI_RESET[match.group(1)]}m"

    text = re.sub(rf' ,({tag_pattern})', repl_on, text)
    text = re.sub(rf' \.({tag_pattern})', repl_reset, text)
    text = re.sub(r' ,[" ](.*?) \.[" ]', r'\1', text, flags=re.DOTALL)
    text = re.sub(r' [,.][0-9a-zA-Z-]+(?:bullet|count|-)?\.', '', text)
    text = re.sub(r' \.\.[^ ]+\.\.', '', text)
    return text

def to_html(text):
    html_on = {
        'center': '<div style="text-align: center;">',
        'b': '<b>', 'i': '<i>', 'u': '<u>', 'c': '<del>',
        'r': '<span style="filter:invert(1);">',
        'k': '<span style="color:black;">', 'd': '<span style="color:red;">',
        'n': '<span style="color:green;">', 'w': '<span style="color:yellow;">',
        'e': '<span style="color:blue;">', 'a': '<span style="color:magenta;">',
        'y': '<span style="color:cyan;">', 'w': '<span style="color:white;">',
        '0': '<span style="background-color:black;">', '1': '<span style="background-color:red;">',
        '2': '<span style="background-color:green;">', '3': '<span style="background-color:yellow;">',
        '4': '<span style="background-color:blue;">', '5': '<span style="background-color:magenta;">',
        '6': '<span style="background-color:cyan;">', '7': '<span style="background-color:white;">',
    }
   
    # Image support (BAR & BOX)
    text = re.sub(r' ,,jpgBAR,,([^|]+)\|([^.]+)\.\.', r'<div style="margin: 20px 0; text-align: center;"><img src="\1" style="max-width:100%; height:auto;"><br><small style="color:#666;">\2</small></div>', text)
    text = re.sub(r' ,,jpgBOX,,([^|]+)\|([^.]+)\.\.', r'<div style="margin: 20px 0; overflow: hidden;"><img src="\1" style="float: left; margin: 0 20px 10px 0; max-width: 40%; height:auto;">\2</div>', text)
   
    text = re.sub(r' \.\|(.*)$', r'<!-- \1 -->', text, flags=re.MULTILINE)
    text = re.sub(r' ,\.#([^|]+)\|([^,]+),,', r'<a href="#\1">\2</a>', text)
    text = re.sub(r' ,\.([^|]+)\|([^\.]+)\.\.', r'<a href="\1">\2</a>', text)
   
    for char in sorted(html_on.keys(), key=len, reverse=True):
        tag = html_on[char]
        text = text.replace(f' ,{char}', tag)
        if char == 'center': text = text.replace(f' .{char}', '</div>')
        else: text = text.replace(f' .{char}', f'</{char}>' if char in ['b', 'i', 'u', 'c'] else '</span>')
           
    text = re.sub(r' [,.][0-9a-zA-Z-]+(?:bullet|count|-)?\.', lambda m: f"<!-- SXT_LAYOUT_RESERVED: {m.group(0)} -->", text)
    body_content = text.replace('\n', '<br>\n')
   
    css_styles = """<style>
        :root { --bg-color: #fdfdfd; --text-color: #222222; --link-color: #0066cc; --font-stack: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        @media (prefers-color-scheme: dark) { :root { --bg-color: #16161a; --text-color: #e4e4e7; --link-color: #4da6ff; } }
        body { font-family: var(--font-stack); background-color: var(--bg-color); color: var(--text-color); line-height: 1.6; max-width: 800px; margin: 40px auto; padding: 0 20px; word-wrap: break-word; }
        a { color: var(--link-color); text-decoration: none; } a:hover { text-decoration: underline; }
    </style>"""

    return f"""<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SXT Document</title>
    {css_styles}
</head>
<body>
{body_content}
</body>
</html>"""

if __name__ == '__main__':
    if len(sys.argv) < 3 or sys.argv[1] not in ['--ansi', '--html']:
        print("Usage: python3 sxt3of3.py [--ansi|--html] file.sxt")
        sys.exit(1)
    mode, filename = sys.argv[1], sys.argv[2]
    try:
        with open(filename, 'r', encoding='utf-8') as f: content = f.read()
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found.")
        sys.exit(1)
    print(to_ansi(content) if mode == '--ansi' else to_html(content), end='')
Dpupbuster:~/0/home/f# ┌─( root ) » { ~/0/home/f }


oui

  • Jr. Member
  • **
    • Messages: 74
ce filtre couvre la majeure partie (en pratique) du code HTML4 et des extensions qui y ont toujours fait défaut (maniement des pages).

il n'utilise (et ne "consomme" en en interdisant l'utilisation) aucun signe spécial, est compatible avec pratiquement toute langue et est EXTRÊMEMENT compact (essentiellement soit un intervale suivi d'une virgule (logique: la phrase continue) ou d'un point (on ferme une action en cours) et d'un seul signe de l'alphabet latin (sauf peu de choses nécessitant impérativement elles-mêmes des extentions, comme les liens).

python3, cat et less suffisent pour créer des fichiers textes ANSI (couleurs, gras, italique, souligné, barré etc.) visibles en simple mode terminal!

mes scripts permettent de manier aussi le html4 et, avec w3m, de revenir en une tseconde à du texte pur (donc on sauvegarde de préférence au nouveau format *.sxt !):

w3m mon_sxt > retour_a.txt

quoi de plus simple!
 
la ruse: dans presque toutes les langues du monde, les virgules et les points sont attachés au texte qu'ils suivent! l'intervale inséré pour provoquer l'erreur orthographique, est exploitée donc comme délimitateur!

rien de plus simple et quasi rien de plus court!
« Modifié: septembre 03, 2026, 03:29:44 pm par oui »


oui

  • Jr. Member
  • **
    • Messages: 74
# =============================================l================================
# SXT MASTER CONTROL CENTER  (adapter la ligne 3, le filtre doit s'appeler python3 sxt3of3.py !)
# =============================================================================
FILE ?= welcome.sxt
START ?= 1
SIZE ?= 1000

view:
   @python3 sxt3of3.py --ansi $(FILE) | less -R

index:
   @echo "=== SXT NAVIGATIONS-INDEX (Suchhilfe für Schiebefenster) ==="
   @echo "----------------------------------------------------------------"
   @grep -n -E " \.\.[^ ]+\.\.| ,,[0-9a-zA-Z]{3}\|[0-9a-zA-Z]{5}\.\." $(FILE) || echo "Keine Anker gefunden."

slice:
   @./sxt2of3.sh --slice $(FILE) $(START) $(SIZE)

join:
   @./sxt2of3.sh --join $(FILE)

clean-txt:
   @python3 -c "import re; f=open('$(FILE)','r'); t=f.read(); f.close(); \
   t=re.sub(r' [,.][a-z0-7]+', '', t); \
   t=re.sub(r' [,.][0-9a-zA-Z-]+(?:bullet|count|-)?\.', '', t); \
   t=re.sub(r' \.\.[^ ]+\.\.', '', t); \
   t=re.sub(r' ,,[0-9a-zA-Z]{3}\|[0-9a-zA-Z]{5}\.\.', '', t); \
   t=re.sub(r' \.\|.*$$', '', t, flags=re.MULTILINE); \
   t=re.sub(r' [,.][\" ](.*?) \.[\" ]', r'\1', t, flags=re.DOTALL); \
   print(t)" > $(FILE:.sxt=).txt && \
   echo "Erfolgreich! Roh-Textdatei generiert."

html:
   @python3 sxt3of3.py --html $(FILE) > $(FILE:.sxt=).html
   @echo "Erfolgreich! '$(FILE:.sxt=).html' wurde generiert."
   @if [ "$(OPEN)" = "1" ]; then \
      xdg-open $(FILE:.sxt=).html 2>/dev/null || echo "Browser konnte nicht automatisch geöffnet werden."; \
   fi


oui

  • Jr. Member
  • **
    • Messages: 74
# -----------------------------------------------------------------------------
# File 2: sxt2of3.sh (Sliding-Window Bash Engine)
# -----------------------------------------------------------------------------
cat << 'EOF' > sxt2of3.sh
#!/bin/bash
set -e

if [ "$1" == "--slice" ] && [ $# -eq 4 ]; then
    DATEI="$2"
    START_ZEILE=$3
    ANZAHL_ZEILEN=$4
    if [ ! -f "$DATEI" ]; then echo "Error: File '$DATEI' missing."; exit 1; fi
    KOPF_ENDE=$((START_ZEILE - 1))
    FUSS_START=$((START_ZEILE + ANZAHL_ZEILEN))
    echo "[sxt-slice] Isolating chunk from line $START_ZEILE..."
    head -n $KOPF_ENDE "$DATEI" > "${DATEI}.kopf"
    tail -n +"$START_ZEILE" "$DATEI" | head -n $ANZAHL_ZEILEN > "${DATEI}.edit"
    tail -n +"$FUSS_START" "$DATEI" > "${DATEI}.fuss"
    echo "Done! Edit '${DATEI}.edit'. Apply join via: $0 --join $DATEI"
elif [ "$1" == "--join" ] && [ $# -eq 2 ]; then
    DATEI="$2"
    if [ ! -f "${DATEI}.kopf" ] || [ ! -f "${DATEI}.edit" ] || [ ! -f "${DATEI}.fuss" ]; then
        echo "Error: Fragment pieces missing for reconstruction!"; exit 1
    fi
    echo "[sxt-slice] Seamlessly merging fragments back..."
    cat "${DATEI}.kopf" "${DATEI}.edit" "${DATEI}.fuss" > "$DATEI"
    rm "${DATEI}.kopf" "${DATEI}.edit" "${DATEI}.fuss"
    echo "Success! '$DATEI' fully consolidated."
else
    echo "Usage:"
    echo "  Isolate: $0 --slice <file.sxt> <start_line> <line_count>"
    echo "  Merge:   $0 --join <file.sxt>"
    exit 1
fi
EOF



oui

  • Jr. Member
  • **
    • Messages: 74
# -----------------------------------------------------------------------------
# File 4: welcome.sxt (Specification Document)
# -----------------------------------------------------------------------------
cat << 'EOF' > welcome.sxt
 ..welcome_anchor|Welcome to SXT.. .| Anker fuer dieses Dokument
 ,,20260726|20260726.. .| Erstellungs- und Änderungsdatum

 ,center Welcome to Smart teXT (SXT) ,b — Specification & Test File .b .center

 This file demonstrates the grammatical rules and the core features of SXT.

 =============================================================================
 1. THE SPACING GRAMMAR (Do's and Don'ts for Whitespace)
 =============================================================================
 In SXT, the precise placement of spaces determines whether a text block is valid:

  • papipo pupapo, pipapo etc.         -> YES! (Valid comma separation)
  • papipo pupapo,pipapo etc.          -> NO!  (Missing space after comma)
  • papipo pupapo , pipapo etc.        -> NO!  (Illegal space before comma)
  • papipo pupapo. Pipapo etc.         -> YES! (Valid sentence structure)
  • papipo pupapo. 5 pipapo etc.       -> YES! (Valid sentence with number)
  • papipo pupapo. pipapo etc.         -> YOU CAN! (Valid lowercase start)
  • papipo pupapo.Pipapo etc.          -> NO!  (Missing space after dot)
  • papipo pupapo.5 pipapo etc.        -> NO!  (Missing space after dot before digit)
  • papipo pupapo . pipapo etc.        -> NO!  (Illegal space before dot)

Verwende Code mit Vorsicht.
• papipo pupapo.pipapo etc. -> NO! (No spaces around dot at all)
NOTE: Structures like " ,_xxx" or " ._xxx" are STRIKT RESERVED FOR CODE!
=============================================================================
2. FORMATTING CODES (Inline ANSI & HTML)
Use a leading space followed by a comma to trigger formatting, and a space
followed by a dot to reset it.
• This is ,b bold text .b and this is regular.
• This is ,i italic text .i and this is regular.
• This is ,u underlined text .u and this is regular.
• This is ,r reverse/inverted text .r and this is regular.
• This is ,c crossed out text .c and this is regular.
Foreground Colors:
• ,k Black text .k ,d Red text .d ,n Green text .n ,w Yellow text .w
• ,e Blue text .e ,a Magenta .a ,y Cyan text .y ,w White text .w
Background Colors:
• ,0 Black BG .0 ,1 Red BG .1 ,2 Green BG .2 ,3 Yellow BG .3
• ,4 Blue BG .4 ,5 Magenta .5 ,6 Cyan BG .6 ,7 White BG .7
Full Page Background Command:
• ,p (Reserved for master page background color definition)
=============================================================================
3. HYPERLINKS & NAVIGATION
• Internal Jump: ,.#welcome_anchor|Go to top,, (Link within this file)
• External Link: ,.https://example.com|Visit Example Website.. (Far link)
• Milestone Mark: ..5000.. (5000 character/word line metric counter)
=============================================================================
4. ADVANCED LAYOUT ENGINE (Reserved Tags)
These structural commands control margins, lists, and numbering sequences:
• Page Numbering: ,page. | ,101page.begin | .page.
• Left Margins: ,010randL. | ,010randLbullet. | ,010randLcount. | ,010randL-.
• Left Resets: .010randL. | .010randLbullet. | .010randLcount. | .010randL-.
• Right Margins: ,010randR. | ,010randRbullet. | ,010randRcount. | ,010randR-.
• Right Resets: .010randR. | .010randRbullet. | .010randRcount. | .010randR-.
=============================================================================
5. ESCAPED FREE TEXT & RAW CODE BLOCKS
• Interpretive Free Text:
," ,b This bold works .b but other syntax rules inside are relaxed ."
• Strict Literal Code:
." This content is preserved exactly as written ."
EOF


oui

  • Jr. Member
  • **
    • Messages: 74
à ce stade les 3 premiers fichiers doivent être présents dans le répertoire où se trouve le ou les fichiers concernés! dans humbleOS pour lequel ce traitement de texte utilisable (excepté les sauts vers les ancres et dates, là il faut un peu plus) en console même pure et même sans éditeur, navigateur ou autres, mais seulement cat et less même dans un fichier texte de longueur gigantesque (la découpe a lieu à l'aide de l'un des 3 scripts et cat suffit!), il est intégré une fois pour toute car c'est son système. Mais en portant les 3 scripts (et la doc si on ne la maîtrise pas encore), on peut l'utiliser partout! Il est libre mais ne doit pas être modifié sinon c'est le chaos!