microsoft / vscode

Visual Studio Code
https://code.visualstudio.com
MIT License
164.91k stars 29.52k forks source link

Add read-only mode #4873

Closed ghost closed 1 year ago

ghost commented 8 years ago

Details:

This feature should be very useful for code reviewing. And I think it's not hard to implement.

Thank you,

dna2github commented 3 years ago

learned from vscode extension samples,

we can get an idea on possible way to enable read-only mode:

the main idea is to reuse vim sample to overwrite type command.

but yes, it is not a complete read-only mode and just to prevent key typing in editor. at least, it works for just being an extension.

need to overwrite more commands like copy/paste, format document to enhance such read-only mode.

btw, i really like SneakyFish5's change mentioned above:

as far as i know, vscode runs extension host and monaco editor in different processes so that we cannot get monaco editor api on extension side; and i am not sure read-only mode for vscode itself is useful or not (i mean read-only mode is used for read-only file on filesytem, but i am not sure it is useful or not if we can enable read-only mode for an editable file), since we have terminal+vim and other ways to change file contents. therefore, if really want read-only, it is good to set the file read-only on filesytem; otherwise, extension to prevent mistake typing is enough. just personal opinion.

in addition, if we enable monaco editor readOnly option, and use format document comamnd to change file contents, the readOnly flag will be set to false then. it is also confusing.

vdh commented 3 years ago

It would be good to avoid tying this directly to the filesystem read-only mode. Most of the use cases would be viewing a file without accidentally editing it, but the file itself may be modified by non-human sources. Generated or external files like lock files, snapshots, or dependency files for example. Things that need to be reviewed next to editable files with all the advantages of IDE integration and text selection, but would cause problems if an errant keystroke made an accidental edit to it.

Gruntfuggly commented 3 years ago

Why is this not as simple as adding a 'readOnly' flag to a TextDocument? Then extensions could set/unset as required. Or am I missing something?

It should have nothing to do with the filing system - I just need to prevent a document being changed.

dna2github commented 3 years ago

Why is this not as simple as adding a 'readOnly' flag to a TextDocument? Then extensions could set/unset as required. Or am I missing something?

It should have nothing to do with the filing system - I just need to prevent a document being changed.

actually monaco editor has such flag; however, the problem is that extension world does not have access to monaco editor api.

monacoEditorApi.updateOptions({ readOnly: true });
Binly42 commented 2 years ago

A little idea relating to this I didn't see mentioned (though I may have missed it):

jaeyonglee8687 commented 2 years ago

This feature would be very helpful to prevent unnecessary manifest file changes.

V01D-NULL commented 2 years ago

Read only mode would be great. When I write code I switch between other files to reference and verify code, in the process of doing so I tend to accidentally press enter or the space bar, the autosave extension saves the file and voila. I've got myself annoying merge conflicts.

boxiangliu commented 2 years ago

A read-only mode would be so useful.

cognominal commented 2 years ago

The mode could be at different granularities. At least per file, and per workspace folder. More would probably be overengineering. Often, I edit only in the hierarchy of the initial folder of the workspace and that's the only one I want to be writable. I use other folders in the workspace as reference and model. Say I want to write an extension. I will add vscode-extension-samples folder in the workspace but I won't edit it. I want it to be read only so as not to modify it by accident.

Also by readonly, I mean readonly thru editors pane. A git pull should work

Tomade commented 2 years ago

Amazing that after almost six years since this issue was raised, VScode still can't do something that Emacs has had bound to C-x C-q since 1985. I couldn't believe it, but here we are.

Whobeu commented 2 years ago

Amazing that after almost six years since this issue was raised, VScode still can't do something that Emacs has had bound to C-x C-q since 1985. I couldn't believe it, but here we are.

I have been following this thread for almost four years now and I too am amazed. Every month I look at release notes and all the new features added with the latest release but this request never appears. @SneakyFish5 came up with a prototype two years ago but there were complaints that it touched a lot of editor code.

All I know is a week ago I again edited a file I was referencing that I did not want to. I always keep a mirror of my files before I start any edits so it was a non-event but still frustrating nonetheless when I wondered why the module I was supposedly working on was not using my changes when I tested it.

