-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstringformat.rb
More file actions
95 lines (87 loc) · 2.39 KB
/
stringformat.rb
File metadata and controls
95 lines (87 loc) · 2.39 KB
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
class String
def format(color: 'white')
require 'tempfile'
require 'base64'
# Terminal detection
def kitty?
ENV['TERM'] == 'xterm-kitty' || ENV['TERM_PROGRAM'] == 'Kitty'
end
def iterm2?
ENV['TERM_PROGRAM'] == 'iTerm.app'
end
# Get terminal columns, similar to tput cols
cols = `tput cols`.to_i
em = (cols * 0.60).to_f
commonmark_content = <<~CMARK
---
documentclass: standalone
classoption: preview
header-includes:
- |
```{=latex}
\\usepackage[width=#{em}em]{geometry}
\\usepackage{xcolor}
\\pagecolor{black}
```
include-before:
- |
```{=latex}
\\color{#{color}}
\\Large
```
...
#{self}
CMARK
tmp_file = Tempfile.new(['stringformat', '.md'])
tmp_file.write(commonmark_content)
tmp_file.close
pdf_file = tmp_file.path.sub('.md', '.pdf')
# Run pandoc
system("pandoc --pdf-engine=xelatex -V mainfont=\"IBM Plex Serif Light\" -f commonmark_x #{tmp_file.path} -o #{pdf_file} >/dev/null 2>&1")
if File.exist?(pdf_file)
if kitty?
# Convert PDF to PNG for Kitty
png_file = tmp_file.path.sub('.md', '.png')
system("convert -density 130 #{pdf_file} #{png_file} >/dev/null 2>&1")
if File.exist?(png_file)
width = (cols * 0.75).to_i
if system("viu -w #{width} #{png_file}") == true
# Clean up
tmp_file.unlink
File.unlink(pdf_file)
File.unlink(png_file)
"" # Image displayed, return empty string
else
# Fallback if viu fails
tmp_file.unlink
File.unlink(pdf_file)
File.unlink(png_file)
self
end
else
# Fallback if PNG conversion fails
tmp_file.unlink
File.unlink(pdf_file)
self
end
elsif iterm2?
pdf_data = File.read(pdf_file)
base64_data = Base64.strict_encode64(pdf_data)
# Clean up
tmp_file.unlink
File.unlink(pdf_file)
# Return iTerm2 inline image sequence
"\e]1337;File=inline=1;preserveAspectRatio=1:#{base64_data}\a"
else
# Fallback for other terminals
tmp_file.unlink
File.unlink(pdf_file)
self
end
else
# Fallback if PDF generation fails
tmp_file.unlink
self
end
end
end