From 219544469d896c18b215ac7006abb8b713674b4e Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Mon, 16 Nov 2026 11:25:49 +0530 Subject: [PATCH 1/7] Add privacy mode for .env files in text viewer Mask the values of KEY=value lines as ******** when previewing .env, .env.*, .envrc and *.env files, so secrets are not exposed during screen shares. The file is not modified, and the mask has a fixed width so value length is not revealed. Handles export prefixes, quoted and multi-line values, and inline comments. An eye button in the top right corner and Alt+M show or hide the values. Masking can be turned off with the MaskEnvValues setting. --- .../Generators/EnvMaskGenerator.cs | 303 ++++++++++++++++++ .../QuickLook.Plugin.TextViewer/Plugin.cs | 4 +- .../TextViewerPanel.DevTools.cs | 153 +++++++++ .../TextViewerPanel.cs | 11 + .../Translations.config | 2 + 5 files changed, 472 insertions(+), 1 deletion(-) create mode 100644 QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs create mode 100644 QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.DevTools.cs diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs new file mode 100644 index 000000000..916467413 --- /dev/null +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs @@ -0,0 +1,303 @@ +// Copyright © 2017-2026 QL-Win Contributors +// +// This file is part of QuickLook program. +// +// 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 . + +using ICSharpCode.AvalonEdit.Rendering; +using QuickLook.Common.Helpers; +using System; +using System.Collections.Generic; +using System.IO; + +namespace QuickLook.Plugin.TextViewer.Generators; + +/// +/// "Privacy mode" for .env files: replaces the value of every KEY=value line with a fixed-width +/// mask on screen, so secrets are not exposed during screen shares or presentations. +/// The document itself is not modified, and the mask has a constant width so it does not reveal +/// how long a value is. +/// +internal sealed class EnvMaskGenerator : VisualLineElementGenerator +{ + private const string Mask = "********"; + + private static readonly char[] LineBreaks = ['\r', '\n']; + + // Sorted, non-overlapping [start, end) document ranges. Every range lies on a single line, + // so a quoted value that spans several lines becomes one range per line. + private readonly int[] _starts; + private readonly int[] _ends; + + /// When false the real values are shown. + public bool IsMasked { get; set; } = true; + + /// The exact text that is shown in the editor (offsets must match the document). + public EnvMaskGenerator(string text) + { + var starts = new List(); + var ends = new List(); + FindValueRanges(text ?? string.Empty, starts, ends); + _starts = starts.ToArray(); + _ends = ends.ToArray(); + } + + /// + /// .env, .env.local, .env.production, .envrc, something.env ... + /// + public static bool IsEnvFile(string path) + { + if (string.IsNullOrEmpty(path)) + return false; + + string name = Path.GetFileName(path); + + return name.Equals(".env", StringComparison.OrdinalIgnoreCase) + || name.Equals(".envrc", StringComparison.OrdinalIgnoreCase) + || name.StartsWith(".env.", StringComparison.OrdinalIgnoreCase) + || name.EndsWith(".env", StringComparison.OrdinalIgnoreCase); + } + + /// + /// Masking applies to .env files unless the user switched it off with the + /// "MaskEnvValues" setting of the text viewer. + /// + public static bool IsEnabledFor(string path) + { + return IsEnvFile(path) && SettingHelper.Get("MaskEnvValues", true, "QuickLook.Plugin.TextViewer"); + } + + public override int GetFirstInterestedOffset(int startOffset) + { + if (!IsMasked) + return -1; + + int index = FirstRangeEndingAfter(startOffset); + if (index < 0) + return -1; + + int offset = Math.Max(_starts[index], startOffset); + + // Only react to ranges on the line that is being built. + return offset < CurrentContext.VisualLine.LastDocumentLine.EndOffset ? offset : -1; + } + + public override VisualLineElement ConstructElement(int offset) + { + int index = FirstRangeEndingAfter(offset); + if (index < 0 || _starts[index] > offset) + return null; + + return new FormattedTextElement(Mask, _ends[index] - offset); + } + + /// Index of the first range whose end lies after , or -1. + private int FirstRangeEndingAfter(int offset) + { + int low = 0; + int high = _ends.Length; + + while (low < high) + { + int mid = (low + high) >> 1; + if (_ends[mid] > offset) + high = mid; + else + low = mid + 1; + } + + return low < _ends.Length ? low : -1; + } + + private static void FindValueRanges(string text, List starts, List ends) + { + int position = 0; + + while (position < text.Length) + { + int lineEnd = IndexOfLineBreak(text, position); + int nextLine = SkipLineBreak(text, lineEnd); + + int p = SkipBlanks(text, position, lineEnd); + + // Blank lines and comments have nothing to mask. + if (p < lineEnd && text[p] != '#') + { + p = SkipExport(text, p, lineEnd); + + int keyStart = p; + while (p < lineEnd && IsKeyChar(text[p])) + p++; + + if (p > keyStart) + { + p = SkipBlanks(text, p, lineEnd); + + if (p < lineEnd && text[p] == '=') + { + int valueStart = SkipBlanks(text, p + 1, lineEnd); + nextLine = AddValueRanges(text, valueStart, lineEnd, nextLine, starts, ends); + } + } + } + + position = nextLine; + } + } + + /// + /// Records the range(s) of one value and returns the offset where parsing should continue. + /// + private static int AddValueRanges(string text, int valueStart, int lineEnd, int nextLine, + List starts, List ends) + { + // KEY= (empty value): nothing to hide. + if (valueStart >= lineEnd) + return nextLine; + + char first = text[valueStart]; + + if (first == '"' || first == '\'' || first == '`') + { + int close = FindClosingQuote(text, valueStart + 1, first); + + if (close >= 0) + { + // The quoted value may span several lines (private keys, certificates...). + AddRange(text, valueStart, close + 1, starts, ends); + + // Resume after the line that holds the closing quote. + return SkipLineBreak(text, IndexOfLineBreak(text, close)); + } + + // No closing quote anywhere: hide the rest of this line, keep parsing the next one. + AddRange(text, valueStart, TrimEnd(text, valueStart, lineEnd), starts, ends); + return nextLine; + } + + // Unquoted value: ends at the line end or at an inline comment (whitespace followed by '#'). + int end = lineEnd; + for (int i = valueStart + 1; i < lineEnd; i++) + { + if (text[i] == '#' && (text[i - 1] == ' ' || text[i - 1] == '\t')) + { + end = i; + break; + } + } + + end = TrimEnd(text, valueStart, end); + if (end > valueStart) + AddRange(text, valueStart, end, starts, ends); + + return nextLine; + } + + /// Adds [start, end) split at line breaks, so that no range crosses a line. + private static void AddRange(string text, int start, int end, List starts, List ends) + { + int segmentStart = start; + + for (int i = start; i < end; i++) + { + if (text[i] != '\r' && text[i] != '\n') + continue; + + if (i > segmentStart) + { + starts.Add(segmentStart); + ends.Add(i); + } + + segmentStart = i + 1; + } + + if (end > segmentStart) + { + starts.Add(segmentStart); + ends.Add(end); + } + } + + private static int FindClosingQuote(string text, int from, char quote) + { + for (int i = from; i < text.Length; i++) + { + // Double quoted values may contain \" escapes. + if (quote == '"' && text[i] == '\\') + { + i++; + continue; + } + + if (text[i] == quote) + return i; + } + + return -1; + } + + private static int IndexOfLineBreak(string text, int from) + { + int index = text.IndexOfAny(LineBreaks, from); + return index < 0 ? text.Length : index; + } + + private static int SkipLineBreak(string text, int index) + { + if (index >= text.Length) + return text.Length; + + if (text[index] == '\r' && index + 1 < text.Length && text[index + 1] == '\n') + return index + 2; + + return index + 1; + } + + private static int SkipBlanks(string text, int from, int limit) + { + while (from < limit && (text[from] == ' ' || text[from] == '\t')) + from++; + + return from; + } + + /// Skips a leading "export " so that "export KEY=value" (.envrc, shell style) works too. + private static int SkipExport(string text, int p, int lineEnd) + { + const string keyword = "export"; + + if (p + keyword.Length < lineEnd + && string.CompareOrdinal(text, p, keyword, 0, keyword.Length) == 0 + && (text[p + keyword.Length] == ' ' || text[p + keyword.Length] == '\t')) + { + return SkipBlanks(text, p + keyword.Length, lineEnd); + } + + return p; + } + + private static int TrimEnd(string text, int start, int end) + { + while (end > start && (text[end - 1] == ' ' || text[end - 1] == '\t')) + end--; + + return end; + } + + private static bool IsKeyChar(char c) + { + return char.IsLetterOrDigit(c) || c == '_' || c == '.' || c == '-'; + } +} diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Plugin.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Plugin.cs index 92bc33737..12c115c5d 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Plugin.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Plugin.cs @@ -93,7 +93,9 @@ public void View(string path, ContextObject context) { _tvp = new TextViewerPanel(); _tvp.LoadFileAsync(path, context); - context.ViewerContent = _tvp; + + // For .env files this adds an eye button (show / hide values) in the top right corner. + context.ViewerContent = _tvp.WrapWithEnvToggle(); } context.Title = Path.GetFileName(path); } diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.DevTools.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.DevTools.cs new file mode 100644 index 000000000..4d70ca54b --- /dev/null +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.DevTools.cs @@ -0,0 +1,153 @@ +// Copyright © 2017-2026 QL-Win Contributors +// +// This file is part of QuickLook program. +// +// 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 . + +using QuickLook.Common.Controls; +using QuickLook.Common.Helpers; +using QuickLook.Plugin.TextViewer.Generators; +using System; +using System.IO; +using System.Reflection; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; + +namespace QuickLook.Plugin.TextViewer; + +// Privacy mode for .env files: values are masked until the user reveals them, +// with an eye button in the top right corner (and Alt+M) to show / hide them. +public partial class TextViewerPanel +{ + private bool _envMaskAvailable; + private bool _envRevealed; + private EnvMaskGenerator _envMask; + + /// Raised after the user hides or reveals the values of an .env file. + public event EventHandler EnvMaskVisibilityChanged; + + /// True when the file being previewed is an .env file and masking is enabled. + public bool IsEnvMaskAvailable => _envMaskAvailable; + + /// True while the real values of an .env file are shown. Always false after opening a file. + public bool AreEnvValuesRevealed => _envRevealed; + + /// + /// Decides synchronously, before the file is read, whether masking applies, + /// so that the toolbar button can be created right after the preview starts. + /// + private void PrepareDeveloperFeatures(string path) + { + _envMaskAvailable = EnvMaskGenerator.IsEnabledFor(path); + } + + /// + /// Installs the mask generator. Called before the document is assigned to the editor, + /// so a secret is never drawn unmasked, not even for a single frame. + /// + private void InstallDeveloperFeatures(string path, string text) + { + if (_envMaskAvailable) + { + _envMask = new EnvMaskGenerator(text) { IsMasked = !_envRevealed }; + TextArea.TextView.ElementGenerators.Add(_envMask); + } + } + + /// Hides or reveals the values of an .env file. Does nothing for other files. + public void ToggleEnvMask() + { + if (!_envMaskAvailable) + return; + + _envRevealed = !_envRevealed; + + // The generator may not exist yet while the file is still loading; + // it picks up _envRevealed when it is installed. + if (_envMask is not null) + { + _envMask.IsMasked = !_envRevealed; + TextArea.TextView.Redraw(); + } + + EnvMaskVisibilityChanged?.Invoke(this, EventArgs.Empty); + } + + /// + /// Returns the element to show in the viewer window. For .env files this is the editor with an + /// eye button in its top right corner (like the buttons of the image viewer); for every other + /// file it is just the editor itself. Call it after . + /// + public FrameworkElement WrapWithEnvToggle() + { + if (!_envMaskAvailable) + return this; + + var button = new Button + { + Width = 24, + Height = 24, + FontFamily = new FontFamily("Segoe Fluent Icons, Segoe MDL2 Assets"), + Focusable = false, + }; + + // Same look as the caption buttons of the viewer window. The style is looked up when the + // button is added to the window, so it follows the current light / dark theme. + button.SetResourceReference(FrameworkElement.StyleProperty, "CaptionButtonStyle"); + + // Local values win over the style, so size and focus behavior stay as set above. + button.Width = 24; + button.Height = 24; + + button.Click += (_, _) => ToggleEnvMask(); + EnvMaskVisibilityChanged += (_, _) => UpdateEnvToggleButton(button); + UpdateEnvToggleButton(button); + + var overlay = new StackPanel + { + Orientation = Orientation.Horizontal, + HorizontalAlignment = HorizontalAlignment.Right, + VerticalAlignment = VerticalAlignment.Top, + + // Leaves room for the vertical scroll bar of the editor. + Margin = new Thickness(0, 8, 24, 0), + }; + overlay.Children.Add(button); + + var host = new Grid(); + host.Children.Add(this); + host.Children.Add(overlay); + return host; + } + + /// + /// Shows an eye while values are hidden (click to reveal) and a crossed-out eye while they are + /// visible (click to hide), with a matching tooltip. + /// + private void UpdateEnvToggleButton(Button button) + { + bool revealed = _envRevealed; + + button.Content = revealed ? FontSymbols.Hide : FontSymbols.RedEye; + + string translationFile = Path.Combine( + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Translations.config"); + + button.ToolTip = TranslationHelper.Get( + revealed ? "MW_HideSecretValues" : "MW_ShowSecretValues", + translationFile, + failsafe: revealed ? "Hide secret values" : "Show secret values"); + } +} diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs index 3a1ab57ce..1adba704e 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs @@ -196,6 +196,11 @@ private void Viewer_KeyDown(object sender, KeyEventArgs e) TextArea.LeftMargins.OfType().FirstOrDefault()?.Stroke = Brushes.Transparent; SettingHelper.Set("ShowLineNumbers", ShowLineNumbers, "QuickLook.Plugin.TextViewer"); } + else if (Keyboard.IsKeyDown(Key.M)) + { + // Hide / reveal the values of an .env file (no effect on other files). + ToggleEnvMask(); + } } } @@ -330,6 +335,8 @@ protected override void ColorizeLine(DocumentLine line) public void LoadFileAsync(string path, ContextObject context) { + PrepareDeveloperFeatures(path); + _ = Task.Run(() => { const int maxLength = 5 * 1024 * 1024; @@ -388,6 +395,10 @@ public void LoadFileAsync(string path, ContextObject context) SyntaxHighlighting = bufferCopy.Length > maxHighlightingLength ? null : highlighting.SyntaxHighlighting; + + // Color swatches and .env masking; installed before the document is shown. + InstallDeveloperFeatures(path, text); + Document = doc; if (SyntaxHighlighting is ICustomHighlightingDefinition custom) diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Translations.config b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Translations.config index 71bbc18ce..70acf9c42 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Translations.config +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Translations.config @@ -32,6 +32,8 @@ Reopen as HTML preview Reopen as image preview Reopen as CSV preview + Show secret values + Hide secret values Consolas From 953171f8ff309d7a88638018fd1441047b701470 Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Mon, 16 Nov 2026 11:29:54 +0530 Subject: [PATCH 2/7] Document MaskEnvValues option in OPTIONS.md Add the MaskEnvValues setting of the text viewer, which controls the privacy mode for .env files. --- OPTIONS.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/OPTIONS.md b/OPTIONS.md index e7e68b138..38b48fdbe 100644 --- a/OPTIONS.md +++ b/OPTIONS.md @@ -279,6 +279,13 @@ These keys are also stored in `QuickLook.config`. - Example: - `False` to disable word wrap. +### `` +- Default: `True` +- Type: `Boolean` +- Description: Mask the values of `.env` files (`.env`, `.env.*`, `.envrc` and `*.env`) as `********` in text previews, so secrets are not exposed during screen shares. Click the eye button or press `Alt+M` while previewing to show or hide the values; masking is always on when a file is opened. +- Example: + - `False` to always show `.env` values. + ### `` - Default: `True` - Type: `Boolean` From 384b7e9c286123ae8c41a11be575d3d08a7f6591 Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Mon, 16 Nov 2026 11:33:48 +0530 Subject: [PATCH 3/7] Fix outdated comment in TextViewerPanel --- .../QuickLook.Plugin.TextViewer/TextViewerPanel.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs index 1adba704e..aed1e9417 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs @@ -396,7 +396,7 @@ public void LoadFileAsync(string path, ContextObject context) ? null : highlighting.SyntaxHighlighting; - // Color swatches and .env masking; installed before the document is shown. + // .env masking; installed before the document is shown. InstallDeveloperFeatures(path, text); Document = doc; @@ -447,4 +447,4 @@ public void LoadFileAsync(string path, ContextObject context) }, DispatcherPriority.Render); }); } -} +} \ No newline at end of file From 3bed94db29c6a227225240dff9153c073c0a845e Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Mon, 16 Nov 2026 16:03:34 +0530 Subject: [PATCH 4/7] fix(TextViewer): harden .env masking against edge cases - Skip a leading BOM when parsing the first key - Treat quoted and unquoted segments as one shell-style value - Honor escaped whitespace before '#' comments - Build mask ranges from the text before line truncation so multi-line quoted values stay masked --- .../Generators/EnvMaskGenerator.cs | 256 ++++++++++++------ .../TextViewerPanel.DevTools.cs | 6 +- .../TextViewerPanel.cs | 9 +- 3 files changed, 181 insertions(+), 90 deletions(-) diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs index 916467413..d26830d01 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs @@ -15,6 +15,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Rendering; using QuickLook.Common.Helpers; using System; @@ -29,28 +30,40 @@ namespace QuickLook.Plugin.TextViewer.Generators; /// The document itself is not modified, and the mask has a constant width so it does not reveal /// how long a value is. /// +/// +/// The generator must be built from the decoded text BEFORE over-long lines are truncated. +/// Truncation can cut off the closing quote of a value, and a value whose end is not visible +/// cannot be masked reliably. Masked ranges are stored as (line, column) instead of offsets: +/// truncation only shortens the end of lines and keeps every line break, so line and column +/// stay valid, and a range is clipped to the real line length when it is drawn. +/// internal sealed class EnvMaskGenerator : VisualLineElementGenerator { private const string Mask = "********"; private static readonly char[] LineBreaks = ['\r', '\n']; - // Sorted, non-overlapping [start, end) document ranges. Every range lies on a single line, - // so a quoted value that spans several lines becomes one range per line. - private readonly int[] _starts; - private readonly int[] _ends; + // One entry per masked line, sorted by line number. A line has at most one masked range, and a + // quoted value that spans several lines becomes one range per line. + // Line numbers are 1-based like DocumentLine.LineNumber, columns are 0-based [start, end). + private readonly int[] _lines; + private readonly int[] _startColumns; + private readonly int[] _endColumns; /// When false the real values are shown. public bool IsMasked { get; set; } = true; - /// The exact text that is shown in the editor (offsets must match the document). + /// The decoded file text, before any line truncation. public EnvMaskGenerator(string text) { + var lines = new List(); var starts = new List(); var ends = new List(); - FindValueRanges(text ?? string.Empty, starts, ends); - _starts = starts.ToArray(); - _ends = ends.ToArray(); + FindValueRanges(text ?? string.Empty, lines, starts, ends); + + _lines = lines.ToArray(); + _startColumns = starts.ToArray(); + _endColumns = ends.ToArray(); } /// @@ -80,56 +93,64 @@ public static bool IsEnabledFor(string path) public override int GetFirstInterestedOffset(int startOffset) { - if (!IsMasked) + if (!IsMasked || _lines.Length == 0) return -1; - int index = FirstRangeEndingAfter(startOffset); - if (index < 0) - return -1; + // A visual line normally is one document line, but can be several when lines are folded. + int limit = CurrentContext.VisualLine.LastDocumentLine.EndOffset; - int offset = Math.Max(_starts[index], startOffset); + for (DocumentLine line = CurrentContext.Document.GetLineByOffset(startOffset); + line != null && line.Offset <= limit; + line = line.NextLine) + { + if (TryGetRange(line, out int start, out int end) && end > startOffset) + return Math.Max(start, startOffset); + } - // Only react to ranges on the line that is being built. - return offset < CurrentContext.VisualLine.LastDocumentLine.EndOffset ? offset : -1; + return -1; } public override VisualLineElement ConstructElement(int offset) { - int index = FirstRangeEndingAfter(offset); - if (index < 0 || _starts[index] > offset) + DocumentLine line = CurrentContext.Document.GetLineByOffset(offset); + + if (!TryGetRange(line, out int start, out int end) || offset < start || offset >= end) return null; - return new FormattedTextElement(Mask, _ends[index] - offset); + return new FormattedTextElement(Mask, end - offset); } - /// Index of the first range whose end lies after , or -1. - private int FirstRangeEndingAfter(int offset) + /// + /// Document offsets of the masked range on a line, clipped to the text that is really there + /// (a truncated line is shorter than the line the range was found on). + /// + private bool TryGetRange(DocumentLine line, out int start, out int end) { - int low = 0; - int high = _ends.Length; + start = end = 0; - while (low < high) - { - int mid = (low + high) >> 1; - if (_ends[mid] > offset) - high = mid; - else - low = mid + 1; - } + int index = Array.BinarySearch(_lines, line.LineNumber); + if (index < 0) + return false; - return low < _ends.Length ? low : -1; + start = line.Offset + _startColumns[index]; + end = line.Offset + Math.Min(_endColumns[index], line.Length); + return end > start; } - private static void FindValueRanges(string text, List starts, List ends) + private static void FindValueRanges(string text, List lines, List starts, List ends) { int position = 0; + int lineNumber = 1; while (position < text.Length) { int lineEnd = IndexOfLineBreak(text, position); int nextLine = SkipLineBreak(text, lineEnd); - int p = SkipBlanks(text, position, lineEnd); + // A UTF-8 BOM is decoded to U+FEFF. It stays part of the text (so columns match the + // document) but is not part of the first key. + int p = position == 0 && text[0] == '\uFEFF' ? 1 : position; + p = SkipBlanks(text, p, lineEnd); // Blank lines and comments have nothing to mask. if (p < lineEnd && text[p] != '#') @@ -147,92 +168,144 @@ private static void FindValueRanges(string text, List starts, List end if (p < lineEnd && text[p] == '=') { int valueStart = SkipBlanks(text, p + 1, lineEnd); - nextLine = AddValueRanges(text, valueStart, lineEnd, nextLine, starts, ends); + + // KEY= (empty value): nothing to hide. + if (valueStart < lineEnd) + { + int valueEnd = ScanValue(text, valueStart); + AddRanges(text, valueStart, valueEnd, lineNumber, position, lines, starts, ends); + + // Resume after the line that holds the end of the value. + nextLine = SkipLineBreak(text, IndexOfLineBreak(text, valueEnd)); + } } } } + lineNumber += CountLineBreaks(text, position, nextLine); position = nextLine; } } /// - /// Records the range(s) of one value and returns the offset where parsing should continue. + /// Returns the end (exclusive) of the value that starts at . + /// A value is a sequence of quoted and unquoted segments, like a shell word (see "Quoting" in + /// the POSIX Shell Command Language): "prefix"secret is one value, and a backslash + /// escapes the next character, so an escaped space does not end the value or start a comment. + /// It ends at the end of the line, or at unescaped whitespace followed by '#' (a comment). + /// To be safe, anything that may belong to the value is masked. /// - private static int AddValueRanges(string text, int valueStart, int lineEnd, int nextLine, - List starts, List ends) + private static int ScanValue(string text, int start) { - // KEY= (empty value): nothing to hide. - if (valueStart >= lineEnd) - return nextLine; + int i = start; + int end = start; - char first = text[valueStart]; + // True at the start of the value and right after a closing quote. + bool afterQuote = true; - if (first == '"' || first == '\'' || first == '`') + while (i < text.Length) { - int close = FindClosingQuote(text, valueStart + 1, first); + char c = text[i]; + + if (c == '\r' || c == '\n') + break; - if (close >= 0) + if (c == '"' || c == '\'' || c == '`') { - // The quoted value may span several lines (private keys, certificates...). - AddRange(text, valueStart, close + 1, starts, ends); + // A quote that opens the value or follows another quoted segment may continue over + // several lines (private keys, certificates...). In the middle of an unquoted word + // it has to close on the same line, so a lone apostrophe (O'Brien) is just a character. + int limit = afterQuote ? text.Length : IndexOfLineBreak(text, i); + int close = FindClosingQuote(text, i + 1, c, limit); + + if (close >= 0) + { + i = close + 1; + end = i; + afterQuote = true; + continue; + } - // Resume after the line that holds the closing quote. - return SkipLineBreak(text, IndexOfLineBreak(text, close)); + // Never closed: hide the rest of this line. + if (afterQuote) + return IndexOfLineBreak(text, i); + + i++; + end = i; + continue; } - // No closing quote anywhere: hide the rest of this line, keep parsing the next one. - AddRange(text, valueStart, TrimEnd(text, valueStart, lineEnd), starts, ends); - return nextLine; - } + afterQuote = false; - // Unquoted value: ends at the line end or at an inline comment (whitespace followed by '#'). - int end = lineEnd; - for (int i = valueStart + 1; i < lineEnd; i++) - { - if (text[i] == '#' && (text[i - 1] == ' ' || text[i - 1] == '\t')) + if (c == '\\') { + // The escaped character (even a space) belongs to the value. + i += i + 1 < text.Length && text[i + 1] != '\r' && text[i + 1] != '\n' ? 2 : 1; end = i; - break; } - } + else if (c == ' ' || c == '\t') + { + int next = SkipBlanks(text, i, text.Length); - end = TrimEnd(text, valueStart, end); - if (end > valueStart) - AddRange(text, valueStart, end, starts, ends); + // Unescaped whitespace followed by '#' starts a comment. + if (next < text.Length && text[next] == '#') + break; - return nextLine; + // Whitespace inside the value; it only counts when more of the value follows. + i = next; + } + else + { + i++; + end = i; + } + } + + return end; } - /// Adds [start, end) split at line breaks, so that no range crosses a line. - private static void AddRange(string text, int start, int end, List starts, List ends) + /// + /// Records [start, end) split at line breaks, so that no range crosses a line. + /// and belong to the line that holds . + /// + private static void AddRanges(string text, int start, int end, int lineNumber, int lineStart, + List lines, List starts, List ends) { - int segmentStart = start; + int segment = start; for (int i = start; i < end; i++) { - if (text[i] != '\r' && text[i] != '\n') + char c = text[i]; + if (c != '\r' && c != '\n') continue; - if (i > segmentStart) + if (i > segment) { - starts.Add(segmentStart); - ends.Add(i); + lines.Add(lineNumber); + starts.Add(segment - lineStart); + ends.Add(i - lineStart); } - segmentStart = i + 1; + if (c == '\r' && i + 1 < end && text[i + 1] == '\n') + i++; + + lineNumber++; + lineStart = i + 1; + segment = lineStart; } - if (end > segmentStart) + if (end > segment) { - starts.Add(segmentStart); - ends.Add(end); + lines.Add(lineNumber); + starts.Add(segment - lineStart); + ends.Add(end - lineStart); } } - private static int FindClosingQuote(string text, int from, char quote) + /// Index of the closing quote before , or -1. + private static int FindClosingQuote(string text, int from, char quote, int limit) { - for (int i = from; i < text.Length; i++) + for (int i = from; i < limit; i++) { // Double quoted values may contain \" escapes. if (quote == '"' && text[i] == '\\') @@ -248,6 +321,29 @@ private static int FindClosingQuote(string text, int from, char quote) return -1; } + /// Number of line breaks in [from, to); "\r\n" counts once, like in the editor. + private static int CountLineBreaks(string text, int from, int to) + { + int count = 0; + + for (int i = from; i < to; i++) + { + if (text[i] == '\r') + { + if (i + 1 < to && text[i + 1] == '\n') + i++; + + count++; + } + else if (text[i] == '\n') + { + count++; + } + } + + return count; + } + private static int IndexOfLineBreak(string text, int from) { int index = text.IndexOfAny(LineBreaks, from); @@ -288,14 +384,6 @@ private static int SkipExport(string text, int p, int lineEnd) return p; } - private static int TrimEnd(string text, int start, int end) - { - while (end > start && (text[end - 1] == ' ' || text[end - 1] == '\t')) - end--; - - return end; - } - private static bool IsKeyChar(char c) { return char.IsLetterOrDigit(c) || c == '_' || c == '.' || c == '-'; diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.DevTools.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.DevTools.cs index 4d70ca54b..395a5a66d 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.DevTools.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.DevTools.cs @@ -54,14 +54,14 @@ private void PrepareDeveloperFeatures(string path) } /// - /// Installs the mask generator. Called before the document is assigned to the editor, + /// Installs the mask generator. is the decoded text before long lines are truncated. Called before the document is assigned to the editor, /// so a secret is never drawn unmasked, not even for a single frame. /// - private void InstallDeveloperFeatures(string path, string text) + private void InstallDeveloperFeatures(string path, string fullText) { if (_envMaskAvailable) { - _envMask = new EnvMaskGenerator(text) { IsMasked = !_envRevealed }; + _envMask = new EnvMaskGenerator(fullText) { IsMasked = !_envRevealed }; TextArea.TextView.ElementGenerators.Add(_envMask); } } diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs index aed1e9417..31b40a82c 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/TextViewerPanel.cs @@ -377,6 +377,9 @@ public void LoadFileAsync(string path, ContextObject context) var encoding = EncodingDetector.DetectFromBytes(bufferCopy); var text = encoding.GetString(bufferCopy); + // .env masking needs the full lines: truncation can cut off a closing quote. + var fullText = text; + // Truncate overly long lines to prevent crashes and lag bool hasLongLines = TruncateLongLinesInText(ref text); @@ -396,8 +399,8 @@ public void LoadFileAsync(string path, ContextObject context) ? null : highlighting.SyntaxHighlighting; - // .env masking; installed before the document is shown. - InstallDeveloperFeatures(path, text); + // .env masking; installed before the document is shown (uses the text before truncation). + InstallDeveloperFeatures(path, fullText); Document = doc; @@ -447,4 +450,4 @@ public void LoadFileAsync(string path, ContextObject context) }, DispatcherPriority.Render); }); } -} \ No newline at end of file +} From a92a26c150843593c5b26f00e29ed4144ba87e59 Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Mon, 16 Nov 2026 16:23:37 +0530 Subject: [PATCH 5/7] fix(TextViewer): mask multi-line values after unquoted prefix and line continuations - Allow a quoted segment to span lines after an unquoted prefix - Treat a backslash before a line break as a continuation of the value --- .../Generators/EnvMaskGenerator.cs | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs index d26830d01..0c5271896 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs @@ -191,7 +191,8 @@ private static void FindValueRanges(string text, List lines, List star /// Returns the end (exclusive) of the value that starts at . /// A value is a sequence of quoted and unquoted segments, like a shell word (see "Quoting" in /// the POSIX Shell Command Language): "prefix"secret is one value, and a backslash - /// escapes the next character, so an escaped space does not end the value or start a comment. + /// escapes the next character, so an escaped space does not end the value or start a comment, and + /// an escaped line break continues the value on the next line. /// It ends at the end of the line, or at unescaped whitespace followed by '#' (a comment). /// To be safe, anything that may belong to the value is masked. /// @@ -212,11 +213,10 @@ private static int ScanValue(string text, int start) if (c == '"' || c == '\'' || c == '`') { - // A quote that opens the value or follows another quoted segment may continue over - // several lines (private keys, certificates...). In the middle of an unquoted word - // it has to close on the same line, so a lone apostrophe (O'Brien) is just a character. - int limit = afterQuote ? text.Length : IndexOfLineBreak(text, i); - int close = FindClosingQuote(text, i + 1, c, limit); + // A quoted segment may continue over several lines (private keys, certificates...), + // also after an unquoted prefix: TOKEN=prefix"first\nsecret". A quote that never + // closes (O'Brien) is just a character. + int close = FindClosingQuote(text, i + 1, c, text.Length); if (close >= 0) { @@ -226,7 +226,8 @@ private static int ScanValue(string text, int start) continue; } - // Never closed: hide the rest of this line. + // Never closed. At the start of a value hide the rest of the line, otherwise + // treat the quote as an ordinary character. if (afterQuote) return IndexOfLineBreak(text, i); @@ -240,7 +241,12 @@ private static int ScanValue(string text, int start) if (c == '\\') { // The escaped character (even a space) belongs to the value. - i += i + 1 < text.Length && text[i + 1] != '\r' && text[i + 1] != '\n' ? 2 : 1; + // A backslash before a line break continues the value on the next line. + if (i + 1 < text.Length && text[i + 1] == '\r' && i + 2 < text.Length && text[i + 2] == '\n') + i += 3; + else + i += i + 1 < text.Length ? 2 : 1; + end = i; } else if (c == ' ' || c == '\t') @@ -388,4 +394,4 @@ private static bool IsKeyChar(char c) { return char.IsLetterOrDigit(c) || c == '_' || c == '.' || c == '-'; } -} +} \ No newline at end of file From f98d221c0693c0c0866afad86936f61535a91be9 Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Mon, 16 Nov 2026 16:32:39 +0530 Subject: [PATCH 6/7] fix(TextViewer): stop mid-value quote pairing at the next assignment A literal apostrophe in an unquoted value (NAME=O'Brien) could pair with the opening quote of the next assignment and leave its multi-line value visible. --- .../Generators/EnvMaskGenerator.cs | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs index 0c5271896..6e0d7e4c9 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs @@ -214,9 +214,11 @@ private static int ScanValue(string text, int start) if (c == '"' || c == '\'' || c == '`') { // A quoted segment may continue over several lines (private keys, certificates...), - // also after an unquoted prefix: TOKEN=prefix"first\nsecret". A quote that never - // closes (O'Brien) is just a character. - int close = FindClosingQuote(text, i + 1, c, text.Length); + // also after an unquoted prefix: TOKEN=prefix"first\nsecret". In the middle of a + // word, though, a quote is usually just a character (NAME=O'Brien), so it must not + // pair with a quote that belongs to the next assignment: the search stops there. + int limit = afterQuote ? text.Length : IndexOfNextAssignment(text, i); + int close = FindClosingQuote(text, i + 1, c, limit); if (close >= 0) { @@ -308,6 +310,39 @@ private static void AddRanges(string text, int start, int end, int lineNumber, i } } + /// Start of the first line after the one holding that begins a KEY=value assignment, or the end of the text. + private static int IndexOfNextAssignment(string text, int from) + { + int position = SkipLineBreak(text, IndexOfLineBreak(text, from)); + + while (position < text.Length) + { + int lineEnd = IndexOfLineBreak(text, position); + int p = SkipBlanks(text, position, lineEnd); + + if (p < lineEnd && text[p] != '#') + { + p = SkipExport(text, p, lineEnd); + + int keyStart = p; + while (p < lineEnd && IsKeyChar(text[p])) + p++; + + if (p > keyStart) + { + p = SkipBlanks(text, p, lineEnd); + + if (p < lineEnd && text[p] == '=') + return position; + } + } + + position = SkipLineBreak(text, lineEnd); + } + + return text.Length; + } + /// Index of the closing quote before , or -1. private static int FindClosingQuote(string text, int from, char quote, int limit) { From 2692c88ddfb27634cffeeb250a8ca2e3141fd12b Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Mon, 16 Nov 2026 16:53:23 +0530 Subject: [PATCH 7/7] perf(TextViewer): cache next-assignment boundary per line in .env scan Avoids rescanning a very long line for every mid-value quote. --- .../Generators/EnvMaskGenerator.cs | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs index 6e0d7e4c9..b3136e759 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.TextViewer/Generators/EnvMaskGenerator.cs @@ -204,6 +204,12 @@ private static int ScanValue(string text, int start) // True at the start of the value and right after a closing quote. bool afterQuote = true; + // End of the line that holds the scan position, and the start of the next assignment after + // it. Both are found on first use and reused while the scan stays on that line, so a line + // with many quotes is not rescanned for each of them. + int lineEnd = -1; + int nextAssignment = -1; + while (i < text.Length) { char c = text[i]; @@ -217,7 +223,22 @@ private static int ScanValue(string text, int start) // also after an unquoted prefix: TOKEN=prefix"first\nsecret". In the middle of a // word, though, a quote is usually just a character (NAME=O'Brien), so it must not // pair with a quote that belongs to the next assignment: the search stops there. - int limit = afterQuote ? text.Length : IndexOfNextAssignment(text, i); + int limit = text.Length; + + if (!afterQuote) + { + if (i > lineEnd) + { + lineEnd = IndexOfLineBreak(text, i); + nextAssignment = -1; + } + + if (nextAssignment < 0) + nextAssignment = IndexOfNextAssignment(text, lineEnd); + + limit = nextAssignment; + } + int close = FindClosingQuote(text, i + 1, c, limit); if (close >= 0) @@ -310,10 +331,10 @@ private static void AddRanges(string text, int start, int end, int lineNumber, i } } - /// Start of the first line after the one holding that begins a KEY=value assignment, or the end of the text. - private static int IndexOfNextAssignment(string text, int from) + /// Start of the first line after the line that ends at and begins a KEY=value assignment, or the end of the text. + private static int IndexOfNextAssignment(string text, int currentLineEnd) { - int position = SkipLineBreak(text, IndexOfLineBreak(text, from)); + int position = SkipLineBreak(text, currentLineEnd); while (position < text.Length) {