doofin commented 2 years ago

If MS don't want to do this,how about working on a new fork here? https://github.com/doofin/vscode

theAkito commented 2 years ago

Guys, Microsoft is currently busy making the code comments politically correct. They don't have time for such unimportant and minor issues, like this one.

I mean, making words and stuff politically correct is hugely improving our lives. It's super important. We can't live without it. Breaking code through unintentional edits is a minor thing, though. It only breaks our code base, but it does not break what we believe in!

gjsjohnmurray commented 2 years ago

@theAkito what connection do you see between the MS people who resource the VS Code project and those who work on MS Word?

theAkito commented 2 years ago

what connection do you see between the MS people who resource the VS Code project and those who work on MS Word?

Sigh. I knew this question would arise.

I was too lazy to look up all the articles I read about how Microsoft is cleansing everything they work on. The MS Word thing is just the newest one, which was easiest and quickest to find.

They are e.g. cleansing code comments basically in all their projects.

That said, it's the same company. So, they are using their limited amount of resources to do stuff like this. They shouldn't do it anywhere. They could use those resources, e.g. from MS Word, to invest in e.g. fixing this issue. And so on.

I hope it's clear now. 👍🏻

gjsjohnmurray commented 2 years ago

They could use those resources, e.g. from MS Word, to invest in e.g. fixing this issue.

I guess I missed the announcement when they transitioned the MS Word developers over to coding in TypeScript.

theAkito commented 2 years ago

I guess I missed the announcement when they transitioned the MS Word developers over to coding in TypeScript.

If you can program one language very well, which I expect from developers being hired by such a huge company, you can use any language.

Programming, once you get it, is pretty much always the same. Languages are basically just dialects of the root understanding of programming (how computers work, how programs work, etc...).

Perhaps, it's hard to get used to used to program idiomatically in different languages, but it's not necessary to get the job done.

Still, even if you were right in your suggestions, then they could fire those MS developers getting paid 100 bucks an hour, which are paid for making it more politically correct, and instead hire developers for this project. This would be a proposal, which would work, if your suggestion would be realistic.

That said, I'm not sure what the point of your off-topic comments is. You are obviously trying to defend an evil practice for the sake of feeling good about it, or something like that. It's fine, if you feel like spending thousands of bucks for making things worse and more evil is good. But that's not a topic for this issue and I honestly have no interest in reading how someone is trying to defend what craziness is going on in huge greedy companies for the sake of being on the masterstream, i.e. to get more money from people who try to be "inclusive" by being explicitly exclusive toward normal people.

Whobeu commented 2 years ago

If you can program one language very well, which I expect from developers being hired by such a huge company, you can use any language.

Programming, once you get it, is pretty much always the same. Languages are basically just dialects of the root understanding of programming (how computers work, how programs work, etc...).

Perhaps, it's hard to get used to used to program idiomatically in different languages, but it's not necessary to get the job done.

I've never been able to get my head around Python. I have no issue with "curly brace" languages and have C, C#, JavaScript, TypeScript and Perl (off the top of my head) in my brainbox. But Python is a weird one. The syntax as well as precise indentation format drive me crazy. I see some of the TC39 proposals for "JavaScript" (ECMAScript) and a few are trying to add Python type features IIRC.

castwide commented 2 years ago

@theAkito The article you linked is about a two-year-old feature in MS Word's grammar tools. It doesn't indicate that the VS Code team is too busy removing slurs from code comments to implement new features.

theAkito commented 2 years ago

I've never been able to get my head around Python. I have no issue with "curly brace" languages and have C, C#, JavaScript, TypeScript and Perl (off the top of my head) in my brainbox. But Python is a weird one. The syntax as well as precise indentation format drive me crazy. I see some of the TC39 proposals for "JavaScript" (ECMAScript) and a few are trying to add Python type features IIRC.

Indeed, I can understand that. I, however, feel the opposite, actually. 😄

With curly braces I have missed a closing or, after refactoring/deleting, an opening brace for so many times and it's just sometimes so hard to get around counting it correctly, when there are like 30 braces in half a page of code.

