Spaces:
Running
Running
File size: 36,590 Bytes
b7d8ac9 f17b1b6 e2b402b 58633fe 34f2fda b7d8ac9 58633fe fcb5c90 58633fe 18e888f f17b1b6 b7d8ac9 c40dca1 f17b1b6 f59c14c f17b1b6 b7d8ac9 c40dca1 b7d8ac9 f59c14c b7d8ac9 c40dca1 b7d8ac9 f59c14c b7d8ac9 c40dca1 e2b402b e6742d7 e2b402b e6742d7 e2b402b c40dca1 e2b402b e6742d7 58633fe fcb5c90 58633fe c40dca1 58633fe fcb5c90 34f2fda b7d8ac9 58633fe b7d8ac9 fcb5c90 b7d8ac9 58633fe b7d8ac9 58633fe b7d8ac9 58633fe b7d8ac9 58633fe b7d8ac9 34f2fda b7d8ac9 58633fe 72c62aa 58633fe 72c62aa 58633fe 72c62aa 58633fe 72c62aa 58633fe 72c62aa 58633fe c40dca1 58633fe c40dca1 58633fe c40dca1 72c62aa c40dca1 58633fe c40dca1 58633fe 72c62aa 58633fe 72c62aa 58633fe 72c62aa 58633fe 585f5d0 e2b402b b7d8ac9 58633fe 72c62aa b7d8ac9 58633fe 72c62aa b7d8ac9 72c62aa b7d8ac9 72c62aa b7d8ac9 e2b402b 58633fe 72c62aa 58633fe b7d8ac9 e2b402b 58633fe 72c62aa e2b402b 72c62aa e2b402b 72c62aa e2b402b 58633fe 72c62aa 58633fe b7d8ac9 e2b402b 58633fe 72c62aa 58633fe b7d8ac9 e2b402b 58633fe c40dca1 58633fe 585f5d0 fcb5c90 c9b3fde fcb5c90 c9b3fde fcb5c90 c9b3fde fcb5c90 c9b3fde fcb5c90 c9b3fde fcb5c90 c9b3fde fcb5c90 34f2fda fcb5c90 d0f80bb fcb5c90 58633fe 34f2fda 58633fe c40dca1 58633fe 72c62aa 58633fe c40dca1 58633fe fcb5c90 58633fe fcb5c90 58633fe fcb5c90 58633fe fcb5c90 58633fe 72c62aa fcb5c90 34f2fda c9b3fde fcb5c90 b7d8ac9 d0f80bb 58633fe 585f5d0 58633fe 585f5d0 58633fe f59c14c 58633fe b7d8ac9 58633fe c9b3fde f282d19 58633fe 34f2fda 58633fe 2ed4eef 34f2fda 2ed4eef 34f2fda c40dca1 34f2fda 2ed4eef c40dca1 34f2fda fcb5c90 34f2fda 2ed4eef 58633fe c9b3fde 58633fe c9b3fde 58633fe b7d8ac9 58633fe fcb5c90 58633fe fcb5c90 58633fe b7d8ac9 58633fe fcb5c90 b7d8ac9 58633fe e2b402b 58633fe 72c62aa 58633fe 72c62aa 58633fe 72c62aa 58633fe c9b3fde b7d8ac9 58633fe c40dca1 fcb5c90 58633fe fcb5c90 58633fe fcb5c90 b7d8ac9 |
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 |
import streamlit as st
import subprocess
import tempfile
import base64
from pathlib import Path
import os
import shutil
import io
from PIL import Image
import fitz # PyMuPDF
import time
import re
from streamlit_monaco import st_monaco
# Set page configuration
st.set_page_config(
page_title="Professional LaTeX Editor",
page_icon="π",
layout="wide",
initial_sidebar_state="collapsed"
)
# Check if pdflatex is available
def is_pdflatex_installed():
return shutil.which("pdflatex") is not None
# Function to convert LaTeX to PDF
def latex_to_pdf(latex_code):
# Check if pdflatex is installed
if not is_pdflatex_installed():
st.error("pdflatex not found. Debug info:")
st.code(f"PATH: {os.environ.get('PATH')}")
result = subprocess.run(["which", "pdflatex"], capture_output=True, text=True)
st.code(f"which pdflatex: {result.stdout} {result.stderr}")
return None, "", "Error: pdflatex is not installed or not in PATH."
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
tex_file = temp_path / "document.tex"
pdf_file = temp_path / "document.pdf"
# Write LaTeX code to file
with open(tex_file, "w") as f:
f.write(latex_code)
try:
# Run pdflatex to compile the LaTeX file
process = subprocess.run(
["pdflatex", "-interaction=nonstopmode", "-output-directory", temp_dir, str(tex_file)],
capture_output=True,
text=True
)
# Check if PDF was created
if pdf_file.exists():
with open(pdf_file, "rb") as file:
pdf_data = file.read()
return pdf_data, process.stdout, process.stderr
else:
return None, process.stdout, process.stderr
except Exception as e:
return None, "", str(e)
# Function to create download link for PDF
def get_download_link(pdf_data, filename="document.pdf"):
b64_pdf = base64.b64encode(pdf_data).decode()
return f'<a href="data:application/pdf;base64,{b64_pdf}" download="{filename}" class="download-button">Download PDF</a>'
# Convert PDF to image for preview
def render_pdf_preview(pdf_data):
if not pdf_data:
return None
try:
# Create a file-like object from the PDF data
pdf_stream = io.BytesIO(pdf_data)
# Open PDF with PyMuPDF (fitz)
pdf_document = fitz.open(stream=pdf_stream, filetype="pdf")
# Render pages as images
images = []
for page_num in range(min(3, len(pdf_document))): # Preview first 3 pages max
page = pdf_document.load_page(page_num)
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2)) # Zoom factor 2 for better resolution
img_data = pix.tobytes("png")
img = Image.open(io.BytesIO(img_data))
images.append(img)
pdf_document.close()
return images
except Exception as e:
st.error(f"Error rendering PDF preview: {str(e)}")
return None
# Function to parse LaTeX errors
def parse_latex_errors(output):
errors = []
warnings = []
# Match errors
error_matches = re.finditer(r'! (.+?)\.[\r\n]', output)
for match in error_matches:
errors.append(match.group(1))
# Match warnings
warning_matches = re.finditer(r'LaTeX Warning: (.+?)[\r\n]', output)
for match in warning_matches:
warnings.append(match.group(1))
return errors, warnings
# Function to extract document structure
def extract_document_structure(latex_code):
structure = []
# Ensure latex_code is a string
if latex_code is None:
return structure
if not isinstance(latex_code, str):
try:
latex_code = str(latex_code)
except:
return structure
# Find sections, subsections, etc.
section_pattern = r'\\(section|subsection|subsubsection|chapter|part)\{([^}]+)\}'
matches = re.finditer(section_pattern, latex_code)
for match in matches:
section_type = match.group(1)
section_title = match.group(2)
# Calculate indentation level based on section type
level = {
'part': 0,
'chapter': 1,
'section': 2,
'subsection': 3,
'subsubsection': 4
}.get(section_type, 0)
structure.append({
'type': section_type,
'title': section_title,
'level': level,
'position': match.start() # Position in document for navigation
})
return structure
# Function to analyze LaTeX packages
def analyze_packages(latex_code):
if not isinstance(latex_code, str):
try:
latex_code = str(latex_code)
except:
return []
# Find all package imports
package_pattern = r'\\usepackage(?:\[.*?\])?\{([^}]+)\}'
matches = re.finditer(package_pattern, latex_code)
packages = []
for match in matches:
package_name = match.group(1)
packages.append(package_name)
return packages
# Function to find all environments in the document
def find_environments(latex_code):
if not isinstance(latex_code, str):
try:
latex_code = str(latex_code)
except:
return []
# Find all environments (begin-end pairs)
env_pattern = r'\\begin\{([^}]+)\}(.*?)\\end\{\1\}'
matches = re.finditer(env_pattern, latex_code, re.DOTALL)
environments = []
for match in matches:
env_name = match.group(1)
environments.append({
'name': env_name,
'position': match.start(),
'content': match.group(2)
})
return environments
# Define LaTeX code snippets for toolbar actions
latex_snippets = {
"bold": "\\textbf{$0}",
"italic": "\\textit{$0}",
"math_inline": "$\n$0\n$",
"section": "\\section{$0}",
"subsection": "\\subsection{$0}",
"itemize": "\\begin{itemize}\n\t\\item $0\n\\end{itemize}",
"enumerate": "\\begin{enumerate}\n\t\\item $0\n\\end{enumerate}",
"equation": "\\begin{equation}\n\t$0\n\\end{equation}",
"align": "\\begin{align}\n\t$0\n\\end{align}",
"figure": "\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=0.8\\textwidth]{$0}\n\t\\caption{Caption}\n\t\\label{fig:label}\n\\end{figure}",
"table": "\\begin{table}[h]\n\t\\centering\n\t\\begin{tabular}{ccc}\n\t\t$0 & B & C \\\\\n\t\t1 & 2 & 3 \\\\\n\t\\end{tabular}\n\t\\caption{Caption}\n\t\\label{tab:label}\n\\end{table}",
"fraction": "\\frac{$0}{denominator}",
"sqrt": "\\sqrt{$0}",
"package": "\\usepackage{$0}"
}
# Default LaTeX template
default_template = r"""\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{xcolor}
\title{Professional \LaTeX{} Document}
\author{Your Name}
\date{\today}
\begin{document}
\maketitle
\section{Introduction}
This is the introduction to your document. You can write your content here.
\section{Mathematical Expressions}
\subsection{Equations}
The famous Einstein's equation:
\begin{equation}
E = mc^2
\end{equation}
The quadratic formula:
\begin{equation}
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
\end{equation}
\subsection{Calculus}
An integral example:
\begin{equation}
\int_{0}^{\pi} \sin(x) \, dx = 2
\end{equation}
\section{Lists and Items}
\subsection{Bullet Points}
\begin{itemize}
\item First item with \textbf{bold text}
\item Second item with \textit{italic text}
\item Third item with \textcolor{blue}{colored text}
\end{itemize}
\subsection{Numbered List}
\begin{enumerate}
\item First step
\item Second step
\item Third step
\end{enumerate}
\section{Tables}
\begin{table}[h]
\centering
\begin{tabular}{|c|c|c|}
\hline
Cell 1 & Cell 2 & Cell 3 \\
\hline
Data 1 & Data 2 & Data 3 \\
\hline
\end{tabular}
\caption{A simple table}
\label{tab:simple}
\end{table}
\section{Figures}
You can include figures using the following syntax:
% \begin{figure}[h]
% \centering
% \includegraphics[width=0.7\textwidth]{example-image}
% \caption{Example figure}
% \label{fig:example}
% \end{figure}
\section{Citations}
You can cite references using the \verb|\cite{}| command \cite{example}.
\section{Cross-References}
You can reference sections, figures, and tables using the \verb|\ref{}| command.
For example, see Table~\ref{tab:simple}.
\section{Conclusion}
Your conclusion here.
% Sample bibliography entry
\begin{thebibliography}{9}
\bibitem{example} Author, A. (2023). \textit{Title of the Work}. Publisher.
\end{thebibliography}
\end{document}
"""
# Enhanced VSCode-like styling
st.markdown("""
<style>
/* Base theming - VS Code inspired */
html, body, .stApp {
background-color: #1e1e1e;
color: #cccccc;
}
/* Streamlit component overrides */
.stButton button {
background-color: #0e639c;
color: white;
border: none;
padding: 0.4rem 1rem;
font-size: 0.8rem;
border-radius: 2px;
}
.stButton button:hover {
background-color: #1177bb;
}
/* Editor tab bar */
.tab-bar {
display: flex;
background-color: #252526;
border-bottom: 1px solid #2d2d2d;
padding: 0;
height: 36px;
}
.tab {
padding: 0 15px;
height: 36px;
line-height: 36px;
background-color: #2d2d2d;
color: white;
border-right: 1px solid #252526;
font-size: 13px;
display: flex;
align-items: center;
}
.tab.active {
background-color: #1e1e1e;
border-top: 1px solid #0e639c;
}
.tab-icon {
margin-right: 6px;
opacity: 0.8;
}
/* Status bar */
.status-bar {
display: flex;
justify-content: space-between;
background-color: #007acc;
color: white;
padding: 3px 10px;
font-size: 12px;
}
/* Toolbar */
.toolbar {
background-color: #2d2d2d;
padding: 5px;
display: flex;
gap: 5px;
align-items: center;
}
.toolbar-button {
background-color: transparent;
border: none;
color: #cccccc;
padding: 5px;
cursor: pointer;
border-radius: 2px;
}
.toolbar-button:hover {
background-color: #3c3c3c;
}
.toolbar-separator {
width: 1px;
height: 20px;
background-color: #555;
margin: 0 5px;
}
/* Terminal/console styling */
.terminal {
background-color: #1e1e1e;
color: #cccccc;
padding: 10px;
font-family: 'Cascadia Code', 'Consolas', monospace;
font-size: 13px;
border-top: 1px solid #2d2d2d;
overflow-y: auto;
max-height: 200px;
}
.terminal-error {
color: #f48771;
}
.terminal-warning {
color: #cca700;
}
/* Outline view */
.outline-view {
background-color: #252526;
border: 1px solid #2d2d2d;
border-radius: 4px;
margin-top: 10px;
max-height: 400px;
overflow-y: auto;
}
.outline-item {
padding: 5px 10px;
cursor: pointer;
display: flex;
align-items: center;
}
.outline-item:hover {
background-color: #2a2d2e;
}
.outline-item-text {
margin-left: 5px;
}
/* Download button styling */
.download-button {
display: inline-block;
padding: 8px 16px;
background-color: #3d995e;
color: white !important;
text-align: center;
text-decoration: none;
font-size: 13px;
border-radius: 2px;
transition: background-color 0.3s;
margin-top: 10px;
font-weight: normal;
}
.download-button:hover {
background-color: #4eb772;
}
/* PDF preview area */
.preview-container {
background-color: #252526;
border: 1px solid #2d2d2d;
border-radius: 4px;
padding: 15px;
margin-top: 10px;
}
/* Control panel */
.control-panel {
background-color: #252526;
border: 1px solid #2d2d2d;
border-radius: 4px;
padding: 10px;
margin-bottom: 10px;
}
.button-group {
display: flex;
gap: 5px;
}
/* Messages */
.stInfo {
background-color: #063b49;
color: #bbbbbb;
border: 1px solid #145b6c;
}
.stError {
background-color: #5a1d1d;
color: #bbbbbb;
border: 1px solid #6c2b2b;
}
.stSuccess {
background-color: #143d27;
color: #bbbbbb;
border: 1px solid #1e5a3a;
}
/* Hide Streamlit footer and menu */
footer, header {display: none !important;}
#MainMenu {visibility: hidden;}
/* Custom tabs */
.stTabs [data-baseweb="tab-list"] {
background-color: #2d2d2d;
gap: 0px !important;
}
.stTabs [data-baseweb="tab"] {
background-color: #252526;
color: #cccccc;
border-radius: 0;
border-right: 1px solid #1e1e1e;
padding: 0px 16px;
height: 36px;
}
.stTabs [aria-selected="true"] {
background-color: #1e1e1e;
border-top: 2px solid #007acc !important;
color: white;
}
/* Problems panel */
.problems-panel {
background-color: #252526;
border: 1px solid #2d2d2d;
border-radius: 4px;
margin-top: 10px;
padding: 0;
}
.problems-header {
background-color: #2d2d2d;
padding: 5px 10px;
font-weight: bold;
font-size: 13px;
}
.problem-item {
padding: 8px 10px;
border-bottom: 1px solid #2d2d2d;
display: flex;
align-items: flex-start;
}
.problem-icon {
margin-right: 8px;
flex-shrink: 0;
}
.problem-message {
flex-grow: 1;
}
.problem-location {
font-size: 12px;
color: #8a8a8a;
margin-top: 2px;
}
/* Document info panel */
.document-info {
background-color: #252526;
border: 1px solid #2d2d2d;
border-radius: 4px;
padding: 10px;
margin-top: 10px;
font-size: 13px;
}
.info-row {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
border-bottom: 1px solid #333;
padding-bottom: 5px;
}
.info-label {
font-weight: bold;
color: #8a8a8a;
}
.info-value {
text-align: right;
}
/* Packages panel */
.packages-panel {
background-color: #252526;
border: 1px solid #2d2d2d;
border-radius: 4px;
margin-top: 10px;
padding: 0;
}
.packages-header {
background-color: #2d2d2d;
padding: 5px 10px;
font-weight: bold;
font-size: 13px;
}
.package-item {
padding: 5px 10px;
border-bottom: 1px solid #2d2d2d;
display: flex;
align-items: center;
}
.package-name {
color: #dcdcaa;
margin-right: 10px;
font-family: monospace;
}
/* Environment analyzer */
.environments-panel {
background-color: #252526;
border: 1px solid #2d2d2d;
border-radius: 4px;
margin-top: 10px;
padding: 0;
}
.environments-header {
background-color: #2d2d2d;
padding: 5px 10px;
font-weight: bold;
font-size: 13px;
}
.environment-item {
padding: 5px 10px;
border-bottom: 1px solid #2d2d2d;
}
.environment-name {
color: #4ec9b0;
font-family: monospace;
font-weight: bold;
}
/* Simple keyboard shortcut */
.shortcut-item {
background-color: #252526;
border: 1px solid #2d2d2d;
border-radius: 4px;
padding: 5px 10px;
margin-top: 10px;
font-size: 13px;
display: flex;
align-items: center;
}
.shortcut-key {
background-color: #3c3c3c;
padding: 2px 8px;
border-radius: 3px;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
font-size: 12px;
margin-right: 10px;
}
/* Monaco editor container */
.monaco-editor-container {
border: 1px solid #2d2d2d;
border-radius: 4px;
overflow: hidden;
}
</style>
""", unsafe_allow_html=True)
# VS Code-style editor tabs
def render_editor_tabs(active_tab="document.tex"):
tab_html = f"""
<div class="tab-bar">
<div class="tab active">
<span class="tab-icon">π</span> {active_tab}
</div>
</div>
"""
st.markdown(tab_html, unsafe_allow_html=True)
# VS Code-style status bar
def render_status_bar():
status_html = """
<div class="status-bar">
<span>LaTeX</span>
<span>Line: 1, Col: 1</span>
<span>UTF-8</span>
</div>
"""
st.markdown(status_html, unsafe_allow_html=True)
# VS Code-style toolbar buttons
def render_toolbar_buttons():
col1, col2, col3, col4, col5 = st.columns([1, 1, 1, 1, 5])
with col1:
st.button("Bold", key="btn_bold", help="Insert bold text")
st.button("Italic", key="btn_italic", help="Insert italic text")
with col2:
st.button("Section", key="btn_section", help="Insert section heading")
st.button("Subsection", key="btn_subsection", help="Insert subsection heading")
with col3:
st.button("Itemize", key="btn_itemize", help="Insert bulleted list")
st.button("Enumerate", key="btn_enumerate", help="Insert numbered list")
with col4:
st.button("Equation", key="btn_equation", help="Insert equation environment")
st.button("Table", key="btn_table", help="Insert table environment")
# Render a document outline based on section hierarchy
def render_document_outline(structure):
if not structure:
return
st.markdown('<div class="outline-view">', unsafe_allow_html=True)
for item in structure:
level = item['level']
title = item['title']
type_icon = {
'part': 'π',
'chapter': 'π',
'section': 'π',
'subsection': 'π',
'subsubsection': 'π'
}.get(item['type'], 'π')
# Indent based on level
indent = " " * (level * 4)
st.markdown(
f'<div class="outline-item">'
f'<span>{type_icon}</span>'
f'<span class="outline-item-text">{indent}{title}</span>'
f'</div>',
unsafe_allow_html=True
)
st.markdown('</div>', unsafe_allow_html=True)
# Render errors and warnings in a VS Code style
def render_problems(errors, warnings):
if not errors and not warnings:
return
st.markdown('<div class="problems-panel">', unsafe_allow_html=True)
st.markdown('<div class="problems-header">Problems</div>', unsafe_allow_html=True)
# Show errors
for error in errors:
st.markdown(
f'<div class="problem-item">'
f'<div class="problem-icon">β</div>'
f'<div class="problem-message">{error}'
f'<div class="problem-location">document.tex</div>'
f'</div></div>',
unsafe_allow_html=True
)
# Show warnings
for warning in warnings:
st.markdown(
f'<div class="problem-item">'
f'<div class="problem-icon">β οΈ</div>'
f'<div class="problem-message">{warning}'
f'<div class="problem-location">document.tex</div>'
f'</div></div>',
unsafe_allow_html=True
)
st.markdown('</div>', unsafe_allow_html=True)
# Render document information panel
def render_document_info(latex_code):
# Ensure latex_code is a string
if not isinstance(latex_code, str):
try:
latex_code = str(latex_code)
except:
latex_code = ""
# Calculate basic document stats
word_count = len(re.findall(r'\b\w+\b', latex_code))
char_count = len(latex_code)
line_count = len(latex_code.split('\n'))
# Find document class
doc_class_match = re.search(r'\\documentclass(?:\[.*?\])?\{(.*?)\}', latex_code)
doc_class = doc_class_match.group(1) if doc_class_match else "unknown"
# Count equations
equation_count = len(re.findall(r'\\begin\{equation', latex_code))
align_count = len(re.findall(r'\\begin\{align', latex_code))
# Count figures
figure_count = len(re.findall(r'\\begin\{figure', latex_code))
# Count tables
table_count = len(re.findall(r'\\begin\{table', latex_code))
# Count custom command definitions
command_count = len(re.findall(r'\\newcommand', latex_code))
# Count references
ref_count = len(re.findall(r'\\ref\{', latex_code))
cite_count = len(re.findall(r'\\cite\{', latex_code))
# Render the info panel
st.markdown('<div class="document-info">', unsafe_allow_html=True)
info_rows = [
("Document Class", doc_class),
("Word Count", word_count),
("Character Count", char_count),
("Line Count", line_count),
("Equations", equation_count),
("Align Environments", align_count),
("Figures", figure_count),
("Tables", table_count),
("Custom Commands", command_count),
("References", ref_count),
("Citations", cite_count)
]
for label, value in info_rows:
st.markdown(
f'<div class="info-row">'
f'<span class="info-label">{label}:</span>'
f'<span class="info-value">{value}</span>'
f'</div>',
unsafe_allow_html=True
)
st.markdown('</div>', unsafe_allow_html=True)
# Display the packages used in the document
def render_packages_panel(packages):
if not packages:
return
st.markdown('<div class="packages-panel">', unsafe_allow_html=True)
st.markdown('<div class="packages-header">Imported Packages</div>', unsafe_allow_html=True)
for package in packages:
st.markdown(
f'<div class="package-item">'
f'<span class="package-name">\\usepackage{{{package}}}</span>'
f'</div>',
unsafe_allow_html=True
)
st.markdown('</div>', unsafe_allow_html=True)
# Display environments in the document
def render_environments_panel(environments):
if not environments:
return
st.markdown('<div class="environments-panel">', unsafe_allow_html=True)
st.markdown('<div class="environments-header">Environments</div>', unsafe_allow_html=True)
# Count environment types
env_counts = {}
for env in environments:
env_name = env['name']
if env_name in env_counts:
env_counts[env_name] += 1
else:
env_counts[env_name] = 1
# Display counts
for env_name, count in env_counts.items():
st.markdown(
f'<div class="environment-item">'
f'<span class="environment-name">\\begin{{{env_name}}}</span> - {count} instances'
f'</div>',
unsafe_allow_html=True
)
st.markdown('</div>', unsafe_allow_html=True)
# Display a simple F5 shortcut reminder
def render_f5_shortcut():
st.markdown(
'<div class="shortcut-item">'
'<span class="shortcut-key">F5</span>'
'<span>Press F5 to compile the document</span>'
'</div>',
unsafe_allow_html=True
)
# Main application
def main():
# Initialize session state
if 'latex_code' not in st.session_state:
st.session_state.latex_code = default_template
if 'show_preview' not in st.session_state:
st.session_state.show_preview = False
if 'last_compiled' not in st.session_state:
st.session_state.last_compiled = None
if 'errors' not in st.session_state:
st.session_state.errors = []
if 'warnings' not in st.session_state:
st.session_state.warnings = []
# Check installation status
if not is_pdflatex_installed():
st.warning("β οΈ LaTeX is not installed. The compilation feature will not work.")
# Create main layout
col1, col2 = st.columns([3, 2])
with col1:
# Create tabs for main editing area with VS Code style
editor_tabs = st.tabs(["Editor", "Settings"])
with editor_tabs[0]:
# VS Code-like editor interface
st.markdown('<div class="editor-container">', unsafe_allow_html=True)
# Tab bar
render_editor_tabs()
# Toolbar buttons
render_toolbar_buttons()
# Check for toolbar button clicks
button_clicked = False
snippet_to_insert = ""
if st.session_state.get("btn_bold", False):
snippet_to_insert = latex_snippets["bold"]
button_clicked = True
elif st.session_state.get("btn_italic", False):
snippet_to_insert = latex_snippets["italic"]
button_clicked = True
elif st.session_state.get("btn_section", False):
snippet_to_insert = latex_snippets["section"]
button_clicked = True
elif st.session_state.get("btn_subsection", False):
snippet_to_insert = latex_snippets["subsection"]
button_clicked = True
elif st.session_state.get("btn_itemize", False):
snippet_to_insert = latex_snippets["itemize"]
button_clicked = True
elif st.session_state.get("btn_enumerate", False):
snippet_to_insert = latex_snippets["enumerate"]
button_clicked = True
elif st.session_state.get("btn_equation", False):
snippet_to_insert = latex_snippets["equation"]
button_clicked = True
elif st.session_state.get("btn_table", False):
snippet_to_insert = latex_snippets["table"]
button_clicked = True
# Monaco Editor with LaTeX configuration
# Monaco Editor with LaTeX configuration
st.markdown('<div class="monaco-editor-container">', unsafe_allow_html=True)
# Create Monaco editor component - simplified parameters
latex_code = st_monaco(
value=st.session_state.latex_code,
height=500,
language="latex",
theme="vs-dark",
key="monaco_editor"
)
st.markdown('</div>', unsafe_allow_html=True)
if latex_code is not None:
st.session_state.latex_code = latex_code
# Status bar
render_status_bar()
st.markdown('</div>', unsafe_allow_html=True)
# F5 shortcut reminder
render_f5_shortcut()
# Control buttons with VS Code styling
st.markdown('<div class="button-group">', unsafe_allow_html=True)
compile_btn = st.button("Compile", help="Compile LaTeX to PDF (F5)")
load_template_btn = st.button("Load Template", help="Load default template")
clear_btn = st.button("Clear", help="Clear editor content")
st.markdown('</div>', unsafe_allow_html=True)
# Handle button actions
if compile_btn:
st.session_state.compile_clicked = True
st.session_state.last_compiled = time.time()
if load_template_btn:
st.session_state.latex_code = default_template
st.rerun()
if clear_btn:
st.session_state.latex_code = ""
st.rerun()
with editor_tabs[1]:
st.markdown("<h3>LaTeX Settings</h3>", unsafe_allow_html=True)
st.markdown('<div class="control-panel">', unsafe_allow_html=True)
col_a, col_b = st.columns(2)
with col_a:
st.checkbox("Auto-compile on save", value=False, key="auto_compile")
st.checkbox("Use pdflatex", value=True, key="use_pdflatex")
st.checkbox("Enable BibTeX", value=False, key="use_bibtex")
st.checkbox("Show line numbers", value=True, key="show_line_numbers")
with col_b:
st.selectbox("Document Class",
["article", "report", "book", "letter", "beamer"],
index=0, key="doc_class")
st.selectbox("PDF Engine",
["pdflatex", "xelatex", "lualatex"],
index=0, key="pdf_engine")
st.selectbox("Editor Theme",
["Dark", "Light", "High Contrast"],
index=0, key="editor_theme")
st.markdown('</div>', unsafe_allow_html=True)
with col2:
# Output tabs with VS Code style
output_tabs = st.tabs(["Output", "Outline", "Analysis", "Problems"])
with output_tabs[0]:
# PDF compilation and output
if 'compile_clicked' in st.session_state and st.session_state.compile_clicked:
with st.spinner("Compiling..."):
pdf_data, stdout, stderr = latex_to_pdf(st.session_state.latex_code)
# Parse errors and warnings
errors, warnings = parse_latex_errors(stdout + stderr)
st.session_state.errors = errors
st.session_state.warnings = warnings
if pdf_data:
st.session_state.pdf_data = pdf_data
st.success("Compilation successful")
# Toggle button for preview
if st.button("Toggle Preview", help="Show or hide the PDF preview"):
st.session_state.show_preview = not st.session_state.show_preview
# Download button
st.markdown(get_download_link(pdf_data), unsafe_allow_html=True)
# Display compilation info
if st.session_state.last_compiled:
time_str = time.strftime("%H:%M:%S", time.localtime(st.session_state.last_compiled))
st.info(f"Last compiled: {time_str}")
# Optional preview
if st.session_state.show_preview:
st.markdown('<div class="preview-container">', unsafe_allow_html=True)
preview_images = render_pdf_preview(pdf_data)
if preview_images:
for i, img in enumerate(preview_images):
st.image(img, caption=f"Page {i+1}", use_container_width=True,
output_format="PNG")
st.markdown('</div>', unsafe_allow_html=True)
# Terminal output in collapsible section
with st.expander("Terminal Output"):
st.markdown('<div class="terminal">', unsafe_allow_html=True)
st.text(stdout)
st.markdown('</div>', unsafe_allow_html=True)
st.session_state.compile_clicked = False
else:
st.error("Compilation failed")
st.markdown('<div class="terminal">', unsafe_allow_html=True)
# Highlight errors in output
for line in stderr.split('\n'):
if "error" in line.lower():
st.markdown(f'<span class="terminal-error">{line}</span>', unsafe_allow_html=True)
elif "warning" in line.lower():
st.markdown(f'<span class="terminal-warning">{line}</span>', unsafe_allow_html=True)
else:
st.write(line)
st.markdown('</div>', unsafe_allow_html=True)
st.session_state.compile_clicked = False
# Display previous PDF if available
elif 'pdf_data' in st.session_state and st.session_state.pdf_data:
# Toggle button for preview
if st.button("Toggle Preview", help="Show or hide the PDF preview"):
st.session_state.show_preview = not st.session_state.show_preview
# Download button
st.markdown(get_download_link(st.session_state.pdf_data), unsafe_allow_html=True)
# Display compilation info
if st.session_state.last_compiled:
time_str = time.strftime("%H:%M:%S", time.localtime(st.session_state.last_compiled))
st.info(f"Last compiled: {time_str}")
# Optional preview
if st.session_state.show_preview:
st.markdown('<div class="preview-container">', unsafe_allow_html=True)
preview_images = render_pdf_preview(st.session_state.pdf_data)
if preview_images:
for i, img in enumerate(preview_images):
st.image(img, caption=f"Page {i+1}", use_container_width=True,
output_format="PNG")
st.markdown('</div>', unsafe_allow_html=True)
else:
st.info("Click 'Compile' to generate PDF output or press F5")
with output_tabs[1]:
# Document structure/outline view (with type check)
if isinstance(st.session_state.latex_code, str):
structure = extract_document_structure(st.session_state.latex_code)
else:
structure = []
if structure:
render_document_outline(structure)
else:
st.info("No document structure detected. Add sections using the toolbar.")
with output_tabs[2]:
# Document analysis features
# Document info
render_document_info(st.session_state.latex_code)
# Package analysis
packages = analyze_packages(st.session_state.latex_code)
if packages:
render_packages_panel(packages)
else:
st.info("No packages detected. Add packages using \\usepackage{}.")
# Environment analysis
environments = find_environments(st.session_state.latex_code)
if environments:
render_environments_panel(environments)
with output_tabs[3]:
# Problems panel (errors & warnings)
if st.session_state.errors or st.session_state.warnings:
render_problems(st.session_state.errors, st.session_state.warnings)
else:
st.info("No problems detected in the document.")
if __name__ == "__main__":
main() |