aster-completion 0.1.1

Natural shell completion
Documentation
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
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
use std::fs::{self, File};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{io, io::Read, io::Write};

use anyhow::{Context, Result, bail};
use aster::client;
use aster::config::{Paths, Settings, completion_key_sequence};
use aster::daemon;
use aster::protocol::{Request, Response};
use clap::{Parser, Subcommand, ValueEnum};

#[derive(Debug, Parser)]
#[command(name = "aster", version, about)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Run the shared per-host daemon in the foreground.
    Daemon,
    /// Record a completed command in shared history.
    Record {
        #[arg(long, required_unless_present = "stdin", conflicts_with = "stdin")]
        command: Option<String>,
        #[arg(long)]
        stdin: bool,
        #[arg(long)]
        cwd: PathBuf,
        #[arg(long)]
        exit_code: i32,
        #[arg(long, default_value = "unknown")]
        session: String,
    },
    /// Return conservative history completions for the current buffer.
    Complete {
        #[arg(long, required_unless_present = "stdin", conflicts_with = "stdin")]
        buffer: Option<String>,
        #[arg(long)]
        stdin: bool,
        #[arg(long)]
        cursor: usize,
        #[arg(long)]
        cwd: PathBuf,
        #[arg(long)]
        limit: Option<usize>,
        #[arg(long, value_enum, default_value_t = OutputFormat::Json)]
        format: OutputFormat,
    },
    /// Fuzzy-rank shared history and installed commands with fzf.
    Fuzzy {
        #[arg(long, default_value = "")]
        query: String,
        #[arg(long)]
        cwd: PathBuf,
        #[arg(long)]
        limit: Option<usize>,
        #[arg(long, value_enum, default_value_t = OutputFormat::Json)]
        format: OutputFormat,
    },
    /// Emit a bounded, sanitized preview for a local regular file.
    PreviewFile {
        #[arg(long)]
        path: PathBuf,
        #[arg(long)]
        cwd: PathBuf,
    },
    /// Import an existing Zsh history file into shared state.
    ImportHistory {
        #[arg(long)]
        file: PathBuf,
    },
    /// Print shell integration code and initialize the default config.
    Init {
        #[arg(value_enum)]
        shell: Shell,
    },
    /// Verify config, storage, and daemon connectivity.
    Doctor,
    /// Stop the shared daemon on this host.
    Stop,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum OutputFormat {
    Json,
    Insert,
    Zsh,
    ZshV2,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum Shell {
    Zsh,
}

fn main() {
    if let Err(error) = run() {
        eprintln!("aster: {error:#}");
        std::process::exit(1);
    }
}

fn run() -> Result<()> {
    let cli = Cli::parse();
    let paths = Paths::discover()?;

    match cli.command {
        Command::Daemon => {
            let settings = Settings::load(&paths.config_file)?;
            daemon::serve(paths, settings)
        }
        Command::Record {
            command,
            stdin,
            cwd,
            exit_code,
            session,
        } => {
            expect_success(client::request(
                &paths,
                Request::Record {
                    command: read_input(command, stdin, 64 * 1024)?,
                    cwd: cwd.to_string_lossy().into_owned(),
                    exit_code,
                    observed_at_ms: now_ms(),
                    session_id: session,
                },
            )?)?;
            Ok(())
        }
        Command::Complete {
            buffer,
            stdin,
            cursor,
            cwd,
            limit,
            format,
        } => {
            let response = client::request_idempotent(
                &paths,
                Request::Complete {
                    buffer: read_input(buffer, stdin, 64 * 1024)?,
                    cursor_byte: cursor,
                    cwd: cwd.to_string_lossy().into_owned(),
                    limit,
                },
            )?;
            write_completion(response, format)
        }
        Command::Fuzzy {
            query,
            cwd,
            limit,
            format,
        } => {
            let response = client::request_idempotent(
                &paths,
                Request::Fuzzy {
                    query,
                    cwd: cwd.to_string_lossy().into_owned(),
                    limit,
                },
            )?;
            write_completion(response, format)
        }
        Command::PreviewFile { path, cwd } => write_file_preview(path, cwd),
        Command::ImportHistory { file } => {
            let file = file
                .canonicalize()
                .with_context(|| format!("failed to resolve history file {}", file.display()))?;
            match client::request(
                &paths,
                Request::ImportHistory {
                    path: file.to_string_lossy().into_owned(),
                },
            )? {
                Response::Imported { imported, skipped } => {
                    if !skipped {
                        eprintln!("aster: imported {imported} history entries");
                    }
                    Ok(())
                }
                Response::Error { message } => bail!(message),
                response => bail!("unexpected daemon response: {response:?}"),
            }
        }
        Command::Init { shell: Shell::Zsh } => {
            Settings::write_default(&paths.config_file)?;
            let settings = Settings::load(&paths.config_file)?;
            print!("{}", zsh_integration(&settings)?);
            Ok(())
        }
        Command::Doctor => doctor(&paths),
        Command::Stop => match client::request_once(&paths, Request::Shutdown)? {
            Response::ShuttingDown => Ok(()),
            Response::Error { message } => bail!(message),
            response => bail!("unexpected daemon response: {response:?}"),
        },
    }
}

fn write_file_preview(path: PathBuf, cwd: PathBuf) -> Result<()> {
    let path = if path.is_absolute() {
        path
    } else {
        cwd.join(path)
    };
    let metadata = fs::symlink_metadata(&path)
        .with_context(|| format!("failed to inspect preview target {}", path.display()))?;
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        bail!("preview target is not a regular non-symlink file");
    }
    let mut bytes = Vec::new();
    File::open(&path)?.take(16 * 1024).read_to_end(&mut bytes)?;
    let kind = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
        "PNG image"
    } else if bytes.starts_with(b"\xff\xd8\xff") {
        "JPEG image"
    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
        "GIF image"
    } else if bytes.starts_with(b"%PDF-") {
        "PDF document"
    } else if bytes.contains(&0) {
        "binary file"
    } else {
        "text file"
    };
    let stdout = io::stdout();
    let mut output = stdout.lock();
    for line in [
        format!("Type: {kind}"),
        format!("Size: {} bytes", metadata.len()),
    ] {
        output.write_all(line.as_bytes())?;
        output.write_all(&[0])?;
    }
    if kind == "text file" {
        let text = String::from_utf8_lossy(&bytes);
        for source in text.lines().take(8) {
            let line: String = source
                .chars()
                .take(160)
                .map(|character| {
                    if character == '\t' {
                        ' '
                    } else if character.is_ascii() && !character.is_control() {
                        character
                    } else {
                        '?'
                    }
                })
                .collect();
            output.write_all(line.as_bytes())?;
            output.write_all(&[0])?;
        }
    } else if matches!(
        kind,
        "PNG image" | "JPEG image" | "GIF image" | "PDF document"
    ) {
        output.write_all(b"Graphical preview requires the future PTY frontend")?;
        output.write_all(&[0])?;
    }
    Ok(())
}

fn doctor(paths: &Paths) -> Result<()> {
    Settings::load(&paths.config_file)?;
    let response = client::request(paths, Request::Ping)?;
    let Response::Pong { version } = response else {
        bail!("unexpected daemon response: {response:?}");
    };
    println!("aster {version}");
    println!("config: {}", paths.config_file.display());
    println!("database: {}", paths.database_file.display());
    println!("socket: {}", paths.socket_file.display());
    println!("status: ready");
    Ok(())
}

fn write_completion(response: Response, format: OutputFormat) -> Result<()> {
    let Response::Completion(completion) = response else {
        return match response {
            Response::Error { message } => Err(anyhow::anyhow!(message)),
            response => Err(anyhow::anyhow!("unexpected daemon response: {response:?}")),
        };
    };
    match format {
        OutputFormat::Json => println!("{}", serde_json::to_string(&completion)?),
        OutputFormat::Insert => {
            if let Some(candidate) = completion.candidates.first() {
                print!("{}", candidate.accept_text);
            }
        }
        OutputFormat::Zsh | OutputFormat::ZshV2 => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            for candidate in completion.candidates {
                let source = match candidate.source {
                    aster::protocol::CandidateSource::History => "history",
                    aster::protocol::CandidateSource::Command => "command",
                };
                let kind = match candidate.kind {
                    aster::protocol::CandidateKind::History => "history",
                    aster::protocol::CandidateKind::Command => "command",
                };
                for field in [
                    candidate.insert_text.as_str(),
                    candidate.display.as_str(),
                    candidate.description.as_str(),
                    kind,
                    source,
                ] {
                    output.write_all(field.as_bytes())?;
                    output.write_all(&[0])?;
                }
                if matches!(format, OutputFormat::ZshV2) {
                    output.write_all(if candidate.description_pending {
                        b"true"
                    } else {
                        b"false"
                    })?;
                    output.write_all(&[0])?;
                }
            }
        }
    }
    Ok(())
}

fn expect_success(response: Response) -> Result<()> {
    match response {
        Response::Recorded => Ok(()),
        Response::Error { message } => bail!(message),
        response => bail!("unexpected daemon response: {response:?}"),
    }
}

fn now_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
        .min(i64::MAX as u128) as i64
}

fn read_input(value: Option<String>, from_stdin: bool, limit: u64) -> Result<String> {
    if !from_stdin {
        return value.context("missing input value");
    }
    let mut bytes = Vec::new();
    io::stdin().take(limit + 1).read_to_end(&mut bytes)?;
    if bytes.len() as u64 > limit {
        bail!("stdin input exceeds {limit} bytes");
    }
    String::from_utf8(bytes).context("stdin input is not valid UTF-8")
}

