This repository was archived by the owner on Apr 17, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparchment.lua
More file actions
1841 lines (1689 loc) · 54.2 KB
/
Copy pathparchment.lua
File metadata and controls
1841 lines (1689 loc) · 54.2 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
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
--[[ parchment.lua (text editing application that feels like parchment)
Copyright © 2024–2026 Victoria Lacroix
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. ]]--
-- SECTION: Support library
local lib = require "parchmentlib"
function lib.get_home_directory()
return os.getenv "HOME"
end
-- Replaces the home directory in the given path with a tilde.
function lib.encode_path(path)
local pattern = "^" .. lib.get_home_directory()
return path:gsub(pattern, "~", 1)
end
-- Replaces a tilde at the start of the path with the user's home directory.
function lib.decode_path(path)
return path:gsub("^~", lib.get_home_directory(), 1)
end
function lib.absolute_path(file_path)
file_path = lib.decode_path(file_path)
local full_path = file_path
local dir
if full_path:sub(1, 1) ~= "/" then dir = lib.get_home_directory() end
if dir then
local up_pattern = "^%.%./"
local only_up_pattern = "^..$"
local cur_dir_pattern = "/[^/]+$"
while file_path:find(up_pattern) do
file_path = file_path:gsub(up_pattern, "")
dir = dir:gsub(cur_dir_pattern, "")
end
while file_path:find(only_up_pattern) do
file_path = ""
dir = dir:gsub(cur_dir_pattern, "")
end
full_path = dir .. "/" .. file_path
end
return full_path
end
-- Takes the given file path (relative or absolute) and returns the directory and the file name.
function lib.dir_and_file(file_path)
file_path = lib.absolute_path(file_path)
local last = 1
while file_path:sub(last + 1):find "/" do
last = last + (file_path:sub(last + 1):find "/")
end
return file_path:sub(1, last - 1), file_path:sub(last + 1)
end
function lib.file_exists(file_name)
file_name = lib.absolute_path(file_name)
local ok, err, code = os.rename(file_name, file_name)
if not ok then
-- In Linux, error code 13 when moving a file means that it failed because the directory cannot be made its own child. Any other error means the file does not exist.
if code == 13 then
return true
end
end
return ok
end
function lib.is_dir(file_name)
file_name = lib.absolute_path(file_name)
if file_name == "/" then return true end
return lib.file_exists(file_name .. "/")
end
-- Iterates all lines in a file handle, returning true if the file contains any NUL characters and false otherwise. The file handle is then seeked back to the beginning for further reading.
function lib.file_is_binary(hdl)
local is_binary = false
for line in hdl:lines() do
if line:match "\0" then
is_binary = true
break
end
end
hdl:seek "set"
return is_binary
end
function lib.escapepattern(str)
-- Lua's string.gmatch function does not have a plain option. This takes input strings and returns their pattern equivalent, allowing string.gmatch to work as though it didn't match patterns.
return str:gsub("[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%1")
end
function lib.escaperepl(str)
-- In order to prevent replacement strings from being treated like replacement patterns, all % characters simply need to be escaped by doubling them.
return str:gsub("%%", "%%%%")
end
-- Simple class implementation without inheritance.
local function newclass(init)
local c = {}
local mt = {}
c.__index = c
function mt:__call(...)
local obj = setmetatable({}, c)
init(obj, ...)
return obj
end
function c:isa(klass)
return getmetatable(self) == klass
end
return setmetatable(c, mt)
end
-- SECTION: Main application
-- This app runs in Flatpak, which puts Lua libraries outside of the standard paths. These lines tell Lua to look for libraries where Flatpak has put them.
package.cpath = "/app/lib/lua/5.4/?.so;" .. package.cpath
package.path = "/app/share/lua/5.4/?.lua;" .. package.path
local lfs = require "lfs"
local LuaGObject = require "LuaGObject"
local GLib = LuaGObject.require "GLib"
local Gio = LuaGObject.require "Gio"
local Adw = LuaGObject.require "Adw"
local Gtk = LuaGObject.require "Gtk"
local Gdk = LuaGObject.require "Gdk"
local Pango = LuaGObject.require "Pango"
local Parchment = LuaGObject.package "Parchment"
local app_id = lib.get_app_id()
local is_standalone = lib.get_is_standalone()
local app_flags = is_standalone and { "HANDLES_OPEN", "HANDLES_COMMAND_LINE", "NON_UNIQUE" } or { "HANDLES_OPEN", "HANDLES_COMMAND_LINE" }
local is_devel = lib.get_is_devel()
local app_title = "Parchment"
local app_version = lib.get_app_ver()
local app = Adw.Application {
application_id = app_id,
resource_base_path = "/ca/vtrlx/Parchment", -- Needs to be hardcoded.
flags = app_flags,
}
app:add_main_option("new-window", string.byte "n", "IN_MAIN", "NONE", "Create a new window.")
app:add_main_option("standalone", string.byte "s", "IN_MAIN", "NONE", "Run Parchment standalone. Suitable for use as an $EDITOR.")
-- Shortcuts from the GNOME HIG (https://developer.gnome.org/hig/reference/keyboard.html)
local accels = {
["app.zoom-out"] = { "<Ctrl>minus" },
["app.zoom-reset"] = { "<Ctrl>equal" },
["app.zoom-in"] = { "<Ctrl><Shift>plus" },
["win.new-file"] = { "<Ctrl>T" },
["win.open-file"] = { "<Ctrl>O" },
["win.new-window"] = {"<Ctrl>N" },
["win.shortcuts"] = { "<Ctrl><Shift>question" },
["win.open-folder"] = { "<Ctrl>D" },
["win.close-tab"] = { "<Ctrl>W" },
["win.save-file"] = { "<Ctrl>S" },
["win.save-file-as"] = { "<Ctrl><Shift>S" },
["win.search"] = { "<Ctrl>F" },
["win.goto"] = { "<Ctrl>I" },
}
for k, v in pairs(accels) do
app:set_accels_for_action(k, v)
end
local lerror = error
local function error(...)
local msg = table.concat({ ... }, " ")
local dlg = Adw.AlertDialog.new("Error", msg)
dlg:add_response("cancel", "Continue")
dlg:choose()
-- Call Lua's builtin error() function so this new one has the same semantics of unwinding the call stack.
lerror(...)
end
-- SECTION: GResources
do -- Load and register GResource.
local resource, err = Gio.Resource.load "/app/data/parchment.gresource"
if resource then
Gio.resources_register(resource)
else
print("Failed to load resource", err)
end
end -- Load and register GResource.
-- SECTION: Critically important global variables
local editors = {}
local window_widgets = {}
-- SECTION: Layout management
local zoomlevels = {
current = 3,
-- The use of fractions for the factor ensures total precision.
{ label = "75%", factor = 3/4 },
{ label = "90%", factor = 9/10 },
{ label = "100%", factor = 1 },
{ label = "110%", factor = 11/10 },
{ label = "125%", factor = 5/4 },
{ label = "133%", factor = 4/3 },
{ label = "150%", factor = 3/2 },
{ label = "166%", factor = 5/3 },
{ label = "180%", factor = 9/5 },
{ label = "200%", factor = 2 },
}
local function get_zoom_dimensions(level, fontsize)
assert(type(level) == "number" and level % 1 == 0)
assert(level >= 1 and level <= #zoomlevels)
local factor = zoomlevels[level].factor
local points = (fontsize or 11) * factor / 1024
local pixels = 8 * factor
local width = 640 * factor
local margin = 24 * factor
return points, pixels, width, margin
end
local css_template = [[
textview.parchment {
font-family: %s;
font-size: %f%s;
}
/* The Gtk.Image class always becomes more opaque when hovered, which suggests that it is actionable even when not. This CSS prevents that from occurring. */
image.parchment:hover {
opacity: 0.7;
}
]]
local styleman = Adw.StyleManager.get_default()
local css_providers = {}
for i = 1, #zoomlevels do table.insert(css_providers, Gtk.CssProvider()) end
function build_css_providers()
local docfontname = styleman.document_font_name
local fontdesc = Pango.FontDescription.from_string(docfontname)
local fontfam, fontsize = fontdesc:get_family(), fontdesc:get_size()
local fontunit = fontdesc:get_size_is_absolute() and "px" or "pt"
for i = 1, #zoomlevels do
local points = get_zoom_dimensions(i, fontsize)
local css = css_template:format(fontfam, points, fontunit)
css_providers[i]:load_from_string(css)
end
end
local function refresh_zoom(previous)
local display = Gdk.Display.get_default()
if previous and css_providers[previous] then
local oldprovider = css_providers[previous]
Gtk.StyleContext.remove_provider_for_display(display, oldprovider)
end
build_css_providers()
local currentzoom = zoomlevels.current
local newprovider = css_providers[currentzoom]
Gtk.StyleContext.add_provider_for_display(display, newprovider, 1000000)
local _, pixels = get_zoom_dimensions(currentzoom)
local above, below = math.floor(pixels / 2), math.ceil(pixels / 2)
for _, e in pairs(editors) do
e.tv.pixels_above_lines = above
e.tv.pixels_below_lines = below
end
end
styleman.on_notify["document-font-name"] = refresh_zoom
-- Ensure that the default zoom level is active when starting up.
refresh_zoom()
local function zoom_out()
local previous = zoomlevels.current
if previous == 1 then return end
zoomlevels.current = previous - 1
refresh_zoom(previous)
end
local function zoom_in()
local previous = zoomlevels.current
if previous == #zoomlevels then return end
zoomlevels.current = previous + 1
refresh_zoom(previous)
end
local function zoom_reset()
local previous = zoomlevels.current
if previous == 3 then return end
zoomlevels.current = 3
refresh_zoom(previous)
end
-- GTK widgets do not provide signals for when they've resized. Instead, one is supposed to use a Layout Manager to handle this. Because the Layout Manager needs to be of a specific class, this will subclass it.
Parchment:class("EditorLayoutManager", Gtk.LayoutManager)
function Parchment.EditorLayoutManager:do_allocate(widget, width, height, baseline)
local _, _, maxwidth, minmargin = get_zoom_dimensions(zoomlevels.current)
local maxinner = maxwidth - minmargin * 2
local totalmargin = math.max(minmargin, (width - maxinner) / 2)
-- In case of the margin space being an odd number, the extra pixel gets assigned to the right side.
widget.left_margin = math.floor(totalmargin)
widget.right_margin = math.ceil(totalmargin)
-- Allow some overscroll at the bottom of the file, but never enough such that all text can be scrolled out of view.
widget.bottom_margin = math.floor(height * 0.6)
Gtk.TextView.do_size_allocate(widget, width, height, baseline)
end
-- SECTION: Text editor context menu
local function editormenu()
local menu = Gio.Menu()
menu:append("Go to Line…", "win.goto")
return menu
end
-- SECTION: Text editor
local editor = newclass(function(self)
self.indenttags = {}
local search_entry = Gtk.Text {
placeholder_text = "Find in file…",
hexpand = true,
}
local search_clear = Gtk.Button {
css_name = "image",
icon_name = "entry-clear-symbolic",
margin_start = 12,
visible = false,
on_clicked = function()
search_entry.text = ""
search_entry:grab_focus()
end,
}
local matchnum_label = Gtk.Label {
css_classes = { "numeric" },
halign = "END",
hexpand = false,
margin_start = 6,
margin_end = 6,
}
function matchnum_label.on_notify.text()
matchnum_label.visible = #matchnum_label.text > 0
end
local sbox = Gtk.Box {
orientation = "HORIZONTAL",
css_name = "entry",
Gtk.Image {
css_classes = { "parchment" },
icon_name = "find-symbolic",
},
search_entry,
search_clear,
matchnum_label,
}
local prev_match = Gtk.Button {
icon_name = "prev-symbolic",
tooltip_text = "Go to previous match",
}
local next_match = Gtk.Button {
icon_name = "next-symbolic",
tooltip_text = "Go to next match",
}
local search_box = Gtk.Box {
orientation = "HORIZONTAL",
css_classes = { "linked" },
sbox,
prev_match,
next_match,
}
local replace_image = Gtk.Image {
css_classes = { "parchment" },
icon_name = "find-replace-symbolic",
}
local replace_entry = Gtk.Text {
placeholder_text = "Replace with…",
hexpand = true,
}
local replace_clear = Gtk.Button {
css_name = "image",
icon_name = "entry-clear-symbolic",
margin_start = 12,
margin_end = 6,
visible = false,
on_clicked = function()
replace_entry.text = ""
replace_entry:grab_focus()
end,
}
local rbox = Gtk.Box {
css_name = "entry",
orientation = "HORIZONTAL",
replace_image,
replace_entry,
replace_clear,
}
local replace_button = Gtk.Button {
label = "Replace",
tooltip_text = "Replaces selected text",
sensitive = false,
}
local replace_in_sel_button = Gtk.Button {
label = "Replace in selection",
tooltip_text = "Replace all matches in the selection",
visible = false,
}
local replace_all_button = Gtk.Button {
label = "Replace all",
tooltip_text = "Replaces all matches in file",
sensitive = false,
}
local replace_box = Gtk.Box {
orientation = "HORIZONTAL",
css_classes = { "linked" },
rbox,
replace_button,
replace_in_sel_button,
replace_all_button,
}
local search_bar_box = Gtk.Box {
orientation = "VERTICAL",
spacing = 6,
search_box,
replace_box,
}
local search_bar_clamp = Adw.Clamp {
orientation = "HORIZONTAL",
child = search_bar_box,
maximum_size = 480,
}
local search_bar = Gtk.SearchBar {
child = search_bar_clamp,
search_mode_enabled = false,
show_close_button = true,
}
search_bar:connect_entry(search_entry)
local currentzoom = zoomlevels.current
local _, pixels = get_zoom_dimensions(currentzoom)
local above, below = math.floor(pixels / 2), math.ceil(pixels / 2)
local text_view = Gtk.TextView {
css_classes = { "parchment", "numeric", "view" },
top_margin = 12,
bottom_margin = 400,
left_margin = 24,
right_margin = 30,
pixels_above_lines = above,
pixels_below_lines = below,
pixels_inside_wrap = 0,
layout_manager = Parchment.EditorLayoutManager(),
wrap_mode = Gtk.WrapMode.WORD_CHAR,
extra_menu = editormenu(),
}
text_view.buffer:set_max_undo_levels(0)
local scrolled_win = Gtk.ScrolledWindow {
hscrollbar_policy = "NEVER",
child = text_view,
vexpand = true,
}
local box = Gtk.Box {
orientation = "VERTICAL",
search_bar,
scrolled_win,
}
self.matches = {}
self.search = {
entry = search_entry,
replentry = replace_entry,
bar = search_bar,
matchnum = matchnum_label,
}
self.tv = text_view
function self.tv.buffer.on_modified_changed()
self:update_title()
end
self.scroll = scrolled_win
self.widget = box
local function refresh_repl_buttons()
if self:selection_has_match() and not self:match_selected() then
replace_button.visible = false
replace_in_sel_button.visible = true
replace_all_button.visible = false
else
replace_button.visible = true
replace_in_sel_button.visible = false
replace_all_button.visible = true
end
replace_button.sensitive = self:match_selected()
replace_in_sel_button.sensitive = not self:match_selected() and
self:selection_has_match()
replace_all_button.sensitive = #self.matches > 0
if search_entry.text == replace_entry.text then
replace_button.sensitive = false
replace_in_sel_button.sensitive = false
replace_all_button.sensitive = false
end
end
function replchanged()
refresh_repl_buttons()
replace_clear.visible = #replace_entry.text > 0
end
function self.tv.buffer.on_mark_set(iter, mark)
refresh_repl_buttons()
end
local function dosearch()
if not search_bar.search_mode_enabled then return end
if #search_entry.text == 0 then
matchnum_label.label = ""
search_clear.visible = false
return
end
matchnum_label.label = self:findall(search_entry.text)
search_clear.visible = true
refresh_repl_buttons()
end
local function prev()
matchnum_label.label = self:prev_match(search_entry.text)
refresh_repl_buttons()
end
local function next()
matchnum_label.label = self:next_match(search_entry.text)
refresh_repl_buttons()
end
local function repl()
if not replace_button.sensitive then return end
self:replace(replace_entry.text)
matchnum_label.label = self:next_match(search_entry.text)
refresh_repl_buttons()
end
local function replsel()
self:replace_in_selection(search_entry.text, replace_entry.text)
dosearch()
end
local function replall()
matchnum_label.label = ""
self:replace_all(search_entry.text, replace_entry.text)
refresh_repl_buttons()
end
--[[
This next line in particular may be the single most expensive operation in the entire application. It performs a search every single time the file's contents change while the search bar is visible. This is the single factor that hamper's Parchment's performance when dealing with large files.
As a benchmark, on a Core i7 laptop using a balanced power profile, in a file with 200,000 lines of text, I had no problem typing text with the search mode turned off. With search enabled, and with an active query, Parchment would sometimes take a fraction of a second to show newly-typed text—but never dropped any keyboard inputs. This is a use case that is far, far beyond what Parchment is expected to support, and this code still works acceptably well. In fact, GtkTextView appears to have a harder time coping with large amounts of text than the find function does.
It's believed that the reason for the find function's excellent performance is that it uses Lua's string search functions, which are optimized to work especially well for long strings of text.
]]--
self.tv.buffer.on_changed = dosearch
--[[
self.tv.buffer.on_insert_text:connect(function(buffer, location, text, len)
local count = 0
for _ in text:gmatch "[^\n]*" do count = count + 1 end
local endline = location:get_line() + 1
local startline = endline - count + 1
for i = startline, endline do self:markindent(i) end
end, nil, true)
self.tv.on_map = function()
if self.did_first_indent then return end
GLib.timeout_add(GLib.PRIORITY_DEFAULT, 40, function()
self:markallindents()
end)
self.did_first_indent = true
end
]]--
search_entry.buffer.on_notify.text = dosearch
replace_entry.buffer.on_notify.text = replchanged
prev_match.on_clicked = prev
next_match.on_clicked = next
search_entry.on_activate = next
replace_button.on_clicked = repl
replace_in_sel_button.on_clicked = replsel
replace_all_button.on_clicked = replall
end)
local function open_file(path)
assert(app.active_window)
local tab_view = window_widgets[app.active_window].tab_view
assert(tab_view)
if type(path) == "string" then
path = lib.absolute_path(path)
local e = editors[path]
if e then
e:grab_focus()
return
end
end
local e = editor()
if type(path) == "string" then
if not e:edit_file(path) then return end
local iter = e.tv.buffer:get_start_iter()
e.tv.buffer:select_range(iter, iter)
end
editors[e.widget] = e
if path then editors[path] = e end
local page = tab_view:add_page(e.widget)
tab_view:set_selected_page(page)
end
local function get_focused_editor()
assert(app.active_window)
local tab_view = window_widgets[app.active_window].tab_view
assert(tab_view)
local page = tab_view.selected_page
if not page then return nil end
return editors[page.child]
end
-- SECTION: File Management
local file_dialog_path = lib.get_home_directory()
local filefilters = Gio.ListStore.new(Gtk.FileFilter)
filefilters:append(Gtk.FileFilter {
name = "Text files",
mime_types = { "text/*" },
})
local function open_file_dialog(window)
local e = get_focused_editor()
local dir = file_dialog_path
if e and e:has_file() then
local _, newdir, _ = e:get_path_info()
dir = newdir
end
local file_dialog = Gtk.FileDialog {
initial_folder = Gio.File.new_for_path(dir),
filters = filefilters,
}
Gio.Async.start(function()
local list = file_dialog:async_open_multiple(window)
if not list then return end
for i = 1, list.n_items do
-- Gio's API documents say that ListModel's :get_item() method is not available to language bindings and to use :get_object() instead. That's not the case for LuaGObject, which binds :get_item() and returns the object itself instead of a pointer.
local file = list:get_item(i - 1)
if i == 1 then
file_dialog_path = file:get_parent():get_path()
end
open_file(file:get_path())
end
end)() -- Calls wrapped async
end
local function save_file_dialog(window, e)
local dir = file_dialog_path
if e:has_file() then
local _, newdir, _ = e:get_path_info()
dir = newdir
end
local file_dialog = Gtk.FileDialog {
initial_folder = Gio.File.new_for_path(dir),
filters = filefilters,
}
Gio.Async.start(function()
local file = file_dialog:async_save(window)
if not file then return end
local path = file:get_path()
local dir, _ = lib.dir_and_file(path)
file_dialog_path = dir
e:save(path)
end)() -- Calls wrapped async
end
-- SECTION: Application menus
local burger_menu = Gio.Menu()
local zoom_item = Gio.MenuItem.new()
local zoom_custom_value = GLib.Variant("s", "zoom_section")
zoom_item:set_attribute_value("custom", zoom_custom_value)
burger_menu:append_item(zoom_item)
if not is_standalone then
local file_menu = Gio.Menu()
file_menu:append("Save As…", "win.save-file-as")
burger_menu:append_section(nil, file_menu)
end
local nav_menu = Gio.Menu()
nav_menu:append("Show in Files", "win.open-folder")
nav_menu:append("Find/Replace", "win.search")
nav_menu:append("Go to Line", "win.goto")
burger_menu:append_section(nil, nav_menu)
local app_menu = Gio.Menu()
if not is_standalone then
app_menu:append("New Window", "win.new-window")
end
app_menu:append("Keyboard Shortcuts", "win.shortcuts")
app_menu:append("About " .. app_title, "win.about")
burger_menu:append_section(nil, app_menu)
local shortcutsdialog = Adw.ShortcutsDialog {
Adw.ShortcutsSection {
title = "Parchment",
table.unpack(not is_standalone and {
Adw.ShortcutsItem.new_from_action("Open a file", "win.open-file"),
Adw.ShortcutsItem.new_from_action("New file", "win.new-file"),
Adw.ShortcutsItem.new_from_action("New window", "win.new-window"),
--Adw.ShortcutsItem.new_from_action("Open/close overview", "win.overview"),
Adw.ShortcutsItem.new_from_action("Show keyboard shortcuts", "win.shortcuts"),
} or {
--Adw.ShortcutsItem.new_from_action("Open/close overview", "win.overview"),
Adw.ShortcutsItem.new_from_action("Show keyboard shortcuts", "win.shortcuts"),
}),
},
Adw.ShortcutsSection {
title = "Editor",
table.unpack(not is_standalone and {
Adw.ShortcutsItem.new_from_action("Show in Files", "win.open-folder"),
Adw.ShortcutsItem.new_from_action("Save file", "win.save-file"),
Adw.ShortcutsItem.new_from_action("Save file as", "win.save-file-as"),
Adw.ShortcutsItem.new_from_action("Search in file", "win.search"),
Adw.ShortcutsItem.new_from_action("Go to line", "win.goto"),
Adw.ShortcutsItem.new_from_action("Close tab", "win.close-tab"),
} or {
Adw.ShortcutsItem.new_from_action("Show in Files", "win.open-folder"),
Adw.ShortcutsItem.new_from_action("Save file", "win.save-file"),
Adw.ShortcutsItem.new_from_action("Search in file", "win.search"),
Adw.ShortcutsItem.new_from_action("Go to line", "win.goto"),
}),
},
Adw.ShortcutsSection {
title = "Zoom",
Adw.ShortcutsItem.new_from_action("Zoom out", "app.zoom-out"),
Adw.ShortcutsItem.new_from_action("Zoom in", "app.zoom-in"),
Adw.ShortcutsItem.new_from_action("Reset zoom", "app.zoom-reset"),
},
}
local function about(parent)
local aboutdlg = Adw.AboutDialog {
application_icon = app_id,
application_name = app_title,
copyright = "© 2025 Victoria Lacroix",
developer_name = "Victoria Lacroix",
issue_url = "https://github.com/vtrlx/parchment/issues/new",
license_type = "GPL_3_0",
version = lib.get_app_ver(),
website = "https://www.vtrlx.ca/apps/parchment/",
}
aboutdlg:add_link("Contact the Developer", "mailto:victoria@vtrlx.ca?subject=Parchment App")
aboutdlg:add_acknowledgement_section("Application Name", {
"Brage Fuglseth https://bragefuglseth.dev",
})
aboutdlg:add_acknowledgement_section("3rd Party Libraries", {
"LuaFileSystem https://lunarmodules.github.io/luafilesystem/index.html",
})
aboutdlg:present(parent)
end
-- SECTION: Main application window
local disabled_in_standalone = {
["new-window"] = true,
["new-file"] = true,
["open-file"]= true,
["save-file-as"] = true,
["close-tab"] = true,
}
local function add_new_action(map, name, cb)
if is_standalone and disabled_in_standalone[name] then return end
local action = Gio.SimpleAction.new(name)
action.enabled = true
action.on_activate = cb
map:add_action(action)
return action
end
-- Creates a new window and presents it, returning the inner tab view.
local function new_window()
local new_tab_button = Gtk.Button {
action_name = "win.new-file",
halign = "START",
icon_name = "file-new-symbolic",
tooltip_text = "New file",
}
local open_file_button = Gtk.Button {
action_name = "win.open-file",
icon_name = "file-open-symbolic",
tooltip_text = "Open a file",
}
local zoom_out_button = Gtk.Button {
action_name = "app.zoom-out",
icon_name = "zoom-minus-symbolic",
tooltip_text = "Zoom out",
}
local zoom_in_button = Gtk.Button {
action_name = "app.zoom-in",
icon_name = "zoom-plus-symbolic",
tooltip_text = "Zoom in",
}
local currentzoom = zoomlevels.current
local zoompercent = zoomlevels[currentzoom].label
local zoom_reset_button = Gtk.Button {
action_name = "app.zoom-reset",
css_classes = { "numeric" },
hexpand = true,
label = zoompercent,
tooltip_text = "Reset zoom to 100%",
width_request = 100,
}
local zoom_box = Gtk.Box {
orientation = "HORIZONTAL",
hexpand = true,
Gtk.Label {
label = "Zoom",
margin_start = 12,
},
Gtk.Box {
orientation = "HORIZONTAL",
halign = "END",
margin_start = 64,
css_classes = { "linked" },
zoom_out_button,
zoom_reset_button,
zoom_in_button,
},
}
local burger_popover = Gtk.PopoverMenu.new_from_model(burger_menu)
burger_popover.halign = "END"
burger_popover:add_child(zoom_box, "zoom_section")
local menu_button = Gtk.MenuButton {
direction = "DOWN",
icon_name = "menu-symbolic",
popover = burger_popover,
}
local tab_view = Adw.TabView {
vexpand = true,
}
function tab_view:on_create_window()
return new_window()
end
--[[
local tab_button = Adw.TabButton {
action_name = "overview.open",
tooltip_text = "View all tabs",
view = tab_view,
}
]]--
local save_button = Gtk.Button {
action_name = "win.save-file",
icon_name = "file-save-symbolic",
tooltip_text = "Save file",
visible = false,
}
local file_properties_button = Gtk.Button {
icon_name = "modify-formatting-symbolic",
tooltip_text = "Modify formatting…",
visible = false,
on_clicked = function()
local e = get_focused_editor()
if not e then return end
e:show_properties()
end,
}
local window_title = Adw.WindowTitle.new(app_title, "")
local content_header = Adw.HeaderBar {
title_widget = window_title,
show_start_title_buttons = false,
valign = "START",
start_packs = not is_standalone and { new_tab_button, open_file_button, save_button } or { save_button },
end_packs = { menu_button, file_properties_button },
-- end_packs = { menu_button, tab_button, file_properties_button },
}
local tab_bar = Adw.TabBar {
autohide = true,
view = tab_view,
}
local content = Adw.ToolbarView {
content = tab_view,
top_bar_style = "FLAT",
top_bars = { content_header, tab_bar },
}
-- This is disabled as it is currently broken by Gtk.TextView causing resize events during its snapshot phase, which when used as a child of Adw.TabOverview leads to the entire tab contents visually freezing until switching to a new tab. Worse still, to fix this requires a breaking change in Gtk and Gtk.SourceView, so the fix must be coordinated downstream with distros.
--[[
local tab_overview = Adw.TabOverview {
child = content,
view = tab_view,
}
]]--
local window = Adw.ApplicationWindow {
application = app,
-- content = tab_overview,
content = content,
title = app_title,
width_request = 480,
height_request = 240,
}
window:set_default_size(640, 720)
function tab_view:on_page_attached(page)
file_properties_button.visible = true
local e = editors[page.child]
if not e then return end
content.top_bar_style = "RAISED_BORDER"
function e:set_title(title, subtitle, icon)
page.title = title
if icon then
local iname = "pencil-symbolic"
page.indicator_icon = Gio.Icon.new_for_string(iname)
else
page.indicator_icon = nil
end
if tab_view.selected_page == page then
window.title = not is_standalone and title or (title .. " (standalone)")
window_title:set_title(title)
window_title:set_subtitle(subtitle)
save_button.tooltip_text = "Save " .. title
save_button.visible = icon
if window_widgets[window] and self:has_file() then
window_widgets[window].open_folder_action.enabled = true
end
end
end
function e:set_search_mode()
end
function e:grab_focus()
window:activate()
tab_view:set_selected_page(page)
e.tv:grab_focus()
end
-- Force set here, because the tab view's selected_page won't be set in time for this call.
local title, subtitle = e:get_title()
page.title = name
window.title = not is_standalone and title or (title .. " (standalone)")
window_title:set_title(title)
window_title:set_subtitle(subtitle)
window_widgets[window].open_folder_action.enabled = e:has_file()
window_widgets[window].search_action.enabled = true
window_widgets[window].goto_action.enabled = true
end
function tab_view:on_page_detached(page)
local e = editors[page.child]
if not e then return end
-- This will be reset once the page is reattached.
function e:set_title() end
end
function tab_view:on_notify(spec)
if spec.name == "selected-page" and self.selected_page then
local e = editors[self.selected_page.child]
e:update_title()
e.tv:grab_focus()
end
end
function tab_view:on_close_page(page)
local e = editors[page.child]
local do_close = true
local reason
if type(e.can_close) == "function" then
do_close, reason = e:can_close()
end
self:close_page_finish(page, do_close)
if not do_close then
local body = "The file %q has unsaved changes."
local _, _, name = e:get_path_info()
body = body:format(name)
if not e:has_file() then
body = "This file has unsaved changes."
end
local dlg = Adw.AlertDialog.new("Save changes?", body)
dlg:add_response("close", "Keep open")
dlg:set_response_appearance("close", "DEFAULT")
dlg:add_response("discard", "Close without saving")
dlg:set_response_appearance("discard", "DESTRUCTIVE")
dlg:add_response("save", "Save and close")
dlg:set_response_appearance("save", "SUGGESTED")
function dlg:on_response(response)
if response == "discard" then
e.tv.buffer:set_modified(false)
tab_view:close_page(page)
elseif response == "save" then
e:save()
tab_view:close_page(page)
end
end
dlg:choose(app.active_window)
else
editors[page.child] = nil
local path = e:get_path_info()
if path then editors[path] = nil end
if self:get_n_pages() == 0 then
window.title = app_title
window_title:set_title(app_title)