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
// src/cli/fzf.rs
use std::io::Write;
use std::sync::Arc;
// Service container dependency injection implemented
use crate::cli::bookmark_commands;
use crate::cli::error::CliResult;
use crate::cli::process::{
clone_bookmark, copy_bookmark_url_to_clipboard, copy_url_to_clipboard, delete_bookmarks,
edit_bookmarks, execute_bookmark_default_action,
};
use crate::domain::bookmark::Bookmark;
use crate::domain::search::SemanticSearchResult;
use crate::domain::system_tag::SystemTag;
use crate::infrastructure::di::ServiceContainer;
use crate::util::helper::{format_file_path, format_mtime};
use crossterm::style::Stylize;
use crossterm::{
execute,
terminal::{Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
};
use skim::tuikit::attr::{Attr, Color};
use skim::{
prelude::*, AnsiString, DisplayContext, ItemPreview, PreviewContext, Skim, SkimItem,
SkimItemReceiver, SkimItemSender,
};
use tracing::{debug, instrument};
#[derive(Clone)]
struct SnippetItem {
bookmark: Bookmark,
display_text: String,
preview: String,
}
impl SkimItem for SnippetItem {
fn text(&self) -> Cow<'_, str> {
Cow::Borrowed(&self.display_text)
}
fn preview(&self, _context: PreviewContext) -> ItemPreview {
ItemPreview::AnsiText(self.preview.clone())
}
fn output(&self) -> Cow<'_, str> {
if let Some(id) = self.bookmark.id {
Cow::Owned(id.to_string())
} else {
Cow::Borrowed("0")
}
}
}
#[derive(Clone)]
struct AlignedBookmark {
bookmark: Bookmark,
max_id_width: usize,
action_description: String,
settings: crate::config::Settings,
}
impl SkimItem for AlignedBookmark {
fn text(&self) -> Cow<'_, str> {
let display_text = create_bookmark_display_text(
&self.bookmark,
self.max_id_width,
&self.action_description,
&self.settings,
);
Cow::Owned(display_text)
}
fn display<'a>(&'a self, context: DisplayContext<'a>) -> AnsiString<'a> {
// Get the text representation
let text = self.text();
// Calculate padding width
let padding = self.max_id_width + 2; // ID width + ": "
let title = &self.bookmark.title;
// Create attribute for title (green)
let attr_title = Attr {
fg: Color::GREEN,
..Attr::default()
};
// Create attribute segments
let mut attr_segments =
vec![(attr_title, (padding as u32, (padding + title.len()) as u32))];
// Get app settings from struct
let fzf_opts = &self.settings.fzf_opts;
// If showing URL, add yellow attribute for it
if !fzf_opts.no_url {
let start_idx_url = text.find('<').unwrap_or(0) as u32;
if start_idx_url > 0 {
let end_idx_url = text.find('>').unwrap_or(text.len()) as u32 + 1; // +1 for >
attr_segments.push((
Attr {
fg: Color::YELLOW,
..Attr::default()
},
(start_idx_url, end_idx_url),
));
}
}
// If showing tags, add magenta attribute for tags
if fzf_opts.show_tags && !self.bookmark.tags.is_empty() {
let start_idx_tags = text.find('[').unwrap_or(0) as u32;
if start_idx_tags > 0 && start_idx_tags < text.len() as u32 {
let end_idx_tags = text.find(']').unwrap_or(text.len()) as u32 + 1; // +1 for ]
attr_segments.push((
Attr {
fg: Color::MAGENTA,
..Attr::default()
},
(start_idx_tags, end_idx_tags),
));
}
}
// Add cyan attribute for action description in parentheses
if fzf_opts.show_action {
if let (Some(start), Some(end)) = (text.rfind('('), text.rfind(')')) {
attr_segments.push((
Attr {
fg: Color::CYAN,
..Attr::default()
},
(start as u32, end as u32 + 1),
));
}
}
// Add grey attribute for file info line (if present)
if fzf_opts.show_file_info {
if let Some(file_info_start) = text.find("📁") {
// Find the end of the file info line (next newline or end of string)
let file_info_end = text[file_info_start..]
.find('\n')
.map(|pos| file_info_start + pos)
.unwrap_or(text.len());
attr_segments.push((
Attr {
fg: Color::LIGHT_BLACK, // Grey color
..Attr::default()
},
(file_info_start as u32, file_info_end as u32),
));
}
}
AnsiString::new_str(context.text, attr_segments)
}
fn preview(&self, _context: PreviewContext) -> ItemPreview {
let preview_text = create_bookmark_preview_text(&self.bookmark, &self.action_description);
ItemPreview::AnsiText(preview_text)
}
fn output(&self) -> Cow<'_, str> {
if let Some(id) = self.bookmark.id {
Cow::Owned(id.to_string())
} else {
Cow::Borrowed("0")
}
}
}
/// Create display text for a bookmark with proper formatting
fn create_bookmark_display_text(
bookmark: &Bookmark,
max_id_width: usize,
action_description: &str,
settings: &crate::config::Settings,
) -> String {
let id = bookmark.id.unwrap_or(0);
let title = &bookmark.title;
let url = &bookmark.url;
let binding = bookmark.formatted_tags();
let tags_str = binding.trim_matches(',');
let fzf_opts = &settings.fzf_opts;
// Format based on config options
let tags_display = if fzf_opts.show_tags {
format!(" [{}]", tags_str)
} else {
String::new()
};
let action_display = if fzf_opts.show_action {
format!(" ({})", action_description)
} else {
String::new()
};
let mut text = if fzf_opts.no_url {
format!(
"{:>width$}: {}{}{}",
id,
title,
action_display,
tags_display,
width = max_id_width
)
} else {
format!(
"{:>width$}: {} <{}>{}{}",
id,
title,
url,
action_display,
tags_display,
width = max_id_width
)
};
// Add file info if present and enabled
if fzf_opts.show_file_info {
if let (Some(file_path), Some(file_mtime)) = (&bookmark.file_path, bookmark.file_mtime) {
let padding = " ".repeat(max_id_width + 2);
let formatted_path = format_file_path(file_path, 120);
let formatted_time = format_mtime(file_mtime);
text.push_str(&format!(
"\n{}📁 {} ({})",
padding, formatted_path, formatted_time
));
}
}
text
}
/// Create preview text for a bookmark
fn create_bookmark_preview_text(bookmark: &Bookmark, action_description: &str) -> String {
let mut preview_text = format!(
"ID: {}\nTitle: {}\nURL/Content: {}\nDescription: {}\nTags: {}\nAccess Count: {}\nDefault Action: {}",
bookmark.id.unwrap_or(0),
bookmark.title,
bookmark.url,
bookmark.description,
bookmark.formatted_tags().trim_matches(','),
bookmark.access_count,
action_description
);
// Add file info if present
if let (Some(file_path), Some(file_mtime)) = (&bookmark.file_path, bookmark.file_mtime) {
let formatted_path = format_file_path(file_path, 120);
let formatted_time = format_mtime(file_mtime);
preview_text.push_str(&format!(
"\n\nSource: {} ({})",
formatted_path, formatted_time
));
}
format!("\x1b[1mBookmark Details:\x1b[0m\n{}", preview_text)
}
/// Format bookmarks for enhanced display and preview
fn create_enhanced_skim_items(
bookmarks: &[Bookmark],
max_id_width: usize,
services: &ServiceContainer,
_show_file_info: bool,
show_action: bool,
) -> Vec<Arc<dyn SkimItem>> {
// Get action service to determine action descriptions
let action_service = &services.action_service;
// Get interpolation service to render URLs
let interpolation_service = &services.interpolation_service;
bookmarks
.iter()
.map(|bookmark| {
let id = bookmark.id.unwrap_or(0);
let base_description = action_service.get_default_action_description(bookmark);
let action_description =
bookmark_commands::format_action_description(base_description, bookmark.opener.as_ref());
// Format display text with action type and proper alignment
let display_text = format!("{:>width$}: {}", id, bookmark.title, width = max_id_width);
// Apply interpolation if the URL contains template variables
let rendered_url = if bookmark.url.contains("{{") || bookmark.url.contains("{%") {
match interpolation_service.render_bookmark_url(bookmark) {
Ok(url) => url,
Err(_) => bookmark.url.clone(), // Fallback if rendering fails
}
} else {
bookmark.url.clone()
};
// Format tags for display
let tags_str = bookmark
.formatted_tags()
.replace(',', " ")
.trim()
.to_string();
let has_tags = !tags_str.is_empty();
// Format preview with proper spacing (simplified)
let preview = if show_action {
// Include the default action in preview and tags at the bottom
let mut preview_text = format!(
"{}: {}\n\n{}:\n{}\n\n{}:\n{}\n\n{}: {}",
"Title".green().bold(),
bookmark.title,
"Description".yellow().bold(),
if bookmark.description.is_empty() {
"No description"
} else {
&bookmark.description
},
"URL/Content".cyan().bold(),
rendered_url, // Use the rendered URL instead of raw URL
"Default Action".magenta().bold(),
action_description
);
// Add tags section if there are any tags
if has_tags {
preview_text.push_str(&format!("\n\n{}: {}", "Tags".blue().bold(), tags_str));
}
// Add file info if present
if let (Some(file_path), Some(file_mtime)) =
(&bookmark.file_path, &bookmark.file_mtime)
{
let formatted_path = format_file_path(file_path, 120);
let formatted_time = format_mtime(*file_mtime);
preview_text.push_str(&format!(
"\n\n{}: {} ({})",
"Source File".dark_grey().bold(),
formatted_path,
formatted_time
));
}
preview_text
} else {
// Omit the default action in preview but still include tags at the bottom
let mut preview_text = format!(
"{}: {}\n\n{}:\n{}\n\n{}:\n{}",
"Title".green().bold(),
bookmark.title,
"Description".yellow().bold(),
if bookmark.description.is_empty() {
"No description"
} else {
&bookmark.description
},
"URL/Content".cyan().bold(),
rendered_url // Use the rendered URL instead of raw URL
);
// Add tags section if there are any tags
if has_tags {
preview_text.push_str(&format!("\n\n{}: {}", "Tags".blue().bold(), tags_str));
}
// Add file info if present
if let (Some(file_path), Some(file_mtime)) =
(&bookmark.file_path, &bookmark.file_mtime)
{
let formatted_path = format_file_path(file_path, 120);
let formatted_time = format_mtime(*file_mtime);
preview_text.push_str(&format!(
"\n\n{}: {} ({})",
"Source File".dark_grey().bold(),
formatted_path,
formatted_time
));
}
preview_text
};
Arc::new(SnippetItem {
bookmark: bookmark.clone(),
display_text,
preview,
}) as Arc<dyn SkimItem>
})
.collect()
}
// Helper function to get selected bookmarks from output
fn get_selected_bookmarks_from_aligned(
output: &SkimOutput,
bookmarks: &[Bookmark],
) -> Vec<Bookmark> {
let selected_ids: Vec<i32> = output
.selected_items
.iter()
.filter_map(|item| {
// Get the output which contains the bookmark ID as a string
let id_str = item.output();
id_str.parse::<i32>().ok()
})
.collect();
// Find the corresponding bookmarks
let selected_bookmarks: Vec<Bookmark> = bookmarks
.iter()
.filter(|b| b.id.is_some() && selected_ids.contains(&b.id.unwrap()))
.cloned()
.collect();
if !selected_bookmarks.is_empty() {
eprintln!("Selected bookmarks:");
for bookmark in &selected_bookmarks {
eprintln!(" - {}: {}", bookmark.id.unwrap_or(0), bookmark.title);
}
}
debug!("Selected {} bookmarks", selected_bookmarks.len());
selected_bookmarks
}
impl SkimItem for SemanticSearchResult {
fn text(&self) -> Cow<'_, str> {
let text = self.display();
Cow::Owned(text)
}
}
/// Processes bookmarks using the fzf-like selector interface
#[instrument(skip(bookmarks), level = "debug")]
pub fn fzf_process(
bookmarks: &[Bookmark],
style: &str,
services: &ServiceContainer,
settings: &crate::config::Settings,
stdout: bool,
) -> CliResult<()> {
if bookmarks.is_empty() {
eprintln!("No bookmarks to display");
return Ok(());
}
// Sort bookmarks by title (case-insensitive)
let mut sorted_bookmarks = bookmarks.to_vec();
sorted_bookmarks.sort_by(|a, b| a.title.to_lowercase().cmp(&b.title.to_lowercase()));
// Find the maximum ID width for proper alignment
let max_id_width = sorted_bookmarks
.iter()
.map(|b| b.id.unwrap_or(0).to_string().len())
.max()
.unwrap_or(0);
// Use provided settings
let fzf_opts = &settings.fzf_opts;
// Build skim options
let mut options_builder = SkimOptionsBuilder::default();
// Set common options
options_builder.height(fzf_opts.height.clone());
options_builder.reverse(fzf_opts.reverse);
options_builder.multi(false);
options_builder.ansi(true);
options_builder.filter(Some("".to_string()));
// Add preview window only for enhanced style
if style == "enhanced" {
options_builder.preview(Some("".to_string()));
options_builder.preview_window("right:70%:wrap".to_string());
}
// Add key bindings
options_builder.bind(vec![
"ctrl-a:accept".to_string(),
"ctrl-o:accept".to_string(),
"ctrl-y:accept".to_string(),
"ctrl-e:accept".to_string(),
"ctrl-d:accept".to_string(),
"ctrl-p:accept".to_string(),
"enter:accept".to_string(),
"esc:abort".to_string(),
]);
let options = options_builder.build().map_err(|e| {
crate::cli::error::CliError::CommandFailed(format!("Failed to build skim options: {}", e))
})?;
// Set up channel for bookmark items
let (tx_item, rx_item): (SkimItemSender, SkimItemReceiver) = unbounded();
// Send bookmarks to skim based on style
if style == "enhanced" {
let skim_items = create_enhanced_skim_items(
&sorted_bookmarks,
max_id_width,
services,
fzf_opts.show_file_info,
fzf_opts.show_action,
);
for item in skim_items {
tx_item.send(item).map_err(|_| {
crate::cli::error::CliError::CommandFailed(
"Failed to send bookmark to skim".to_string(),
)
})?;
}
} else {
// Original style - use AlignedBookmark instead
for bookmark in &sorted_bookmarks {
debug!("Sending bookmark to skim: {}", bookmark.title);
// Get action description, incorporating custom opener if present
let base_description = services
.action_service
.get_default_action_description(bookmark);
let action_description =
bookmark_commands::format_action_description(base_description, bookmark.opener.as_ref());
let item = Arc::new(AlignedBookmark {
bookmark: bookmark.clone(),
max_id_width,
action_description,
settings: settings.clone(),
});
tx_item.send(item).map_err(|_| {
crate::cli::error::CliError::CommandFailed(
"Failed to send bookmark to skim".to_string(),
)
})?;
}
}
drop(tx_item); // Close channel to signal end of items
// Determine if we need to manually handle alternate screen
// Skim uses alternate screen automatically for height=100%, but not for smaller heights
// For height < 100%, we wrap with alternate screen to ensure proper terminal restoration
//
// IMPORTANT: Skip alternate screen handling in --stdout mode because these escape sequences
// (\E[?1049h, \E[?1049l) would pollute the output that shell widgets capture.
// In stdout mode, skim still works fine - we just accept potential terminal artifacts.
let use_alternate_screen = !stdout && fzf_opts.height != "100%" && fzf_opts.height != "100";
if use_alternate_screen {
execute!(std::io::stdout(), EnterAlternateScreen)?;
}
// Execute the skim selector
let skim_output = Skim::run_with(&options, Some(rx_item));
// Restore terminal if we entered alternate screen
if use_alternate_screen {
execute!(std::io::stdout(), LeaveAlternateScreen)?;
}
if let Some(output) = skim_output {
let key = output.final_key;
debug!("Final key: {:?}", key);
// Check if the user pressed ESC - if so, don't process selected items
if key == Key::ESC {
debug!("Selection aborted with ESC key");
reset_terminal_state(stdout);
return Ok(());
}
// Get selected bookmarks
let selected_bookmarks = get_selected_bookmarks_from_aligned(&output, &sorted_bookmarks);
if selected_bookmarks.is_empty() {
debug!("No bookmarks selected");
return Ok(());
}
// Get IDs of selected bookmarks
let ids: Vec<i32> = selected_bookmarks.iter().filter_map(|bm| bm.id).collect();
debug!("Selected bookmark IDs: {:?}", ids);
// Ensure clean output positioning before processing action
// Skim handles terminal restoration - we just need a newline for output
println!();
// Process the selected action based on the key
match key {
// Execute default action for Enter - Use the action service
Key::Enter => {
if stdout {
// Output interpolated content to stdout instead of executing
for bookmark in &selected_bookmarks {
let content = services
.interpolation_service
.render_bookmark_url(bookmark)
.map_err(|e| {
crate::cli::error::CliError::CommandFailed(format!(
"Failed to render content: {}",
e
))
})?;
println!("{}", content);
}
} else {
// Execute default action for each selected bookmark
for bookmark in &selected_bookmarks {
// Use the action service to execute the default action
execute_bookmark_default_action(bookmark, services.action_service.clone())?;
}
}
}
Key::Ctrl('y') | Key::Ctrl('o') => {
// clear_fzf_artifacts();
if let Some(bookmark) = selected_bookmarks.first() {
// Check if this is a shell script
let is_shell_script = bookmark
.tags
.iter()
.any(|tag| tag.is_system_tag_of(SystemTag::Shell));
if is_shell_script {
// For shell scripts, copy the bkmr open command instead of URL content
let command =
format!("bkmr open --no-edit {} --", bookmark.id.unwrap_or(0));
copy_url_to_clipboard(&command, services.clipboard_service.clone())?;
} else {
// For all other types, copy URL to clipboard with interpolation
copy_bookmark_url_to_clipboard(
bookmark,
services.interpolation_service.clone(),
services.clipboard_service.clone(),
)?;
}
}
}
Key::Ctrl('e') => {
// Edit selected bookmarks - editor handles its own terminal
edit_bookmarks(
ids,
false,
services.bookmark_service.clone(),
services.template_service.clone(),
settings,
)?;
}
Key::Ctrl('d') => {
// clear_fzf_artifacts();
// Delete selected bookmarks
delete_bookmarks(ids, services.bookmark_service.clone(), settings)?;
}
Key::Ctrl('a') => {
// clear_fzf_artifacts();
// Clone selected bookmark
if let Some(bookmark) = selected_bookmarks.first() {
if let Some(id) = bookmark.id {
clone_bookmark(
id,
services.bookmark_service.clone(),
services.template_service.clone(),
)?;
}
}
}
Key::Ctrl('p') => {
// Show detailed information for the selected bookmark
if let Some(bookmark) = selected_bookmarks.first() {
// Clear from cursor for clean detail view
let _ = execute!(std::io::stdout(), Clear(ClearType::FromCursorDown));
// Use the shared function to show bookmark details
let details = bookmark_commands::show_bookmark_details(bookmark, services);
print!("{}", details);
}
}
_ => {
debug!("Unhandled key: {:?}", key);
}
}
// Reset terminal state after action (cursor visible, colors reset)
// Skip for --stdout mode to keep output clean for shell widgets
reset_terminal_state(stdout);
}
Ok(())
}
/// Minimal terminal state reset after skim exit.
///
/// This reset is useful for interactive mode as a safety measure after:
/// - `execute_bookmark_default_action()` which runs external commands/browsers
/// - `edit_bookmarks()` which opens editors that might alter terminal state
/// - `Ctrl+P` detail printing which uses colors
///
/// However, for `--stdout` mode (shell widget integration), this function
/// must be skipped because it writes ANSI escape sequences (\E[0m, \E[?25h)
/// to stdout, polluting the output that the shell widget captures.
/// In stdout mode, we're just printing content - no terminal state changes occur.
fn reset_terminal_state(skip: bool) {
if skip {
return;
}
let mut stdout = std::io::stdout();
let _ = execute!(
stdout,
crossterm::style::ResetColor,
crossterm::cursor::Show
);
let _ = stdout.flush();
}