I think, it's mostly related to practice. I'm sure, if I would stop using indentation based languages altogether for a year, I would most likely get along perfectly with the brace problem after some time.

At the same time I assume, you probably would get along with the opposite, if you wouldn't deal with bracey languages all the time. It just gets probably more confusing, when you are constantly switching from one syntax to the other (which I do). 😃

The article you linked is about a two-year-old feature in MS Word's grammar tools. It doesn't indicate that the VS Code team is too busy removing slurs from code comments to implement new features.

Thank you for the information. 🙂 I did not know about that, because I stopped using Microsoft Word a very long time ago.

I did not implicate, that they literally stopped processing this issue, just to remove a slur in Microsoft Word. I was generally criticising their behaviour in the past years, regarding that topic.

Additionally, it's important to not fall for their newtalk. For example, it's not about "slurs" (as you have said in your comment) but it's about normal sentences, which are deformed and changed for the sake of appeasing a loud and screamy minority, pretending to be the majority of people around the globe.

castwide commented 2 years ago

Additionally, it's important to not fall for their newtalk. For example, it's not about "slurs" (as you have said in your comment) but it's about normal sentences, which are deformed and changed for the sake of appeasing a loud and screamy minority, pretending to be the majority of people around the globe.

There's no indication that the VS Code team is preoccupied with that, either.

theAkito commented 2 years ago

There's no indication that the VS Code team is preoccupied with that, either.

Again, of course you can try to defend the wrong behaviour by changing words and making it seem like what I say is insignificant.

The point I was making with my joke (btw. in case someone did not get it: it was a joke based on actual facts) is that Microsoft as a company (not the VS Code team particularly, as part of Microsoft) is spending more than a single penny on doing stuff like it is prortrayed in the article I linked. If they spend more than a single penny on doing something like that, they are obviously having bad company politics. That is my point. If Microsoft has bad company politics, it's not unlikely bad politics from the company as a whole drips down to lower levels, like e.g. the VS Code team in particular.

I am not accusing the VS Code team in particular to waste their time on something like that. Never did that. I just said, that Microsoft as a whole is doing such things, so it's not unlikely the VS Code team may suffer from bad company politics.

Please, don't repeat that Microsoft has nothing to do with VS Code. They are most obviously related. VS Code is literally a product coming from Microsoft.

proimage commented 2 years ago

Get a room, y'all. This isn't really the place for rabbit-trail discussions.

Granted, nothing else seems to be happening here, and you are making the thread longer and more visible, so... ¯\_(ツ)_/¯

doofin commented 2 years ago

Just setup a room for dissidents of vscode : https://gitter.im/republiccode/community?utm_source=share-link&utm_medium=link&utm_campaign=share-link

zethon commented 2 years ago

I just noticed this icon in CLion:

image

Oh, and what does it do?

image

And as far as I can tell, it only makes the file read-only in the IDE and not on the filesytem.

Come on VSCode!

henrik-jensen commented 2 years ago

Try F1/ctrl+shift+p and type 'Preferences Default' Default Keyboard Settings and Default Settings are read-only. Why can't we have that for all files? I know they both are not actually files but generated on the fly, but it seems as though most of the functionality is available.

Here's a gif animation. vscode-read-only_1650469528512

kolulu23 commented 2 years ago

It would be great if read-only is a default for "library" files(e.g. anything in node_modules). I think all JetBrains IDEs support this feature now.

henrik-jensen commented 2 years ago

@NikkoWei

您的邮件已到站

Will you please stop it,- it's is getting annoying to get an extra notification from you with that message on the email, every time others post a reply to this issue. And it clutters the thread (just like this post,- but I'll delete it as soon as you've stopped your autoreply thingy bot) Thanks PS! Google translate it from Chinese as "Your message has arrived". So I assume it is some kind of autoreply in your mail system that is misconfigured, honest mistake, but please fix it.

chrisinmtown commented 2 years ago

Visual Studio Code knows a lot about python, please consider extending it a bit more so VSC opens installed Python files in read-only mode. In other words, I feel that any python file within a virtual environment should not be editable when opened. I often open one of those files by following a definition link via control-click. Then I start editing the installed file .. and I cannot figure out why my source file is unchanged, my tox tests keep failing, etc. Thanks in advance!