fn zsh_integration(settings: &Settings) -> Result<String> {
    let completion_key = completion_key_sequence(&settings.completion.key)?;
    let completion_key_label = match settings.completion.key.as_str() {
        "ctrl-space" => "Ctrl-Space".to_owned(),
        "shift-tab" => "Shift-Tab".to_owned(),
        "tab" => "Tab".to_owned(),
        key => format!(
            "Ctrl-{}",
            key.trim_start_matches("ctrl-").to_ascii_uppercase()
        ),
    };
    let menu_width = settings.ui.menu_width.to_string();
    let max_visible = settings.ui.max_visible.to_string();
    let max_candidates = settings.completion.max_candidates.to_string();
    Ok(r#"# Aster shell integration
if [[ -o interactive ]] && (( $+commands[aster] )); then
  typeset -g ASTER_ZSH_LOADED=1
  typeset -g _ASTER_COMMAND=""
  typeset -g _ASTER_COMMAND_CWD=""
  typeset -g _ASTER_MENU_ACTIVE=0
  typeset -g _ASTER_MENU_INDEX=1
  typeset -g _ASTER_MENU_START=1
  typeset -g _ASTER_MENU_BUFFER=""
  typeset -g _ASTER_MENU_OWNS_DISPLAY=0
  typeset -g _ASTER_MENU_REQUEST_BUFFER=""
  typeset -g _ASTER_MENU_REQUEST_CWD=""
  typeset -g _ASTER_MENU_REQUEST_CURSOR=0
  typeset -g _ASTER_MENU_REQUEST_FD=-1
  typeset -g _ASTER_MENU_REQUEST_DIRTY=0
  typeset -g _ASTER_MENU_REFRESH_TICKS=0
  typeset -g _ASTER_MENU_RESTORE_DISPLAY=""
  typeset -g _ASTER_RESTORE_HIGHLIGHTS=0
  typeset -g _ASTER_CAPTURE_FOREIGN_HIGHLIGHTS=0
  typeset -g _ASTER_MENU_TICK_FD=-1
  typeset -g _ASTER_HAS_ZSELECT=0
  typeset -g _ASTER_NATIVE_REQUEST_FD=-1
  typeset -g _ASTER_NATIVE_REQUEST_PID=-1
  typeset -g _ASTER_NATIVE_REQUEST_TICKS=0
  typeset -g _ASTER_NATIVE_START_TICKS=0
  typeset -g _ASTER_NATIVE_REQUESTED=0
  typeset -g _ASTER_IN_NATIVE_COMPLETION=0
  typeset -g _ASTER_FUZZY_ACTIVE=0
  typeset -g _ASTER_FUZZY_BASE=""
  typeset -g _ASTER_FUZZY_QUERY=""
  typeset -g _ASTER_FUZZY_KEYTIMEOUT=-1
  typeset -g _ASTER_FUZZY_PREVIOUS_KEYMAP=""
  typeset -g _ASTER_PREVIEW_FD=-1
  typeset -g _ASTER_PREVIEW_PID=-1
  typeset -g _ASTER_PREVIEW_TICKS=0
  typeset -g _ASTER_PREVIEW_TARGET=""
  typeset -g _ASTER_PREVIEW_PATH=""
  typeset -ga _ASTER_PREVIEW_LINES=()
  typeset -g _ASTER_UTF8_UI=0
  typeset -g _ASTER_CHARMAP="${(U)$(command locale charmap 2>/dev/null)}"
  [[ "$_ASTER_CHARMAP" == *UTF-8* || "$_ASTER_CHARMAP" == *UTF8* ]] && _ASTER_UTF8_UI=1
  unset _ASTER_CHARMAP
  typeset -ga _ASTER_MENU_ACCEPTS=()
  typeset -ga _ASTER_MENU_DISPLAYS=()
  typeset -ga _ASTER_MENU_DESCRIPTIONS=()
  typeset -ga _ASTER_MENU_KINDS=()
  typeset -ga _ASTER_MENU_SOURCES=()
  typeset -ga _ASTER_FOREIGN_HIGHLIGHTS=()
  typeset -ga _ASTER_RENDERED_HIGHLIGHTS=()
  typeset -ga _ASTER_DAEMON_ACCEPTS=()
  typeset -ga _ASTER_DAEMON_DISPLAYS=()
  typeset -ga _ASTER_DAEMON_DESCRIPTIONS=()
  typeset -ga _ASTER_DAEMON_KINDS=()
  typeset -ga _ASTER_DAEMON_SOURCES=()
  typeset -ga _ASTER_NATIVE_ACCEPTS=()
  typeset -ga _ASTER_NATIVE_DISPLAYS=()
  typeset -ga _ASTER_NATIVE_DESCRIPTIONS=()

  _aster_tmux_title() {
    if [[ -n "${TMUX_PANE:-}" ]] && (( $+commands[tmux] )); then
      command tmux select-pane -t "$TMUX_PANE" -T "$1" >/dev/null 2>&1
    fi
    return 0
  }

  _aster_preexec() {
    local command_name="${${1%%[[:space:]]*}:t}"
    _ASTER_COMMAND="$1"
    _ASTER_COMMAND_CWD="$PWD"
    _aster_tmux_title "${command_name:-command}"
    return 0
  }

  _aster_precmd() {
    local exit_code=$?
    if [[ -n "$_ASTER_COMMAND" ]]; then
      local session_id="${HOST:-unknown}:${TMUX_PANE:-${SSH_TTY:-local}}:$$"
      print -rn -- "$_ASTER_COMMAND" | command aster record \
        --stdin \
        --cwd "$_ASTER_COMMAND_CWD" \
        --exit-code "$exit_code" \
        --session "$session_id" >/dev/null 2>&1 &!
      _ASTER_COMMAND=""
      _ASTER_COMMAND_CWD=""
    fi
    _aster_tmux_title "${ASTER_TMUX_SHELL_TITLE:-aster}"
    return 0
  }

  _aster_menu_cancel_query() {
    local fd="$_ASTER_MENU_REQUEST_FD"
    if (( fd >= 0 )); then
      zle -F "$fd" 2>/dev/null
      exec {fd}<&-
    fi
    _ASTER_MENU_REQUEST_FD=-1
  }

  _aster_native_cancel() {
    local fd="$_ASTER_NATIVE_REQUEST_FD"
    if (( fd >= 0 )); then
      zle -F "$fd" 2>/dev/null
      exec {fd}<&-
    fi
    if (( _ASTER_NATIVE_REQUEST_PID > 0 )); then
      kill "$_ASTER_NATIVE_REQUEST_PID" 2>/dev/null
    fi
    _ASTER_NATIVE_REQUEST_FD=-1
    _ASTER_NATIVE_REQUEST_PID=-1
    _ASTER_NATIVE_REQUEST_TICKS=0
    _ASTER_NATIVE_START_TICKS=0
  }

  _aster_preview_cancel() {
    local fd="$_ASTER_PREVIEW_FD"
    if (( fd >= 0 )); then
      zle -F "$fd" 2>/dev/null
      exec {fd}<&-
    fi
    (( _ASTER_PREVIEW_PID > 0 )) && kill "$_ASTER_PREVIEW_PID" 2>/dev/null
    _ASTER_PREVIEW_FD=-1
    _ASTER_PREVIEW_PID=-1
    _ASTER_PREVIEW_TICKS=0
  }

  _aster_preview_clear() {
    _aster_preview_cancel
    _ASTER_PREVIEW_TARGET=""
    _ASTER_PREVIEW_PATH=""
    _ASTER_PREVIEW_LINES=()
  }

  _aster_preview_consider() {
    local display source target path
    if (( ${COLUMNS:-80} < 100 || ! _ASTER_MENU_ACTIVE )); then
      _aster_preview_clear
      return
    fi
    display="${_ASTER_MENU_DISPLAYS[$_ASTER_MENU_INDEX]}"
    source="${_ASTER_MENU_SOURCES[$_ASTER_MENU_INDEX]}"
    target="${source}:${display}"
    [[ "$target" == "$_ASTER_PREVIEW_TARGET" ]] && return
    _aster_preview_clear
    _ASTER_PREVIEW_TARGET="$target"
    if [[ "$source" == native ]]; then
      path="${display##* }"
      [[ -n "$path" ]] || return
      _ASTER_PREVIEW_PATH="$path"
    fi
  }

  _aster_preview_ready() {
    local fd="$1" line
    local -a lines
    if (( fd != _ASTER_PREVIEW_FD )); then
      zle -F "$fd" 2>/dev/null
      exec {fd}<&-
      return 0
    fi
    zle -F "$fd"
    while IFS= read -r -u "$fd" -d '' line; do
      lines+=("$line")
      (( ${#lines} >= 10 )) && break
    done
    exec {fd}<&-
    _ASTER_PREVIEW_FD=-1
    _ASTER_PREVIEW_PID=-1
    _ASTER_PREVIEW_TICKS=0
    _ASTER_PREVIEW_PATH=""
    (( ${#lines} )) && _ASTER_PREVIEW_LINES=("${lines[@]}") || \
      _ASTER_PREVIEW_LINES=("Preview unavailable")
    _aster_menu_publish
  }

  _aster_menu_cancel_request() {
    _aster_menu_cancel_query
    _aster_native_cancel
    _ASTER_MENU_REQUEST_BUFFER=""
    _ASTER_MENU_REQUEST_CWD=""
    _ASTER_MENU_REQUEST_CURSOR=0
    _ASTER_MENU_REQUEST_DIRTY=0
    _ASTER_MENU_REFRESH_TICKS=0
    _ASTER_MENU_RESTORE_DISPLAY=""
    _ASTER_NATIVE_REQUESTED=0
    _ASTER_NATIVE_START_TICKS=0
  }

  _aster_fuzzy_reset() {
    if (( _ASTER_FUZZY_ACTIVE && _ASTER_FUZZY_KEYTIMEOUT >= 0 )); then
      KEYTIMEOUT=$_ASTER_FUZZY_KEYTIMEOUT
    fi
    if (( _ASTER_FUZZY_ACTIVE )) && [[ -n "$_ASTER_FUZZY_PREVIOUS_KEYMAP" ]]; then
      zle -K "$_ASTER_FUZZY_PREVIOUS_KEYMAP" 2>/dev/null
    fi
    _ASTER_FUZZY_ACTIVE=0
    _ASTER_FUZZY_BASE=""
    _ASTER_FUZZY_QUERY=""
    _ASTER_FUZZY_KEYTIMEOUT=-1
    _ASTER_FUZZY_PREVIOUS_KEYMAP=""
  }

  _aster_menu_clear() {
    local preserve_buffer="${1:-0}"
    _aster_menu_cancel_request
    _ASTER_MENU_ACTIVE=0
    _ASTER_MENU_INDEX=1
    _ASTER_MENU_START=1
    _ASTER_RESTORE_HIGHLIGHTS=0
    _ASTER_CAPTURE_FOREIGN_HIGHLIGHTS=0
    _aster_fuzzy_reset
    _aster_preview_clear
    (( preserve_buffer )) || _ASTER_MENU_BUFFER=""
    _ASTER_MENU_ACCEPTS=()
    _ASTER_MENU_DISPLAYS=()
    _ASTER_MENU_DESCRIPTIONS=()
    _ASTER_MENU_KINDS=()
    _ASTER_MENU_SOURCES=()
    _ASTER_DAEMON_ACCEPTS=()
    _ASTER_DAEMON_DISPLAYS=()
    _ASTER_DAEMON_DESCRIPTIONS=()
    _ASTER_DAEMON_KINDS=()
    _ASTER_DAEMON_SOURCES=()
    _ASTER_NATIVE_ACCEPTS=()
    _ASTER_NATIVE_DISPLAYS=()
    _ASTER_NATIVE_DESCRIPTIONS=()
    if (( _ASTER_MENU_OWNS_DISPLAY )); then
      POSTDISPLAY=""
      region_highlight=( "${(@)region_highlight:#*memo=aster*}" )
      _ASTER_MENU_OWNS_DISPLAY=0
    fi
  }

  _aster_fuzzy_start() {
    (( CURSOR == ${#BUFFER} )) || return 1
    _ASTER_FUZZY_KEYTIMEOUT=$KEYTIMEOUT
    _ASTER_FUZZY_PREVIOUS_KEYMAP="$KEYMAP"
    KEYTIMEOUT=1
    _ASTER_FUZZY_ACTIVE=1
    zle -K aster-fuzzy
    _ASTER_FUZZY_BASE="$BUFFER"
    _ASTER_FUZZY_QUERY=""
    _ASTER_MENU_BUFFER="$BUFFER"
    _aster_menu_schedule
    _aster_menu_render
  }

  _aster_fuzzy_refresh() {
    _ASTER_MENU_BUFFER="$BUFFER"
    _aster_menu_schedule
    _aster_menu_render
  }

  _aster_menu_render() {
    local index display description kind icon marker row top bottom fill ghost=""
    local horizontal="─" vertical="│" top_left="╭" top_right="╮"
    local bottom_left="╰" bottom_right="╯" separator="·" ellipsis="…"
    local selected_marker="▶ " history_icon="↺" command_icon="❯" native_icon="⇥"
    if (( ! _ASTER_UTF8_UI )); then
      horizontal="-"
      vertical="|"
      top_left="+"
      top_right="+"
      bottom_left="+"
      bottom_right="+"
      separator="|"
      ellipsis="~"
      selected_marker="> "
      history_icon="H"
      command_icon="$"
      native_icon="T"
    fi
    local input="${BUFFER:-$_ASTER_MENU_REQUEST_BUFFER}"
    local virtual_query=""
    (( _ASTER_FUZZY_ACTIVE )) && virtual_query="$_ASTER_FUZZY_QUERY"
    local cursor_position=$CURSOR
    if [[ -z "$BUFFER" && -n "$_ASTER_MENU_REQUEST_BUFFER" ]]; then
      cursor_position=$_ASTER_MENU_REQUEST_CURSOR
    fi
    local box_width=$(( ${COLUMNS:-80} - 2 ))
    (( box_width > __ASTER_UI_MENU_WIDTH__ )) && box_width=__ASTER_UI_MENU_WIDTH__
    if (( box_width < 40 )); then
      POSTDISPLAY="$virtual_query"
      return 0
    fi

    local total=${#_ASTER_MENU_DISPLAYS}
    if (( total == 0 )); then
      region_highlight=( "${(@)region_highlight:#*memo=aster*}" )
      POSTDISPLAY="$virtual_query"
      if [[ -n "$virtual_query" ]]; then
        region_highlight+=("${#input} $(( ${#input} + ${#virtual_query} )) fg=__ASTER_UI_ACCENT__,bold memo=aster")
      fi
      _ASTER_MENU_OWNS_DISPLAY=1
      return 0
    fi
    local window_size=$total
    (( window_size > __ASTER_UI_MAX_VISIBLE__ )) && window_size=__ASTER_UI_MAX_VISIBLE__
    local max_start=$(( total - window_size + 1 ))
    if (( window_size > 2 )); then
      (( _ASTER_MENU_INDEX <= _ASTER_MENU_START && _ASTER_MENU_START > 1 )) && \
        _ASTER_MENU_START=$(( _ASTER_MENU_INDEX - 1 ))
      (( _ASTER_MENU_INDEX >= _ASTER_MENU_START + window_size - 1 )) && \
        _ASTER_MENU_START=$(( _ASTER_MENU_INDEX - window_size + 2 ))
    else
      (( _ASTER_MENU_INDEX < _ASTER_MENU_START )) && _ASTER_MENU_START=$_ASTER_MENU_INDEX
      (( _ASTER_MENU_INDEX >= _ASTER_MENU_START + window_size )) && \
        _ASTER_MENU_START=$(( _ASTER_MENU_INDEX - window_size + 1 ))
    fi
    (( _ASTER_MENU_START < 1 )) && _ASTER_MENU_START=1
    (( _ASTER_MENU_START > max_start )) && _ASTER_MENU_START=$max_start
    local end=$(( _ASTER_MENU_START + window_size - 1 ))

    local description_width=24
    (( box_width < 64 )) && description_width=16
    local title_width=$(( box_width - description_width - 9 ))
    local top_prefix="${top_left}${horizontal}"
    local count=" $_ASTER_MENU_INDEX/$total "
    printf -v fill '%*s' "$(( box_width - ${#top_prefix} - ${#count} - 1 ))" ""
    fill="${fill// /$horizontal}"
    top="${top_prefix}${fill}${count}${top_right}"
    local footer=" S-Tab/K up ${separator} C-N down ${separator} Tab part ${separator} __ASTER_COMPLETION_KEY_LABEL__ full "
    (( _ASTER_FUZZY_ACTIVE )) && \
      footer=" Esc exit ${separator} C-K up ${separator} C-N down ${separator} Tab choose "
    local bottom_prefix="${bottom_left}${horizontal}${footer}"
    printf -v fill '%*s' "$(( box_width - ${#bottom_prefix} - 1 ))" ""
    fill="${fill// /$horizontal}"
    bottom="${bottom_prefix}${fill}${bottom_right}"

    local indent=$(( __ASTER_UI_PROMPT_OFFSET__ + cursor_position ))
    local max_indent=$(( ${COLUMNS:-80} - box_width - 1 ))
    (( indent > max_indent )) && indent=$max_indent
    (( indent < 0 )) && indent=0
    local padding
    printf -v padding '%*s' "$indent" ""

    local selected="$_ASTER_MENU_DISPLAYS[$_ASTER_MENU_INDEX]"
    _aster_preview_consider
    if (( ! _ASTER_FUZZY_ACTIVE && cursor_position == ${#input} )) &&
       [[ -n "$input" && "$selected" == "$input"* ]]; then
      ghost="${selected[${#input}+1,-1]}"
    fi

    region_highlight=( "${(@)region_highlight:#*memo=aster*}" )
    (( _ASTER_FUZZY_ACTIVE )) && POSTDISPLAY="$virtual_query" || POSTDISPLAY="$ghost"
    local buffer_end=${#input}
    if [[ -n "$virtual_query" ]]; then
      region_highlight+=("$buffer_end $(( buffer_end + ${#virtual_query} )) fg=__ASTER_UI_ACCENT__,bold memo=aster")
    elif [[ -n "$ghost" ]]; then
      region_highlight+=("$buffer_end $(( buffer_end + ${#ghost} )) fg=__ASTER_UI_GHOST__ memo=aster")
    fi

    local line_start=$(( ${#input} + ${#POSTDISPLAY} + 1 + indent ))
    POSTDISPLAY+=$'\n'"${padding}${top}"
    region_highlight+=("$line_start $(( line_start + ${#top} )) fg=__ASTER_UI_BORDER__ memo=aster")

    for (( index = _ASTER_MENU_START; index <= end; index++ )); do
      display="$_ASTER_MENU_DISPLAYS[$index]"
      if (( ${#display} > title_width )); then
        display="${display[1,$(( title_width - 1 ))]}${ellipsis}"
      fi
      description="$_ASTER_MENU_DESCRIPTIONS[$index]"
      if (( ${#description} > description_width )); then
        description="${description[1,$(( description_width - 1 ))]}${ellipsis}"
      fi
      kind="$_ASTER_MENU_KINDS[$index]"
      case "$kind" in
        history) icon="$history_icon" ;;
        command) icon="$command_icon" ;;
        native) icon="$native_icon" ;;
        *) icon="." ;;
      esac
      marker="  "
      (( index == _ASTER_MENU_INDEX )) && marker="$selected_marker"
      printf -v row '%s %s%s %-*s %-*s %s' \
        "$vertical" "$marker" "$icon" "$title_width" "$display" \
        "$description_width" "$description" "$vertical"

      line_start=$(( ${#input} + ${#POSTDISPLAY} + 1 + indent ))
      POSTDISPLAY+=$'\n'"${padding}${row}"
      if (( index == _ASTER_MENU_INDEX )); then
        region_highlight+=("$(( line_start + 1 )) $(( line_start + ${#row} - 1 )) bg=__ASTER_UI_SELECTED_BACKGROUND__,fg=__ASTER_UI_SELECTED_TEXT__ memo=aster")
        region_highlight+=("$(( line_start + 2 )) $(( line_start + 3 )) bg=__ASTER_UI_SELECTED_BACKGROUND__,fg=__ASTER_UI_ACCENT__,bold memo=aster")
        region_highlight+=("$(( line_start + 4 )) $(( line_start + 5 )) bg=__ASTER_UI_SELECTED_BACKGROUND__,fg=__ASTER_UI_ACCENT__ memo=aster")
      else
        region_highlight+=("$(( line_start + 1 )) $(( line_start + ${#row} - 1 )) fg=__ASTER_UI_TEXT__ memo=aster")
        region_highlight+=("$(( line_start + 4 )) $(( line_start + 5 )) fg=__ASTER_UI_MUTED__ memo=aster")
      fi
      region_highlight+=("$line_start $(( line_start + 1 )) fg=__ASTER_UI_BORDER__ memo=aster")
      region_highlight+=("$(( line_start + ${#row} - 1 )) $(( line_start + ${#row} )) fg=__ASTER_UI_BORDER__ memo=aster")

      local match_length=0
      (( ! _ASTER_FUZZY_ACTIVE )) && match_length=${#input}
      (( match_length > title_width )) && match_length=$title_width
      if (( match_length > 0 )); then
        if (( index == _ASTER_MENU_INDEX )); then
          region_highlight+=("$(( line_start + 6 )) $(( line_start + 6 + match_length )) bg=__ASTER_UI_SELECTED_BACKGROUND__,fg=__ASTER_UI_SELECTED_TEXT__,bold memo=aster")
        else
          region_highlight+=("$(( line_start + 6 )) $(( line_start + 6 + match_length )) fg=__ASTER_UI_SELECTED_TEXT__,bold memo=aster")
        fi
      fi
      local description_start=$(( line_start + 6 + title_width + 1 ))
      if (( index == _ASTER_MENU_INDEX )); then
        region_highlight+=("$description_start $(( description_start + description_width )) bg=__ASTER_UI_SELECTED_BACKGROUND__,fg=__ASTER_UI_SELECTED_SOURCE__ memo=aster")
      else
        region_highlight+=("$description_start $(( description_start + description_width )) fg=__ASTER_UI_MUTED__ memo=aster")
      fi
    done

    line_start=$(( ${#input} + ${#POSTDISPLAY} + 1 + indent ))
    POSTDISPLAY+=$'\n'"${padding}${bottom}"
    region_highlight+=("$line_start $(( line_start + ${#bottom} )) fg=__ASTER_UI_BORDER__ memo=aster")
    local preview_source="${_ASTER_MENU_SOURCES[$_ASTER_MENU_INDEX]}"
    local preview_description="${_ASTER_MENU_DESCRIPTIONS[$_ASTER_MENU_INDEX]}"
    local show_preview=0
    if [[ "$preview_source" == command && -n "$preview_description" &&
          "$preview_description" != "System command" &&
          "$preview_description" != "Executable installed by "* ]]; then
      show_preview=1
    elif [[ "$preview_source" == native && ${#_ASTER_PREVIEW_LINES} -gt 0 &&
            "${_ASTER_PREVIEW_LINES[1]}" != "Preview unavailable" &&
            "${_ASTER_PREVIEW_LINES[1]}" != "Preview timed out" ]]; then
      show_preview=1
    fi
    if (( ${COLUMNS:-80} >= 100 && show_preview )); then
      local preview_width=$(( ${COLUMNS:-80} - indent - 1 ))
      (( preview_width > 96 )) && preview_width=96
      if (( preview_width >= 40 )); then
        local preview_label=" Preview: ${selected} " preview_top preview_bottom preview_line
        local preview_content_width=$(( preview_width - 4 ))
        local -a preview_lines
        if (( ${#_ASTER_PREVIEW_LINES} )); then
          preview_lines=("${_ASTER_PREVIEW_LINES[@]}")
        else
          preview_lines=("Source: ${_ASTER_MENU_SOURCES[$_ASTER_MENU_INDEX]} / ${_ASTER_MENU_KINDS[$_ASTER_MENU_INDEX]}")
          preview_lines+=("$preview_description")
        fi
        (( ${#preview_label} > preview_width - 2 )) && \
          preview_label="${preview_label[1,$(( preview_width - 3 ))]}${ellipsis}"
        printf -v fill '%*s' "$(( preview_width - ${#preview_label} - 2 ))" ""
        fill="${fill// /$horizontal}"
        preview_top="${top_left}${preview_label}${fill}${top_right}"
        line_start=$(( ${#input} + ${#POSTDISPLAY} + 1 + indent ))
        POSTDISPLAY+=$'\n'"${padding}${preview_top}"
        region_highlight+=("$line_start $(( line_start + ${#preview_top} )) fg=__ASTER_UI_BORDER__ memo=aster")
        local preview_index
        for (( preview_index = 1; preview_index <= ${#preview_lines} && preview_index <= 8; preview_index++ )); do
          preview_line="${preview_lines[$preview_index]}"
          (( ${#preview_line} > preview_content_width )) && \
            preview_line="${preview_line[1,$(( preview_content_width - 1 ))]}${ellipsis}"
          printf -v row '%s %-*s %s' "$vertical" "$preview_content_width" "$preview_line" "$vertical"
          line_start=$(( ${#input} + ${#POSTDISPLAY} + 1 + indent ))
          POSTDISPLAY+=$'\n'"${padding}${row}"
          region_highlight+=("$line_start $(( line_start + 1 )) fg=__ASTER_UI_BORDER__ memo=aster")
          region_highlight+=("$(( line_start + 1 )) $(( line_start + ${#row} - 1 )) fg=__ASTER_UI_TEXT__ memo=aster")
          region_highlight+=("$(( line_start + ${#row} - 1 )) $(( line_start + ${#row} )) fg=__ASTER_UI_BORDER__ memo=aster")
        done
        printf -v fill '%*s' "$(( preview_width - 2 ))" ""
        fill="${fill// /$horizontal}"
        preview_bottom="${bottom_left}${fill}${bottom_right}"
        line_start=$(( ${#input} + ${#POSTDISPLAY} + 1 + indent ))
        POSTDISPLAY+=$'\n'"${padding}${preview_bottom}"
        region_highlight+=("$line_start $(( line_start + ${#preview_bottom} )) fg=__ASTER_UI_BORDER__ memo=aster")
      fi
    fi
    _ASTER_MENU_OWNS_DISPLAY=1
  }

  _aster_menu_query() {
    local LC_ALL=C cursor_byte accept display description kind source
    _aster_menu_cancel_request
    cursor_byte=${#LBUFFER}
    _ASTER_MENU_BUFFER="$BUFFER"
    _ASTER_MENU_ACCEPTS=()
    _ASTER_MENU_DISPLAYS=()
    _ASTER_MENU_DESCRIPTIONS=()
    _ASTER_MENU_KINDS=()
    _ASTER_MENU_SOURCES=()
    while IFS= read -r -d '' accept &&
          IFS= read -r -d '' display &&
          IFS= read -r -d '' description &&
          IFS= read -r -d '' kind &&
          IFS= read -r -d '' source; do
      _ASTER_MENU_ACCEPTS+=("$accept")
      _ASTER_MENU_DISPLAYS+=("$display")
      _ASTER_MENU_DESCRIPTIONS+=("$description")
      _ASTER_MENU_KINDS+=("$kind")
      _ASTER_MENU_SOURCES+=("$source")
    done < <(print -rn -- "$BUFFER" | command aster complete \
      --stdin \
      --cursor "$cursor_byte" \
      --cwd "$PWD" \
      --format zsh 2>/dev/null)
    if (( ${#_ASTER_MENU_ACCEPTS} == 0 )); then
      _aster_menu_clear 1
      return 1
    fi
    _ASTER_MENU_ACTIVE=1
    _ASTER_MENU_INDEX=1
    _ASTER_MENU_START=1
    _aster_menu_render
    return 0
  }

  _aster_next_segment() {
    local value="$1" character
    local index saw_non_whitespace=0
    REPLY="$value"
    for (( index = 1; index <= ${#value}; index++ )); do
      character="${value[$index]}"
      if [[ "$character" == [[:space:]] ]]; then
        if (( saw_non_whitespace )); then
          REPLY="${value[1,$index]}"
          return 0
        fi
        continue
      fi
      saw_non_whitespace=1
      if [[ "$character" == [/:=,] ]]; then
        REPLY="${value[1,$index]}"
        return 0
      fi
    done
  }

  _aster_menu_accept() {
    local mode="${1:-candidate}"
    local accept="${_ASTER_MENU_ACCEPTS[$_ASTER_MENU_INDEX]}"
    local display="${_ASTER_MENU_DISPLAYS[$_ASTER_MENU_INDEX]}"
    local source="${_ASTER_MENU_SOURCES[$_ASTER_MENU_INDEX]}"
    (( CURSOR == ${#BUFFER} )) || return 1
    if (( _ASTER_FUZZY_ACTIVE )); then
      _aster_menu_clear
      BUFFER="$accept"
      [[ "$source" == command && "$BUFFER" != *[[:space:]]* ]] && BUFFER+=" "
      CURSOR=${#BUFFER}
      _ASTER_MENU_BUFFER="$BUFFER"
      _aster_menu_schedule
      return 0
    fi
    if [[ "$mode" == segment ]]; then
      _aster_next_segment "$accept"
      accept="$REPLY"
    fi
    LBUFFER+="$accept"
    if [[ "$source" == native && "$BUFFER" == "$display" &&
          "${BUFFER[-1]}" != [/:=,[:space:]] ]]; then
      LBUFFER+=" "
    fi
    POSTDISPLAY=""
    if [[ "$mode" == segment ]]; then
      _aster_menu_refresh
    else
      _aster_menu_clear
      _ASTER_MENU_BUFFER="$BUFFER"
      _aster_menu_schedule
    fi
  }

  _aster_call_native_completion() {
    local widget="$1"
    _ASTER_IN_NATIVE_COMPLETION=1
    {
      zle "$widget"
    } always {
      _ASTER_IN_NATIVE_COMPLETION=0
    }
  }

  _aster_menu_refresh() {
    local selected="$_ASTER_MENU_DISPLAYS[$_ASTER_MENU_INDEX]"
    local previous_buffer="$_ASTER_MENU_BUFFER" delta="" accept
    local index retained_index
    local -a accepts displays descriptions kinds sources
    if (( _ASTER_MENU_ACTIVE )) && [[ "$BUFFER" == "$previous_buffer"* ]]; then
      delta="${BUFFER[${#previous_buffer}+1,-1]}"
      for (( index = 1; index <= ${#_ASTER_MENU_DISPLAYS}; index++ )); do
        [[ "${_ASTER_MENU_DISPLAYS[$index]}" == "$BUFFER"* ]] || continue
        accept="${_ASTER_MENU_ACCEPTS[$index]}"
        if [[ -n "$delta" ]]; then
          [[ "$accept" == "$delta"* ]] || continue
          accept="${accept[${#delta}+1,-1]}"
        fi
        [[ -n "$accept" ]] || continue
        accepts+=("$accept")
        displays+=("${_ASTER_MENU_DISPLAYS[$index]}")
        descriptions+=("${_ASTER_MENU_DESCRIPTIONS[$index]}")
        kinds+=("${_ASTER_MENU_KINDS[$index]}")
        sources+=("${_ASTER_MENU_SOURCES[$index]}")
      done
    fi
    if (( ${#displays} )); then
      _ASTER_MENU_ACCEPTS=("${accepts[@]}")
      _ASTER_MENU_DISPLAYS=("${displays[@]}")
      _ASTER_MENU_DESCRIPTIONS=("${descriptions[@]}")
      _ASTER_MENU_KINDS=("${kinds[@]}")
      _ASTER_MENU_SOURCES=("${sources[@]}")
      retained_index=${_ASTER_MENU_DISPLAYS[(Ie)$selected]}
      (( retained_index )) || retained_index=1
      _ASTER_MENU_INDEX=$retained_index
      _ASTER_MENU_START=$retained_index
      _ASTER_MENU_BUFFER="$BUFFER"
      _ASTER_CAPTURE_FOREIGN_HIGHLIGHTS=1
      _aster_menu_render
    else
      _aster_menu_clear
    fi
    _ASTER_MENU_BUFFER="$BUFFER"
    if [[ -n "$BUFFER" ]] && (( CURSOR == ${#BUFFER} )); then
      _aster_menu_schedule
    fi
  }

  _aster_menu_schedule() {
    local LC_ALL=C
    _aster_menu_cancel_query
    _aster_native_cancel
    _ASTER_MENU_REQUEST_BUFFER="$BUFFER"
    _ASTER_MENU_REQUEST_CWD="$PWD"
    _ASTER_MENU_REQUEST_CURSOR=${#LBUFFER}
    _ASTER_MENU_REQUEST_DIRTY=1
    _ASTER_NATIVE_REQUESTED=0
    _ASTER_NATIVE_START_TICKS=0
    _ASTER_DAEMON_ACCEPTS=()
    _ASTER_DAEMON_DISPLAYS=()
    _ASTER_DAEMON_DESCRIPTIONS=()
    _ASTER_DAEMON_KINDS=()
    _ASTER_DAEMON_SOURCES=()
    _ASTER_NATIVE_ACCEPTS=()
    _ASTER_NATIVE_DISPLAYS=()
    _ASTER_NATIVE_DESCRIPTIONS=()
  }

  _aster_menu_publish() {
    local selected="${_ASTER_MENU_DISPLAYS[$_ASTER_MENU_INDEX]}"
    local index display
    local -a redraw_hooks apply_hooks
    local limit=$(( __ASTER_COMPLETION_MAX_CANDIDATES__ * 2 ))
    _ASTER_MENU_ACCEPTS=()
    _ASTER_MENU_DISPLAYS=()
    _ASTER_MENU_DESCRIPTIONS=()
    _ASTER_MENU_KINDS=()
    _ASTER_MENU_SOURCES=()

    for (( index = 1; index <= ${#_ASTER_DAEMON_ACCEPTS}; index++ )); do
      [[ "${_ASTER_DAEMON_SOURCES[$index]}" == history ]] || continue
      display="${_ASTER_DAEMON_DISPLAYS[$index]}"
      [[ -n "$display" ]] && (( ! ${_ASTER_MENU_DISPLAYS[(Ie)$display]} )) || continue
      _ASTER_MENU_ACCEPTS+=("${_ASTER_DAEMON_ACCEPTS[$index]}")
      _ASTER_MENU_DISPLAYS+=("$display")
      _ASTER_MENU_DESCRIPTIONS+=("${_ASTER_DAEMON_DESCRIPTIONS[$index]}")
      _ASTER_MENU_KINDS+=("${_ASTER_DAEMON_KINDS[$index]}")
      _ASTER_MENU_SOURCES+=("${_ASTER_DAEMON_SOURCES[$index]}")
      (( ${#_ASTER_MENU_ACCEPTS} >= limit )) && break
    done

    if (( ${#_ASTER_MENU_ACCEPTS} < limit )); then
      for (( index = 1; index <= ${#_ASTER_NATIVE_ACCEPTS}; index++ )); do
        display="${_ASTER_NATIVE_DISPLAYS[$index]}"
        [[ -n "$display" ]] && (( ! ${_ASTER_MENU_DISPLAYS[(Ie)$display]} )) || continue
        _ASTER_MENU_ACCEPTS+=("${_ASTER_NATIVE_ACCEPTS[$index]}")
        _ASTER_MENU_DISPLAYS+=("$display")
        _ASTER_MENU_DESCRIPTIONS+=("${_ASTER_NATIVE_DESCRIPTIONS[$index]}")
        _ASTER_MENU_KINDS+=("native")
        _ASTER_MENU_SOURCES+=("native")
        (( ${#_ASTER_MENU_ACCEPTS} >= limit )) && break
      done
    fi

    if (( ${#_ASTER_MENU_ACCEPTS} < limit )); then
      for (( index = 1; index <= ${#_ASTER_DAEMON_ACCEPTS}; index++ )); do
        [[ "${_ASTER_DAEMON_SOURCES[$index]}" == history ]] && continue
        display="${_ASTER_DAEMON_DISPLAYS[$index]}"
        [[ -n "$display" ]] && (( ! ${_ASTER_MENU_DISPLAYS[(Ie)$display]} )) || continue
        _ASTER_MENU_ACCEPTS+=("${_ASTER_DAEMON_ACCEPTS[$index]}")
        _ASTER_MENU_DISPLAYS+=("$display")
        _ASTER_MENU_DESCRIPTIONS+=("${_ASTER_DAEMON_DESCRIPTIONS[$index]}")
        _ASTER_MENU_KINDS+=("${_ASTER_DAEMON_KINDS[$index]}")
        _ASTER_MENU_SOURCES+=("${_ASTER_DAEMON_SOURCES[$index]}")
        (( ${#_ASTER_MENU_ACCEPTS} >= limit )) && break
      done
    fi

    _ASTER_MENU_RESTORE_DISPLAY="$selected"
    zstyle -a zle-line-pre-redraw widgets redraw_hooks
    apply_hooks=( "${(@)redraw_hooks:#*:_zsh_highlight__zle-line-pre-redraw}" )
    if (( ${#apply_hooks} != ${#redraw_hooks} )); then
      zstyle zle-line-pre-redraw widgets "${apply_hooks[@]}"
      {
        zle aster-menu-apply
      } always {
        zstyle zle-line-pre-redraw widgets "${redraw_hooks[@]}"
      }
    else
      zle aster-menu-apply
    fi
    region_highlight=( "${_ASTER_RENDERED_HIGHLIGHTS[@]}" )
  }

  _aster_menu_request_ready() {
    local fd="$1" accept display description kind source pending
    local any_pending=0
    local -a accepts displays descriptions kinds sources
    if (( fd != _ASTER_MENU_REQUEST_FD )); then
      zle -F "$fd" 2>/dev/null
      exec {fd}<&-
      return 0
    fi

    zle -F "$fd"
    BUFFER="$_ASTER_MENU_REQUEST_BUFFER"
    CURSOR=$_ASTER_MENU_REQUEST_CURSOR
    while IFS= read -r -u "$fd" -d '' accept &&
          IFS= read -r -u "$fd" -d '' display &&
          IFS= read -r -u "$fd" -d '' description &&
          IFS= read -r -u "$fd" -d '' kind &&
          IFS= read -r -u "$fd" -d '' source &&
          IFS= read -r -u "$fd" -d '' pending; do
      accepts+=("$accept")
      displays+=("$display")
      descriptions+=("$description")
      kinds+=("$kind")
      sources+=("$source")
      [[ "$pending" == true ]] && any_pending=1
    done
    exec {fd}<&-

    _ASTER_MENU_REQUEST_FD=-1
    _ASTER_DAEMON_ACCEPTS=("${accepts[@]}")
    _ASTER_DAEMON_DISPLAYS=("${displays[@]}")
    _ASTER_DAEMON_DESCRIPTIONS=("${descriptions[@]}")
    _ASTER_DAEMON_KINDS=("${kinds[@]}")
    _ASTER_DAEMON_SOURCES=("${sources[@]}")
    (( any_pending )) && _ASTER_MENU_REFRESH_TICKS=5 || _ASTER_MENU_REFRESH_TICKS=0
    if (( ! _ASTER_FUZZY_ACTIVE && ${#accepts} == 0 && _ASTER_MENU_ACTIVE &&
          $+functions[_main_complete] )) &&
       (( ! _ASTER_NATIVE_REQUESTED || _ASTER_NATIVE_REQUEST_FD >= 0 )); then
      return 0
    fi
    _aster_menu_publish
  }

  _aster_native_request_ready() {
    local fd="$1" accept display description
    local -a accepts displays descriptions
    if (( fd != _ASTER_NATIVE_REQUEST_FD )); then
      zle -F "$fd" 2>/dev/null
      exec {fd}<&-
      return 0
    fi

    zle -F "$fd"
    BUFFER="$_ASTER_MENU_REQUEST_BUFFER"
    CURSOR=$_ASTER_MENU_REQUEST_CURSOR
    while IFS= read -r -u "$fd" -d '' accept &&
          IFS= read -r -u "$fd" -d '' display &&
          IFS= read -r -u "$fd" -d '' description; do
      accepts+=("$accept")
      displays+=("$display")
      descriptions+=("$description")
    done
    exec {fd}<&-
    _ASTER_NATIVE_REQUEST_FD=-1
    _ASTER_NATIVE_REQUEST_PID=-1
    _ASTER_NATIVE_REQUEST_TICKS=0

    _ASTER_NATIVE_ACCEPTS=("${accepts[@]}")
    _ASTER_NATIVE_DISPLAYS=("${displays[@]}")
    _ASTER_NATIVE_DESCRIPTIONS=("${descriptions[@]}")
    _aster_menu_publish
  }

  _aster_native_capture_widget() {
    local fd
    exec {fd}< <(
      local original_lbuffer="$LBUFFER"
      local -a accepts displays descriptions

      compadd() {
        local argument status current_prefix="$PREFIX"
        local added_prefix="" hidden_prefix="" ignored_prefix=""
        local added_suffix="" hidden_suffix="" ignored_suffix=""
        local index=1
        for argument in "$@"; do
          if [[ "$argument" == -A || "$argument" == -O || "$argument" == -D ]]; then
            builtin compadd "$@"
            return
          fi
        done
        while (( index <= $# )); do
          argument="${@[index]}"
          case "$argument" in
            --) break ;;
            -P|-p|-i|-S|-s|-I)
              (( index++ ))
              (( index <= $# )) || break
              case "$argument" in
                -P) added_prefix="${@[index]}" ;;
                -p) hidden_prefix="${@[index]}" ;;
                -i) ignored_prefix="${@[index]}" ;;
                -S) added_suffix="${@[index]}" ;;
                -s) hidden_suffix="${@[index]}" ;;
                -I) ignored_suffix="${@[index]}" ;;
              esac
              ;;
          esac
          (( index++ ))
        done

        local -a generated
        generated=("${(@0)$(
          local -a matches
          builtin compadd -A matches "$@" 2>/dev/null
          local match
          for match in "${matches[@]}"; do
            print -rn -- "$match"$'\0'
          done
        )}")

        if [[ -z "$IPREFIX$ISUFFIX$QIPREFIX$QISUFFIX$SUFFIX$added_prefix$hidden_prefix$ignored_prefix" ]]; then
          local base_length=$(( ${#original_lbuffer} - ${#current_prefix} ))
          local base="" match full accept
          (( base_length > 0 )) && base="${original_lbuffer[1,$base_length]}"
          if (( base_length >= 0 )) &&
             [[ -z "$current_prefix" ||
                "${original_lbuffer[$(( base_length + 1 )),-1]}" == "$current_prefix" ]]; then
            for match in "${generated[@]}"; do
              (( ${#displays} < __ASTER_COMPLETION_MAX_CANDIDATES__ )) || break
              [[ -n "$match" && "${(q)match}" == "$match" ]] || continue
              [[ -z "$current_prefix" ||
                 "${match[1,${#current_prefix}]}" == "$current_prefix" ]] || continue
              full="${base}${match}${hidden_suffix}${added_suffix}${ignored_suffix}"
              [[ "$full" == "$original_lbuffer"* && "$full" != "$original_lbuffer" ]] || continue
              (( ${displays[(Ie)$full]} )) && continue
              accept="${full[${#original_lbuffer}+1,-1]}"
              [[ -n "$accept" ]] || continue
              accepts+=("$accept")
              displays+=("$full")
              descriptions+=("Zsh completion")
            done
          fi
        fi

        builtin compadd "$@"
        status=$?
        return status
      }

      _main_complete >/dev/null 2>&1
      local index
      for (( index = 1; index <= ${#accepts}; index++ )); do
        printf '%s\0%s\0%s\0' \
          "${accepts[$index]}" \
          "${displays[$index]}" \
          "${descriptions[$index]}"
      done
    )
    _ASTER_NATIVE_REQUEST_FD="$fd"
    _ASTER_NATIVE_REQUEST_PID=$!
    _ASTER_NATIVE_REQUEST_TICKS=0
    zle -F "$fd" _aster_native_request_ready
    compstate[insert]=''
    compstate[list]=''
  }

  _aster_menu_apply_result() {
    local -a rendered_highlights
    if (( ${#_ASTER_MENU_ACCEPTS} == 0 )); then
      _ASTER_MENU_ACTIVE=0
      region_highlight=( "${_ASTER_FOREIGN_HIGHLIGHTS[@]}" )
      if (( _ASTER_FUZZY_ACTIVE )); then
        _aster_menu_render
      else
        POSTDISPLAY=""
      fi
      rendered_highlights=( "${region_highlight[@]}" )
      _ASTER_RENDERED_HIGHLIGHTS=( "${rendered_highlights[@]}" )
      _ASTER_RESTORE_HIGHLIGHTS=1
      zle -R
      region_highlight=( "${rendered_highlights[@]}" )
      return 0
    fi
    _ASTER_MENU_ACTIVE=1
    _ASTER_MENU_INDEX=1
    if [[ -n "$_ASTER_MENU_RESTORE_DISPLAY" ]]; then
      local index
      for (( index = 1; index <= ${#_ASTER_MENU_DISPLAYS}; index++ )); do
        if [[ "${_ASTER_MENU_DISPLAYS[$index]}" == "$_ASTER_MENU_RESTORE_DISPLAY" ]]; then
          _ASTER_MENU_INDEX=$index
          break
        fi
      done
    fi
    _ASTER_MENU_RESTORE_DISPLAY=""
    _ASTER_MENU_START=$_ASTER_MENU_INDEX
    _ASTER_MENU_BUFFER="$_ASTER_MENU_REQUEST_BUFFER"
    region_highlight=( "${_ASTER_FOREIGN_HIGHLIGHTS[@]}" )
    _aster_menu_render
    rendered_highlights=( "${region_highlight[@]}" )
    _ASTER_RENDERED_HIGHLIGHTS=( "${rendered_highlights[@]}" )
    _ASTER_RESTORE_HIGHLIGHTS=1
    zle -R
    region_highlight=( "${rendered_highlights[@]}" )
  }

  _aster_menu_start_ticker() {
    (( _ASTER_MENU_TICK_FD >= 0 )) && return 0
    local fd
    exec {fd}< <(
      if (( _ASTER_HAS_ZSELECT )); then
        while true; do
          zselect -t 3
          print -r -- tick || exit
        done
      else
        while sleep 0.03; do
          print -r -- tick || exit
        done
      fi
    )
    _ASTER_MENU_TICK_FD="$fd"
    zle -F "$fd" _aster_menu_tick
  }

  _aster_menu_stop_ticker() {
    local fd="$_ASTER_MENU_TICK_FD"
    if (( fd >= 0 )); then
      zle -F "$fd" 2>/dev/null
      exec {fd}<&-
      _ASTER_MENU_TICK_FD=-1
    fi
  }

  _aster_menu_tick() {
    local fd="$1" tick query_fd buffer cwd cursor
    if (( fd != _ASTER_MENU_TICK_FD )) || ! IFS= read -r -u "$fd" tick; then
      zle -F "$fd" 2>/dev/null
      exec {fd}<&-
      _ASTER_MENU_TICK_FD=-1
      return 0
    fi
    (( _ASTER_IN_NATIVE_COMPLETION )) && return 0
    if [[ -n "$_ASTER_PREVIEW_PATH" ]]; then
      (( _ASTER_PREVIEW_TICKS++ ))
      if (( _ASTER_PREVIEW_FD < 0 && _ASTER_PREVIEW_TICKS >= 2 )); then
        local preview_fd
        exec {preview_fd}< <(command aster preview-file \
          --path "$_ASTER_PREVIEW_PATH" \
          --cwd "$PWD" 2>/dev/null)
        _ASTER_PREVIEW_FD="$preview_fd"
        _ASTER_PREVIEW_PID=$!
        _ASTER_PREVIEW_TICKS=0
        zle -F "$preview_fd" _aster_preview_ready
      elif (( _ASTER_PREVIEW_FD >= 0 && _ASTER_PREVIEW_TICKS > 34 )); then
        _aster_preview_cancel
        _ASTER_PREVIEW_PATH=""
        _ASTER_PREVIEW_LINES=("Preview timed out")
        zle -R
      fi
    fi
    if (( _ASTER_NATIVE_REQUEST_FD >= 0 )); then
      (( _ASTER_NATIVE_REQUEST_TICKS++ ))
      if (( _ASTER_NATIVE_REQUEST_TICKS > 50 )); then
        _aster_native_cancel
        _aster_menu_publish
      fi
    fi
    if (( ! _ASTER_FUZZY_ACTIVE && ! _ASTER_NATIVE_REQUESTED )) &&
       [[ -n "$_ASTER_MENU_REQUEST_BUFFER" ]]; then
      (( _ASTER_NATIVE_START_TICKS++ ))
      if (( _ASTER_NATIVE_START_TICKS >= 2 )) && (( $+functions[_main_complete] )); then
        _ASTER_NATIVE_REQUESTED=1
        _aster_call_native_completion aster-native-capture
      fi
    fi
    if (( ! _ASTER_MENU_REQUEST_DIRTY )); then
      (( _ASTER_MENU_REFRESH_TICKS > 0 )) || return 0
      (( _ASTER_MENU_REFRESH_TICKS-- ))
      (( _ASTER_MENU_REFRESH_TICKS == 0 )) || return 0
      _ASTER_MENU_REQUEST_DIRTY=1
    fi

    _ASTER_MENU_REQUEST_DIRTY=0
    buffer="$_ASTER_MENU_REQUEST_BUFFER"
    cwd="$_ASTER_MENU_REQUEST_CWD"
    cursor="$_ASTER_MENU_REQUEST_CURSOR"
    if [[ -z "$buffer" ]]; then
      return 0
    fi

    _aster_menu_cancel_query
    if (( _ASTER_FUZZY_ACTIVE )); then
      exec {query_fd}< <(command aster fuzzy \
        --query "$_ASTER_FUZZY_QUERY" \
        --cwd "$cwd" \
        --format zsh-v2 2>/dev/null)
    else
      exec {query_fd}< <(print -rn -- "$buffer" | command aster complete \
        --stdin \
        --cursor "$cursor" \
        --cwd "$cwd" \
        --format zsh-v2 2>/dev/null)
    fi
    _ASTER_MENU_REQUEST_FD="$query_fd"
    zle -F "$query_fd" _aster_menu_request_ready
  }

  _aster_menu_line_init() {
    _aster_menu_start_ticker
  }

  _aster_menu_line_finish() {
    _aster_menu_clear
    _aster_menu_stop_ticker
  }

  _aster_self_insert() {
    if (( _ASTER_FUZZY_ACTIVE )); then
      _ASTER_FUZZY_QUERY+="$KEYS"
      _aster_fuzzy_refresh
      return
    fi
    zle _aster-native-self-insert
    _aster_menu_refresh
  }

  _aster_space() {
    if (( _ASTER_FUZZY_ACTIVE )); then
      _ASTER_FUZZY_QUERY+=" "
      _aster_fuzzy_refresh
      return
    fi
    if [[ "$LBUFFER" == *" " ]] && (( CURSOR == ${#BUFFER} )); then
      _aster_fuzzy_start
      return
    fi
    zle _aster-native-space
    _aster_menu_refresh
  }

  _aster_backward_delete() {
    if (( _ASTER_FUZZY_ACTIVE )); then
      if [[ -n "$_ASTER_FUZZY_QUERY" ]]; then
        _ASTER_FUZZY_QUERY="${_ASTER_FUZZY_QUERY[1,-2]}"
        _aster_fuzzy_refresh
      else
        _aster_menu_clear
        zle _aster-native-backward-delete
        _aster_menu_refresh
      fi
      return
    fi
    zle _aster-native-backward-delete
    _aster_menu_refresh
  }

  _aster_bracketed_paste() {
    _aster_menu_clear 1
    POSTDISPLAY=""
    zle _aster-native-bracketed-paste
    _aster_menu_refresh
  }

  _aster_tab() {
    if (( _ASTER_FUZZY_ACTIVE )); then
      if (( _ASTER_MENU_ACTIVE )); then
        _aster_menu_accept
      else
        zle beep
      fi
      return
    fi
    if (( _ASTER_MENU_ACTIVE && CURSOR == ${#BUFFER} )); then
      _aster_menu_accept segment
      return
    fi
    _aster_menu_clear
    POSTDISPLAY=""
    _aster_call_native_completion _aster-native-tab
    _ASTER_MENU_BUFFER="$BUFFER"
    [[ -n "$BUFFER" ]] && (( CURSOR == ${#BUFFER} )) && _aster_menu_schedule
  }

  _aster_shift_tab() {
    if (( _ASTER_MENU_ACTIVE )); then
      (( _ASTER_MENU_INDEX > 1 )) && (( _ASTER_MENU_INDEX-- ))
      _aster_menu_render
      return
    fi
    if (( _ASTER_FUZZY_ACTIVE )); then
      zle beep
      return
    fi
    _aster_menu_clear
    POSTDISPLAY=""
    _aster_call_native_completion _aster-native-shift-tab
    _ASTER_MENU_BUFFER="$BUFFER"
    [[ -n "$BUFFER" ]] && (( CURSOR == ${#BUFFER} )) && _aster_menu_schedule
  }

  _aster_complete() {
    if (( _ASTER_FUZZY_ACTIVE && ! _ASTER_MENU_ACTIVE )); then
      zle beep
      return
    fi
    if (( _ASTER_MENU_ACTIVE && CURSOR == ${#BUFFER} )); then
      _aster_menu_accept
    elif (( CURSOR == ${#BUFFER} )) && _aster_menu_query; then
      _aster_menu_accept
    else
      (( _ASTER_MENU_ACTIVE )) && _aster_menu_clear 1
      _aster_call_native_completion _aster-native-trigger
    fi
  }

  _aster_menu_down() {
    if (( _ASTER_MENU_ACTIVE )); then
      (( _ASTER_MENU_INDEX < ${#_ASTER_MENU_ACCEPTS} )) && (( _ASTER_MENU_INDEX++ ))
      _aster_menu_render
    elif (( _ASTER_FUZZY_ACTIVE )); then
      zle beep
    else
      zle _aster-native-down
      _aster_menu_refresh
    fi
  }

  _aster_menu_up() {
    if (( _ASTER_MENU_ACTIVE )); then
      (( _ASTER_MENU_INDEX > 1 )) && (( _ASTER_MENU_INDEX-- ))
      _aster_menu_render
    elif (( _ASTER_FUZZY_ACTIVE )); then
      zle beep
    else
      zle _aster-native-up
      _aster_menu_refresh
    fi
  }

  _aster_escape() {
    if (( _ASTER_FUZZY_ACTIVE )); then
      local base="$_ASTER_FUZZY_BASE"
      _aster_menu_clear
      BUFFER="$base"
      CURSOR=${#BUFFER}
      _ASTER_MENU_BUFFER="$BUFFER"
      [[ "$BUFFER" == *[![:space:]]* ]] && _aster_menu_schedule
      region_highlight=( "${_ASTER_FOREIGN_HIGHLIGHTS[@]}" )
      zle -R
      return
    fi
    zle _aster-native-escape
  }

  _aster_menu_pre_redraw() {
    if (( _ASTER_CAPTURE_FOREIGN_HIGHLIGHTS )); then
      _ASTER_FOREIGN_HIGHLIGHTS=( "${(@)region_highlight:#*memo=aster*}" )
      _ASTER_CAPTURE_FOREIGN_HIGHLIGHTS=0
    elif (( _ASTER_MENU_ACTIVE || _ASTER_FUZZY_ACTIVE )) &&
         [[ "$BUFFER" == "$_ASTER_MENU_BUFFER" ]]; then
      region_highlight=( "${_ASTER_FOREIGN_HIGHLIGHTS[@]}" )
      _ASTER_RESTORE_HIGHLIGHTS=0
    elif (( _ASTER_RESTORE_HIGHLIGHTS )); then
      region_highlight=( "${_ASTER_FOREIGN_HIGHLIGHTS[@]}" )
      _ASTER_RESTORE_HIGHLIGHTS=0
    elif [[ -n "$BUFFER" ]]; then
      _ASTER_FOREIGN_HIGHLIGHTS=( "${(@)region_highlight:#*memo=aster*}" )
    elif [[ -n "$_ASTER_MENU_REQUEST_BUFFER" ]]; then
      region_highlight=( "${_ASTER_FOREIGN_HIGHLIGHTS[@]}" )
    else
      _ASTER_FOREIGN_HIGHLIGHTS=()
    fi
    if [[ "$BUFFER" != "$_ASTER_MENU_BUFFER" ]]; then
      _aster_menu_clear
      _ASTER_MENU_BUFFER="$BUFFER"
      [[ -n "$BUFFER" ]] && (( CURSOR == ${#BUFFER} )) && _aster_menu_schedule
    elif (( CURSOR != ${#BUFFER} )); then
      if (( _ASTER_FUZZY_ACTIVE )); then
        _aster_menu_clear
        _ASTER_MENU_BUFFER="$BUFFER"
      else
        _aster_menu_cancel_request
      fi
    fi
    (( _ASTER_MENU_ACTIVE || _ASTER_FUZZY_ACTIVE )) && _aster_menu_render
  }

  autoload -Uz add-zsh-hook
  autoload -Uz add-zle-hook-widget
  zmodload zsh/zselect 2>/dev/null && _ASTER_HAS_ZSELECT=1
  if (( $+functions[_zsh_autosuggest_bind_widgets] )); then
    typeset -g ZSH_AUTOSUGGEST_MANUAL_REBIND=1
    precmd_functions=(${precmd_functions:#_zsh_autosuggest_start})
  fi
  add-zsh-hook preexec _aster_preexec
  add-zsh-hook precmd _aster_precmd
  add-zle-hook-widget line-init _aster_menu_line_init
  add-zle-hook-widget line-finish _aster_menu_line_finish
  add-zle-hook-widget line-pre-redraw _aster_menu_pre_redraw
  preexec_functions=(_aster_preexec ${preexec_functions:#_aster_preexec})
  precmd_functions=(_aster_precmd ${precmd_functions:#_aster_precmd})

  if [[ -z "${widgets[_aster-native-self-insert]:-}" ]]; then
    typeset -g _ASTER_PREVIOUS_TRIGGER="${$(bindkey '__ASTER_COMPLETION_KEY__')##* }"
    [[ -z "$_ASTER_PREVIOUS_TRIGGER" || "$_ASTER_PREVIOUS_TRIGGER" == "undefined-key" ]] && \
      _ASTER_PREVIOUS_TRIGGER=set-mark-command
    typeset -g _ASTER_PREVIOUS_DOWN="${$(bindkey '^N')##* }"
    typeset -g _ASTER_PREVIOUS_UP="${$(bindkey '^K')##* }"
    typeset -g _ASTER_PREVIOUS_SHIFT_TAB="${$(bindkey '^[[Z')##* }"
    typeset -g _ASTER_PREVIOUS_ESCAPE="${$(bindkey '^[')##* }"
    [[ -z "$_ASTER_PREVIOUS_DOWN" || "$_ASTER_PREVIOUS_DOWN" == "undefined-key" ]] && \
      _ASTER_PREVIOUS_DOWN=down-line-or-history
    [[ -z "$_ASTER_PREVIOUS_UP" || "$_ASTER_PREVIOUS_UP" == "undefined-key" ]] && \
      _ASTER_PREVIOUS_UP=kill-line
    [[ -z "$_ASTER_PREVIOUS_SHIFT_TAB" || "$_ASTER_PREVIOUS_SHIFT_TAB" == "undefined-key" ]] && \
      _ASTER_PREVIOUS_SHIFT_TAB=reverse-menu-complete
    [[ -z "$_ASTER_PREVIOUS_ESCAPE" ]] && _ASTER_PREVIOUS_ESCAPE=undefined-key
    zle -A "$_ASTER_PREVIOUS_TRIGGER" _aster-native-trigger
    zle -A "$_ASTER_PREVIOUS_DOWN" _aster-native-down
    zle -A "$_ASTER_PREVIOUS_UP" _aster-native-up
    zle -A "$_ASTER_PREVIOUS_SHIFT_TAB" _aster-native-shift-tab
    zle -A "$_ASTER_PREVIOUS_ESCAPE" _aster-native-escape
    zle -A self-insert _aster-native-self-insert
    typeset -g _ASTER_PREVIOUS_SPACE="${$(bindkey ' ')##* }"
    [[ -z "$_ASTER_PREVIOUS_SPACE" || "$_ASTER_PREVIOUS_SPACE" == "undefined-key" ]] && \
      _ASTER_PREVIOUS_SPACE=self-insert
    zle -A "$_ASTER_PREVIOUS_SPACE" _aster-native-space
    zle -A backward-delete-char _aster-native-backward-delete
    zle -A bracketed-paste _aster-native-bracketed-paste
    typeset -g _ASTER_PREVIOUS_TAB="${$(bindkey '^I')##* }"
    [[ -z "$_ASTER_PREVIOUS_TAB" || "$_ASTER_PREVIOUS_TAB" == "undefined-key" ]] && \
      _ASTER_PREVIOUS_TAB=expand-or-complete
    zle -A "$_ASTER_PREVIOUS_TAB" _aster-native-tab
  fi
  if [[ -z "${widgets[_aster-native-space]:-}" ]]; then
    if [[ -z "${_ASTER_PREVIOUS_SPACE:-}" || "$_ASTER_PREVIOUS_SPACE" == aster-space ]]; then
      typeset -g _ASTER_PREVIOUS_SPACE="${$(bindkey ' ')##* }"
      if [[ -z "$_ASTER_PREVIOUS_SPACE" || "$_ASTER_PREVIOUS_SPACE" == "undefined-key" ||
            "$_ASTER_PREVIOUS_SPACE" == aster-space ]]; then
        if [[ -n "${widgets[magic-space]:-}" ]]; then
          _ASTER_PREVIOUS_SPACE=magic-space
        else
          _ASTER_PREVIOUS_SPACE=self-insert
        fi
      fi
    fi
    zle -A "$_ASTER_PREVIOUS_SPACE" _aster-native-space
  fi
  if [[ -z "${widgets[_aster-native-escape]:-}" ]]; then
    if [[ -z "${_ASTER_PREVIOUS_ESCAPE:-}" || "$_ASTER_PREVIOUS_ESCAPE" == aster-escape ]]; then
      typeset -g _ASTER_PREVIOUS_ESCAPE="${$(bindkey '^[')##* }"
      [[ -z "$_ASTER_PREVIOUS_ESCAPE" || "$_ASTER_PREVIOUS_ESCAPE" == aster-escape ]] && \
        _ASTER_PREVIOUS_ESCAPE=undefined-key
    fi
    zle -A "$_ASTER_PREVIOUS_ESCAPE" _aster-native-escape
  fi
  zle -N aster-tab _aster_tab
  bindkey '^I' aster-tab
  zle -N aster-complete _aster_complete
  zle -N aster-menu-down _aster_menu_down
  zle -N aster-menu-up _aster_menu_up
  zle -N aster-shift-tab _aster_shift_tab
  zle -N aster-escape _aster_escape
  zle -N aster-menu-ready _aster_menu_request_ready
  zle -N aster-menu-apply _aster_menu_apply_result
  zle -N aster-menu-tick _aster_menu_tick
  zle -C aster-native-capture .complete-word _aster_native_capture_widget
  zle -N self-insert _aster_self_insert
  zle -N aster-space _aster_space
  zle -N backward-delete-char _aster_backward_delete
  zle -N bracketed-paste _aster_bracketed_paste
  bindkey '__ASTER_COMPLETION_KEY__' aster-complete
  bindkey '^N' aster-menu-down
  bindkey '^K' aster-menu-up
  bindkey '^[[Z' aster-shift-tab
  bindkey '^[' aster-escape
  bindkey ' ' aster-space
  bindkey -N aster-fuzzy
  bindkey -M aster-fuzzy -R ' '-'~' self-insert
  bindkey -M aster-fuzzy ' ' aster-space
  bindkey -M aster-fuzzy '^?' backward-delete-char
  bindkey -M aster-fuzzy '^H' backward-delete-char
  bindkey -M aster-fuzzy '^I' aster-tab
  bindkey -M aster-fuzzy '^N' aster-menu-down
  bindkey -M aster-fuzzy '^K' aster-menu-up
  bindkey -M aster-fuzzy '__ASTER_COMPLETION_KEY__' aster-complete
  bindkey -M aster-fuzzy '^M' aster-complete
  bindkey -M aster-fuzzy '^[' aster-escape

  if [[ -n "${HISTFILE:-}" && -r "$HISTFILE" ]]; then
    command aster import-history --file "${HISTFILE:A}" >/dev/null 2>&1 &!
  fi
fi
"#
    .replace("__ASTER_COMPLETION_KEY__", &completion_key)
    .replace("__ASTER_COMPLETION_KEY_LABEL__", &completion_key_label)
    .replace("__ASTER_UI_MENU_WIDTH__", &menu_width)
    .replace("__ASTER_UI_MAX_VISIBLE__", &max_visible)
    .replace("__ASTER_COMPLETION_MAX_CANDIDATES__", &max_candidates)
    .replace(
        "__ASTER_UI_PROMPT_OFFSET__",
        &settings.ui.prompt_offset.to_string(),
    )
    .replace("__ASTER_UI_BORDER__", &settings.ui.border)
    .replace("__ASTER_UI_ACCENT__", &settings.ui.accent)
    .replace("__ASTER_UI_TEXT__", &settings.ui.text)
    .replace("__ASTER_UI_MUTED__", &settings.ui.muted)
    .replace("__ASTER_UI_GHOST__", &settings.ui.ghost)
    .replace(
        "__ASTER_UI_SELECTED_BACKGROUND__",
        &settings.ui.selected_background,
    )
    .replace("__ASTER_UI_SELECTED_TEXT__", &settings.ui.selected_text)
    .replace(
        "__ASTER_UI_SELECTED_SOURCE__",
        &settings.ui.selected_source,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn zsh_integration_uses_configured_completion_key() {
        let mut settings = Settings::default();
        let integration = zsh_integration(&settings).unwrap();
        assert!(integration.contains("bindkey '^@' aster-complete"));
        assert!(integration.contains("Ctrl-Space full"));
        assert!(integration.contains("bindkey '^[[Z' aster-shift-tab"));
        assert!(integration.contains("--format zsh-v2"));
        assert!(integration.contains("_ASTER_MENU_REFRESH_TICKS=5"));
        assert!(integration.contains("zle -C aster-native-capture"));
        assert!(integration.contains("descriptions+=(\"Zsh completion\")"));
        assert!(integration.contains("${(@)region_highlight:#*memo=aster*}"));
        assert!(integration.contains("_ASTER_FOREIGN_HIGHLIGHTS"));
        assert!(!integration.contains("aster-menu-enter"));
        assert!(!integration.contains("bindkey '^M'"));
        assert!(!integration.contains("__ASTER_COMPLETION_KEY__"));
        assert!(!integration.contains("__ASTER_UI_"));

        settings.completion.key = "ctrl-x".to_owned();
        settings.ui.selected_background = "#3a3228".to_owned();
        let integration = zsh_integration(&settings).unwrap();
        assert!(integration.contains("bindkey '^X' aster-complete"));
        assert!(integration.contains("bg=#3a3228"));
    }
}