universonic commented 2 years ago

您的邮件已到站

@NikkoWei Can u please stop this f**king notification?

jackpunt commented 2 years ago

If/When this is ever fixed, I'll vote for the feature requested in https://github.com/Microsoft/vscode/issues/12227 That is: a way to mark (for example) all the .js files in a */.js as readonly. (So when I'm debugging, and click into a .js file, I don't start editing it, when I really want to edit the .ts file)

Also: I do not expect or want it to change the file system; do what ^x^q does in emacs (make the buffer readonly) and just do a bing or flash when a command tries to insert/delete chars.

The big thing is to make it 'sticky' and 'glob-able' so the workspace can be programmed to block the needful files.

fumin commented 2 years ago

If there's ever a non-bot human in the VS code team, they should have blocked @NikkoWei . Instead, those goons have left this issue stale since 2006... Good job Microsoft at promoting your most promising product (that is your other products suck), by not supporting such a basic feature!

georgerdprj commented 2 years ago

I am working on an extension which would benefit a lot from being able to use the "readOnly" option of monaco editor.

var editor = monaco.editor.create(element.nativeElement, {
    model: null,
    readOnly: true
});

Being able to set an editor as having immutable state has a lot of good use cases. Please try to prioritise this feature, it seems that a lot of people would benefit from it.

georgerdprj commented 2 years ago

Hi, thinking of it, having readOnly property in the TextEditorOptions interface would resolve most of devs requirements for the start.

    /**
     * Represents a {@link TextEditor text editor}'s {@link TextEditor.options options}.
     */
    export interface TextEditorOptions {
        tabSize?: number | string;
        insertSpaces?: boolean | string;
        cursorStyle?: TextEditorCursorStyle;
        lineNumbers?: TextEditorLineNumbersStyle;
    }

Could this be a compromise that can make it better for everyone? Devs get this very useful feature and vscode team doesn't have to make major changes?

wsgalaxy commented 2 years ago

I need this option, MS support it please.

georgerdprj commented 2 years ago

@bpasero @alexdima Hi, I can see that you have been previously active on this issue. Is this issue still considered to be resolved? Or do you have any plans or updates with this one?

cdsaenz commented 2 years ago

I don't have experience with VSCode Extensions writing but maybe the vscode.workspace.onDidChangeTextDocument event might be of help? If we could equate the document to a document somehow marked as readonly (current session is enough for me) maybe we could reject those changes with some warning? Example in SO: https://stackoverflow.com/a/53293685/827376

GeorgeCrisan commented 2 years ago

@cdsaenz Hi, this is a very interesting suggestion. I've been trying myself all sorts of workarounds for the last month, and I've decided to show a dialog warning to the user saying that modifying the file will not have the desired effect and should be treated as read only. But looking at the current situation we should not have to struggle with workarounds. The editor object could very easily have access to the readOnly property already existing in the monco editor. It is already implemented in so many places in vscode. (the default settings json file for example)

Most of us need is to have that property available, as @alexdima said years ago "The editor has an option readOnly that would need to be exercised by the workbench"

@bpasero and vscode team, please do consider this issue, is one that can be done and would benefit many developers. Please do consider this feature to be implemented. All the best.

jackpunt commented 2 years ago

I've been trying to do this via an extension (as suggested in another issue/thread) Fairly straightforward to identify files listed in a include/exclude BlobPattern pair, But can't find a way to set the readOnly flag:

"The editor has an option readOnly that would need to be exercised by the workbench" I don't know what is the "workbench" to exercise... [someone let me know?]

I can find no way for an extension to get the EditModel or EditorConfiguration in order to EditorConfiguration.options.updateOptions({ readOnly: true|false });

So it seems to require an extensive mod for an extension to extend the extHost.protocol to create a path from extension back to the EditWidget (or whatever) that holds the readOnly flag.

The TextEditor object promised by vscode.window.showTextDocument(doc)in an extension is greatly impoverished. If anyone knows better how to proceed, let me know.

(I see that the DiffEditor can set the blocks of original vs current text to readOnly/writeable on line-by-line basis. But it seems wrong to create/invoke a whole new "Editor" to enable a read-only view... We want Text to be in a TextEditor, and Code to be in a CodeEditor, with all the usual language support.)

@bpasero @alexdima

jackpunt commented 2 years ago

@georgerdprj, I looked a bit into your suggestion. It appears that those 'options' are only sent to the extension, no path for extension to set them. So a mainThreadEditor could set the value, and an extension could then react to it, but not the other way. (and legitimately: readOnly/writeable is not so much a user 'option' as a transient 'state' of the Editor)

My next approach is to add a method (setReadOnly) to the extHostTextEditor [parallel to edit(), show(), hide()... ] Presumably that will create a clean path/dto back to the mainThreadEditor and we can updateOptions from there.

And to clarify the confusion about 'filesystem readOnly' vs 'writeable' This ISSUE is about the TextEditor [buffer] being 'Editable' vs 'Immutable'

I suppose when I get it working I'll open a new issue with the PR: "Enable Immutable Editor mode" To avoid confusing the original vscode implementors who likely fought greatly to sync with the filesystem modes...

GeorgeCrisan commented 2 years ago

Hi @jackpunt, thank you very much for looking into this.

jackpunt commented 2 years ago

Trying to do a "buffer-read-only" feature from an extension requires a ton of mods to the core, and still no reliable way/place to change the config and capabilities.

A simpler approach is interposing on TextFileEditorModel.isReadonly(). Augment the filesystem checks with the GlobPattern check.

Now: need to find the config settings (to get the inc/exc globs) from within TextFileEditorModel.isReadonly()...

jackpunt commented 2 years ago

IT WORKS! I'll do a PR if/when I find a legitimate way to get the workspaceService that holds the config/settings; For for those who are interested:

In vs/workbench/services/textfile/common/textFileEditorModelManager.ts

import { match as matchGlobPattern } from 'vs/base/common/glob';

  override isReadonly(): boolean {
    const workspaceService = this.filesConfigurationService.configurationService; // <-- dubious accessor
    const inglobs = workspaceService.getValue('files.readonlyInclude');
    const exglobs = workspaceService.getValue('files.readonlyExclude');
    const isPathInGlobs = (path: string, inglobs: string[], exglobs: string[]) => {
      return !!inglobs?.find(glob => matchGlobPattern(glob, path))
          && !exglobs?.find(glob => matchGlobPattern(glob, path));
    };
    if (isPathInGlobs(this.resource.fsPath, inglobs, exglobs)) { return true; }
    return this.lastResolvedFileStat?.readonly || this.fileService.hasCapability(this.resource, FileSystemProviderCapabilities.Readonly);
  }

That's all there is to it, plus contribute the 2 config settings: in vs/workbench/contrib/files/browser/files.contribution.ts

        'files.readonlyInclude': {
            'type': 'array',
            'items': {
                'type': 'string'
            },
            'default': [],
            'description': nls.localize('readonlyInclude', "Configure paths or glob patterns to open as read-only."),
            'scope': ConfigurationScope.RESOURCE
        },
        'files.readonlyExclude': {
            'type': 'array',
            'items': {
                'type': 'string'
            },
            'default': [],
            'description': nls.localize('readonlyExclude', "Overrides files.readonlyInclude: paths or glob patterns to NOT open as read-only."),
            'scope': ConfigurationScope.RESOURCE
        },
gjsjohnmurray commented 2 years ago

@jackpunt definitely looks interesting. Please submit a PR.

Why do you consider that accessor to be dubious?

GeorgeCrisan commented 2 years ago

Absolute legend, I am now away from pc until 4th of october because I am in holiday but I wish now I had the laptop with me to give a try.

jackpunt commented 2 years ago

@gjsjohnmurray Property 'configurationService' does not exist on type 'IFilesConfigurationService'.ts(2339)

I found that access path by 'browsing' in the debugger, but it is marked as an error... I'll keep looking a bit; maybe someone will tell me the obvious/correct way to get the settings. (Hmm, maybe I could inject the IConfigurationService directly into ITextModelManager ?)

Is there was an 'architectural design document' that explains how the various components of vscode are related and how they are intended to be used...??

jackpunt commented 2 years ago

Ok! "If you need the IConfigurationSevice, then just inject it!"

The only [minor] defect now is that if you edit your settings, the 'lock' decoration does not change, unless/until you close and reopen them. (happily, the isReadonly() status is updated) Ah! decoration is keyed on: if (e.hasChanged(EditorOption.readOnly)) {

TODO: somehow know to fire _onDidChangeReadonly() when config changes for a path...

TODO: get these mods into github/PR

import { match as matchGlobPattern } from 'vs/base/common/glob';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
...
    @IConfigurationService private readonly configurationService: IConfigurationService,
...
  private isReadonlySetting(): boolean {
    const inglobs = this.configurationService.getValue<string[]>('files.readonlyInclude');
    const exglobs = this.configurationService.getValue<string[]>('files.readonlyExclude');
    const isPathInGlobs = (path: string, inglobs: string[], exglobs: string[]) => {
      return !!inglobs?.find(glob => matchGlobPattern(glob, path))
        && !exglobs?.find(glob => matchGlobPattern(glob, path));
    };
    return isPathInGlobs(this.resource.fsPath, inglobs, exglobs);
  }

  override isReadonly(): boolean {
    if (this.isReadonlySetting()) { return true; }
    return this.lastResolvedFileStat?.readonly || this.fileService.hasCapability(this.resource, FileSystemProviderCapabilities.Readonly);
  }

This has been so much fun, maybe next I'll try removing the !readOnly test from mouseHandler.start There's no doc/comment to explain why you can't select code from a readonly section. #161717 [I often want to pull some code from the red section of the DiffEditor] if (!options.get(EditorOption.readOnly) // <--- WHY?? (note: seems to work fine when replaced by true)

jackpunt commented 2 years ago

PR submitted; see #161715 #161716

includes updating onDidChangeReadonly, so the 'lock' icon is updated when TextModel is activated. (astonishingly: the filesystem read-only bit does not seem to set the 'lock' icon)

The original [out-of-date] code :

import { match as matchGlobPattern } from 'vs/base/common/glob';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
...
    @IConfigurationService private readonly configurationService: IConfigurationService,
...
  private isReadonlyFromConfig(): boolean {
    const readonlyInclude = this.configurationService.getValue<string[]>('files.readonlyInclude');
    const readonlyExclude = this.configurationService.getValue<string[]>('files.readonlyExclude');
    return !!readonlyInclude?.find(glob => matchGlobPattern(glob, this.resource.fsPath))
      && !readonlyExclude?.find(glob => matchGlobPattern(glob, this.resource.fsPath));
  }

  private oldReadonly = false;

  private checkDidChangeReadonly(newReadonly: boolean): boolean {
    if (this.oldReadonly !== newReadonly) {
      this.oldReadonly = newReadonly;    // must set before fire(); reentrant.
      this._onDidChangeReadonly.fire();
    }
    return newReadonly;
  }

  override isReadonly(): boolean {
    return this.checkDidChangeReadonly(
      this.isReadonlyFromConfig() ||
      this.lastResolvedFileStat?.readonly ||
      this.fileService.hasCapability(this.resource, FileSystemProviderCapabilities.Readonly));
  }
Screen Shot 2022-09-26 at 2 53 25 PM
NorthboundTrain commented 2 years ago

This is great, Ganesh -- thank you!

Is this something that could be bound to a key, so that I could toggle the read-only flag as needed?

jackpunt commented 2 years ago

@NorthboundTrain if you want a key/command, you'll need to write extra code: I don't know if it is possible to to change the WorkspaceConfiguration 'directly' from an extension; [the extension API is pretty constrained, which is why this mod is done directly to the TextEditorModel]

Presumably, you could make an extension that auto-edits the settings.json file and saves that. (or just open your settings.json and add the file you want to set read-only)

The previous attempts to solve this generated large/complex mods that the vscode team did not want to analyze or support; so this time we do the smallest hack to achieve 99% of needful solution.

The sweet spot for this mod is to mark log files, js files (built/generated/node_modules), or other type-specific or directory-specific files as read-only.