ronantakizawa/codereview-bench huggingface dataset:
Repository: lapce/lapce
File: lapce-ui/src/app.rs (Rust)

Code before:
            window_data.maximised,
        );
        launcher = launcher.with_window(window);
    }

    let launcher = launcher.configure_env(|env, data| data.reload_env(env));
    launcher.launch(data).expect("launch failed");
}

fn new_window_desc<W, T: druid::Data>(
    window_id: WindowId,
    root: W,
    size: Size,
    pos: Point,
    maximised: bool,
) -> WindowDesc<T>
where
    W: Widget<T> + 'static,
{
    let mut desc = WindowDesc::new_with_id(window_id, root)
        .title(LocalizedString::new("Lapce").with_placeholder("Lapce"))
        .window_size(size)
        .set_position(pos);

    #[cfg(target_os = "windows")]
    if Config::load(&lapce_data::data::LapceWorkspace::default())
        .unwrap_or_default()
        .custom_titlebar()
    {
        desc = desc.show_titlebar(false);
    }

    if maximised {
        desc = desc.set_window_state(WindowState::Maximized);
    }

    if let Some(icon) = window_icon() {
        desc = desc.with_window_icon(icon);
    }

    #[cfg(target_os = "macos")]
    if true {
        desc = macos_window_desc(desc);
    }

    desc
}

#[cfg(target_os = "macos")]
fn window_icon() -> Option<druid::Icon> {
    None

Review comment (suggestion):
You can pass the ```Config``` in from the parameter. 

Code after:
            window_data.size,
            window_data.pos,
            window_data.maximised,
            &window_data.config,
        );
        launcher = launcher.with_window(window);
    }

    let launcher = launcher.configure_env(|env, data| data.reload_env(env));
    launcher.launch(data).expect("launch failed");
}

fn new_window_desc<W, T: druid::Data>(
    window_id: WindowId,
    root: W,
    size: Size,
    pos: Point,
    maximised: bool,
    #[cfg(target_os = "windows")] config: &Arc<Config>,
    #[cfg(not(target_os = "windows"))] _config: &Arc<Config>,
) -> WindowDesc<T>
where
    W: Widget<T> + 'static,
{
    let mut desc = WindowDesc::new_with_id(window_id, root)
        .title(LocalizedString::new("Lapce").with_placeholder("Lapce"))
        .window_size(size)
        .set_position(pos);

    #[cfg(target_os = "windows")]
    if config.ui.custom_titlebar() {
        desc = desc.show_titlebar(false);
    }

    if maximised {
        desc = desc.set_window_state(WindowState::Maximized);
    }

    if let Some(icon) = window_icon() {
        desc = desc.with_window_icon(icon);
    }

    #[cfg(target_os = "macos")]
    if true {
        desc = macos_window_desc(desc);
    }

    desc
}

#[cfg(target_os = "macos")]
Repository: lapce/lapce
File: lapce-data/src/editor.rs (Rust)

Code before:
    } else {
        log::error!("Failed to convert code action edit Position to offset");
    }
}

/// Checks if completion should be triggered if the received command
/// is one that inserts whitespace or deletes whitespace
fn show_completion(
    cmd: &EditCommand,
    doc: &str,
    deltas: &[(RopeDelta, InvalLines)],
) -> bool {
    let show_completion = match cmd {
        EditCommand::DeleteBackward | EditCommand::DeleteForward => {
            let start = match &deltas[0].0.els[0] {
                xi_rope::DeltaElement::Copy(_, start) => start,
                _ => &0,
            };

            let end = match &deltas[0].0.els[1] {
                xi_rope::DeltaElement::Copy(end, _) => end,
                _ => &0,
            };

            if start > &0 && end > &0 && end > start {
                let slice = &doc[*start..*end];
                !slice
                    .chars()
                    .all(|c| c.is_whitespace() || c.is_ascii_whitespace())
            } else {
                true
            }
        }
        EditCommand::InsertNewLine
        | EditCommand::InsertTab
        | EditCommand::NewLineAbove
        | EditCommand::NewLineBelow
        | EditCommand::Undo
        | EditCommand::Redo => false,
        _ => true,
    };

    show_completion
}


Review comment (performance):
You could use the ```slice_to_cow``` on the rope to make it more efficient without converting the rope to a string.

https://github.com/lapce/lapce/blob/master/lapce-core/src/buffer.rs#L931

Code after:
    } else {
        log::error!("Failed to convert code action edit Position to offset");
    }
}

/// Checks if completion should be triggered if the received command
/// is one that inserts whitespace or deletes whitespace
fn show_completion(
    cmd: &EditCommand,
    doc: &Rope,
    deltas: &[(RopeDelta, InvalLines)],
) -> bool {
    let show_completion = match cmd {
        EditCommand::DeleteBackward | EditCommand::DeleteForward => {
            let start = match &deltas[0].0.els[0] {
                xi_rope::DeltaElement::Copy(_, start) => start,
                _ => &0,
            };

            let end = match &deltas[0].0.els[1] {
                xi_rope::DeltaElement::Copy(end, _) => end,
                _ => &0,
            };

            if start > &0 && end > start {
                !doc.slice_to_cow(*start..*end)
                    .chars()
                    .all(|c| c.is_whitespace() || c.is_ascii_whitespace())
            } else {
                true
            }
        }
        EditCommand::InsertNewLine
        | EditCommand::InsertTab
        | EditCommand::NewLineAbove
        | EditCommand::NewLineBelow
        | EditCommand::Undo
        | EditCommand::Redo => false,
        _ => true,
    };

    show_completion
}
Repository: lapce/lapce
File: lapce-core/src/syntax/highlight.rs (Rust)

Code before:
    Elixir: "lang-elixir",
    Elm: "lang-elm",
    Erlang: "lang-erlang",
    Glimmer: "lang-glimmer",
    Go: "lang-go",
    Hare: "lang-hare",
    Haskell: "lang-haskell",
    Haxe: "lang-haxe",
    Hcl: "lang-hcl",
    Html: "lang-html",
    Java: "lang-java",
    Javascript: "lang-javascript",
    Json: "lang-json",
    Jsx: "lang-javascript",
    Julia: "lang-julia",
    Kotlin: "lang-kotlin",
    Latex: "lang-latex",
    Lua: "lang-lua",
    Markdown: "lang-markdown",
    MarkdownInline: "lang-markdown",
    Nix: "lang-nix",
    Ocaml: "lang-ocaml",
    OcamlInterface: "lang-ocaml",
    Php: "lang-php",
    Prisma: "lang-prisma",
    ProtoBuf: "lang-proto",
    Python: "lang-python",
    Ql: "lang-ql",
    R: "lang-r",
    Ruby: "lang-ruby",
    Rust: "lang-rust",
    Scheme: "lang-scheme",
    Scss: "lang-scss",
    Sql: "lang-sql",
    Svelte: "lang-svelte",
    Swift: "lang-swift",
    Toml: "lang-toml",
    Tsx: "lang-typescript",
    Typescript: "lang-typescript",
    Vue: "lang-vue",
    Wgsl: "lang-wgsl",
    Xml: "lang-xml",
    Yaml: "lang-yaml",
    Zig: "lang-zig",
);

/// Indicates which highlight should be applied to a region of source code.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Highlight(pub usize);

/// Represents a single step in rendering a syntax-highlighted document.

Review comment (suggestion):
```suggestion
    ProtoBuf: "lang-protobuf",
```

Code after:
    Elixir: "lang-elixir",
    Elm: "lang-elm",
    Erlang: "lang-erlang",
    Glimmer: "lang-glimmer",
    Go: "lang-go",
    Hare: "lang-hare",
    Haskell: "lang-haskell",
    Haxe: "lang-haxe",
    Hcl: "lang-hcl",
    Html: "lang-html",
    Java: "lang-java",
    Javascript: "lang-javascript",
    Json: "lang-json",
    Jsx: "lang-javascript",
    Julia: "lang-julia",
    Kotlin: "lang-kotlin",
    Latex: "lang-latex",
    Lua: "lang-lua",
    Markdown: "lang-markdown",
    MarkdownInline: "lang-markdown",
    Nix: "lang-nix",
    Ocaml: "lang-ocaml",
    OcamlInterface: "lang-ocaml",
    Php: "lang-php",
    Prisma: "lang-prisma",
    ProtoBuf: "lang-protobuf",
    Python: "lang-python",
    Ql: "lang-ql",
    R: "lang-r",
    Ruby: "lang-ruby",
    Rust: "lang-rust",
    Scheme: "lang-scheme",
    Scss: "lang-scss",
    Sql: "lang-sql",
    Svelte: "lang-svelte",
    Swift: "lang-swift",
    Toml: "lang-toml",
    Tsx: "lang-typescript",
    Typescript: "lang-typescript",
    Vue: "lang-vue",
    Wgsl: "lang-wgsl",
    Xml: "lang-xml",
    Yaml: "lang-yaml",
    Zig: "lang-zig",
);

/// Indicates which highlight should be applied to a region of source code.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Highlight(pub usize);

/// Represents a single step in rendering a syntax-highlighted document.
Repository: lapce/lapce
File: lapce-core/src/language.rs (Rust)

Code before:
    Jsx,
    #[cfg(feature = "lang-julia")]
    Julia,
    #[cfg(feature = "lang-kotlin")]
    Kotlin,
    #[cfg(feature = "lang-latex")]
    Latex,
    #[cfg(feature = "lang-lua")]
    Lua,
    #[cfg(feature = "lang-markdown")]
    Markdown,
    // TODO: Hide this when it is shown to the user!
    #[cfg(feature = "lang-markdown")]
    #[strum(serialize = "markdown.inline")]
    MarkdownInline,
    #[cfg(feature = "lang-nix")]
    Nix,
    #[cfg(feature = "lang-ocaml")]
    Ocaml,
    #[cfg(feature = "lang-ocaml")]
    OcamlInterface,
    #[cfg(feature = "lang-php")]
    Php,
    #[cfg(feature = "lang-prisma")]
    Prisma,
    #[cfg(feature = "lang-proto")]
    ProtoBuf,
    #[cfg(feature = "lang-python")]
    Python,
    #[cfg(feature = "lang-ql")]
    Ql,
    #[cfg(feature = "lang-r")]
    R,
    #[cfg(feature = "lang-ruby")]
    Ruby,
    #[cfg(feature = "lang-rust")]
    Rust,
    #[cfg(feature = "lang-scheme")]
    Scheme,
    #[cfg(feature = "lang-scss")]
    Scss,
    #[cfg(feature = "lang-sql")]
    Sql,
    #[cfg(feature = "lang-svelte")]
    Svelte,
    #[cfg(feature = "lang-swift")]
    Swift,
    #[cfg(feature = "lang-toml")]
    Toml,
    #[cfg(feature = "lang-typescript")]
    Tsx,

Review comment (suggestion):
```suggestion
    #[cfg(feature = "lang-protobuf")]
```

Code after:
    Jsx,
    #[cfg(feature = "lang-julia")]
    Julia,
    #[cfg(feature = "lang-kotlin")]
    Kotlin,
    #[cfg(feature = "lang-latex")]
    Latex,
    #[cfg(feature = "lang-lua")]
    Lua,
    #[cfg(feature = "lang-markdown")]
    Markdown,
    // TODO: Hide this when it is shown to the user!
    #[cfg(feature = "lang-markdown")]
    #[strum(serialize = "markdown.inline")]
    MarkdownInline,
    #[cfg(feature = "lang-nix")]
    Nix,
    #[cfg(feature = "lang-ocaml")]
    Ocaml,
    #[cfg(feature = "lang-ocaml")]
    OcamlInterface,
    #[cfg(feature = "lang-php")]
    Php,
    #[cfg(feature = "lang-prisma")]
    Prisma,
    #[cfg(feature = "lang-protobuf")]
    ProtoBuf,
    #[cfg(feature = "lang-python")]
    Python,
    #[cfg(feature = "lang-ql")]
    Ql,
    #[cfg(feature = "lang-r")]
    R,
    #[cfg(feature = "lang-ruby")]
    Ruby,
    #[cfg(feature = "lang-rust")]
    Rust,
    #[cfg(feature = "lang-scheme")]
    Scheme,
    #[cfg(feature = "lang-scss")]
    Scss,
    #[cfg(feature = "lang-sql")]
    Sql,
    #[cfg(feature = "lang-svelte")]
    Svelte,
    #[cfg(feature = "lang-swift")]
    Swift,
    #[cfg(feature = "lang-toml")]
    Toml,
    #[cfg(feature = "lang-typescript")]
    Tsx,
Repository: lapce/lapce
File: lapce-ui/src/app.rs (Rust)

Code before:
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
use std::{path::PathBuf, process::Stdio, sync::Arc};

use clap::Parser;
use druid::{
    AppDelegate, AppLauncher, Command, Env, Event, LocalizedString, Point, Region,
    Size, Target, Widget, WidgetExt, WidgetPod, WindowDesc, WindowHandle, WindowId,
    WindowState,
};

#[cfg(target_os = "macos")]
use lapce_core::command::FocusCommand;

#[cfg(target_os = "macos")]
use druid::{Menu, MenuItem, SysMods};

use lapce_core::meta;

use lapce_data::{
    command::{LapceUICommand, LAPCE_UI_COMMAND},
    config::LapceConfig,
    data::{
        LapceData, LapceTabLens, LapceWindowData, LapceWindowLens, LapceWorkspace,
        LapceWorkspaceType,
    },
    db::{TabsInfo, WindowInfo},
};

use crate::{
    logging::override_log_levels,
    tab::{LapceTabHeader, LAPCE_TAB_META},
    window::LapceWindow,
};

#[derive(Parser)]
#[clap(name = "Lapce")]
#[clap(version=*meta::VERSION)]
#[derive(Debug)]
struct Cli {
    /// Launch new window even if Lapce is already running
    #[clap(short, long, action)]
    new: bool,
    /// Don't return instantly when opened in terminal
    #[clap(short, long, action)]
    wait: bool,
    paths: Vec<PathBuf>,

Review comment (suggestion):
```suggestion
#[cfg(target_os = "macos")]
use druid::{Menu, MenuItem, SysMods};
#[cfg(target_os = "macos")]
use lapce_core::command::FocusCommand;
use lapce_core::meta;
use lapce_data::{
    command::{LapceUICommand, LAPCE_UI_COMMAND},
    config::LapceConfig,
```

Code after:
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
use std::{path::PathBuf, process::Stdio, sync::Arc};

use clap::Parser;
use druid::{
    AppDelegate, AppLauncher, Command, Env, Event, LocalizedString, Point, Region,
    Size, Target, Widget, WidgetExt, WidgetPod, WindowDesc, WindowHandle, WindowId,
    WindowState,
};
#[cfg(target_os = "macos")]
use druid::{Menu, MenuItem, SysMods};
#[cfg(target_os = "macos")]
use lapce_core::command::FocusCommand;
use lapce_core::meta;
use lapce_data::{
    command::{LapceUICommand, LAPCE_UI_COMMAND},
    config::LapceConfig,
    data::{
        LapceData, LapceTabLens, LapceWindowData, LapceWindowLens, LapceWorkspace,
        LapceWorkspaceType,
    },
    db::{TabsInfo, WindowInfo},
};

use crate::{
    logging::override_log_levels,
    tab::{LapceTabHeader, LAPCE_TAB_META},
    window::LapceWindow,
};

#[derive(Parser)]
#[clap(name = "Lapce")]
#[clap(version=*meta::VERSION)]
#[derive(Debug)]
struct Cli {
    /// Launch new window even if Lapce is already running
    #[clap(short, long, action)]
    new: bool,
    /// Don't return instantly when opened in terminal
    #[clap(short, long, action)]
    wait: bool,
    paths: Vec<PathBuf>,
}

pub fn build_window(data: &mut LapceWindowData) -> impl Widget<LapceData> {
    LapceWindow::new(data).lens(LapceWindowLens(data.window_id))
Repository: lapce/lapce
File: lapce-proxy/src/lib.rs (Rust)

Code before:
                }
                RpcMessage::Response(id, resp) => {
                    core_rpc.handle_response(id, Ok(resp));
                }
                RpcMessage::Error(id, err) => {
                    core_rpc.handle_response(id, Err(err));
                }
            }
        }
        local_proxy_rpc.shutdown();
    });

    let local_proxy_rpc = proxy_rpc.clone();
    std::thread::spawn(move || {
        if let Err(err) = listen_local_socket(local_proxy_rpc) {
            tracing::error!("{:?}", err);
        }
    });
    if let Err(err) = require_lapce_path() {
        tracing::error!("{:?}", err);
    }

    proxy_rpc.mainloop(&mut dispatcher);
}

pub fn require_lapce_path() -> Result<()> {
    let exedir = std::env::current_exe()?
        .parent()
        .ok_or(anyhow!("can't get parent dir of exe"))?
        .canonicalize()?;

    let current_path = std::env::var("PATH")?;
    let paths = std::env::split_paths(&current_path);
    for path in paths {
        if exedir == path.canonicalize()? {
            return Ok(());
        }
    }
    let paths = std::env::split_paths(&current_path);
    std::env::set_var(
        "PATH",
        std::env::join_paths(std::iter::once(exedir).chain(paths))?,
    );

    Ok(())
}

fn listen_local_socket(proxy_rpc: ProxyRpcHandler) -> Result<()> {
    let local_socket = Directory::local_socket()
        .ok_or_else(|| anyhow!("can't get local socket folder"))?;
    if let Err(err) = std::fs::remove_file(&local_socket) {

Review comment (suggestion):
```suggestion
pub fn register_lapce_path() -> Result<()> {
```

Code after:
                }
                RpcMessage::Response(id, resp) => {
                    core_rpc.handle_response(id, Ok(resp));
                }
                RpcMessage::Error(id, err) => {
                    core_rpc.handle_response(id, Err(err));
                }
            }
        }
        local_proxy_rpc.shutdown();
    });

    let local_proxy_rpc = proxy_rpc.clone();
    std::thread::spawn(move || {
        if let Err(err) = listen_local_socket(local_proxy_rpc) {
            tracing::error!("{:?}", err);
        }
    });
    if let Err(err) = register_lapce_path() {
        tracing::error!("{:?}", err);
    }

    proxy_rpc.mainloop(&mut dispatcher);
}

pub fn register_lapce_path() -> Result<()> {
    let exedir = std::env::current_exe()?
        .parent()
        .ok_or(anyhow!("can't get parent dir of exe"))?
        .canonicalize()?;

    let current_path = std::env::var("PATH")?;
    let paths = std::env::split_paths(&current_path);
    for path in paths {
        if exedir == path.canonicalize()? {
            return Ok(());
        }
    }
    let paths = std::env::split_paths(&current_path);
    std::env::set_var(
        "PATH",
        std::env::join_paths(std::iter::once(exedir).chain(paths))?,
    );

    Ok(())
}

fn listen_local_socket(proxy_rpc: ProxyRpcHandler) -> Result<()> {
    let local_socket = Directory::local_socket()
        .ok_or_else(|| anyhow!("can't get local socket folder"))?;
    if let Err(err) = std::fs::remove_file(&local_socket) {
Repository: laravel/framework
File: src/Illuminate/Foundation/Bootstrap/HandleExceptions.php (PHP)

Code before:
     * the HTTP and Console kernels. But, fatal error exceptions must
     * be handled differently since they are not normal exceptions.
     *
     * @param  \Throwable  $e
     * @return void
     */
    public function handleException(Throwable $e)
    {
        self::$reservedMemory = null;

        $uncaught = false;

        try {
            $this->getExceptionHandler()->report($e);
        } catch (Exception $e) {
            $uncaught = true;
        }

        if (static::$app->runningInConsole()) {
            $this->renderForConsole($e);
        } else {
            $this->renderHttpResponse($e);
        }

        if ($uncaught) {
            exit(1);
        }
    }

    /**
     * Render an exception to the console.
     *
     * @param  \Throwable  $e
     * @return void
     */
    protected function renderForConsole(Throwable $e)
    {
        $this->getExceptionHandler()->renderForConsole(new ConsoleOutput, $e);
    }

    /**
     * Render an exception as an HTTP response and send it.
     *
     * @param  \Throwable  $e
     * @return void
     */
    protected function renderHttpResponse(Throwable $e)
    {
        $this->getExceptionHandler()->render(static::$app['request'], $e)->send();
    }


Review comment (suggestion):
Wouldn't this cause Octane to exit the worker on every uncaught exception, which is not desired? 

https://github.com/laravel/octane/issues/654

Code after:
     * the HTTP and Console kernels. But, fatal error exceptions must
     * be handled differently since they are not normal exceptions.
     *
     * @param  \Throwable  $e
     * @return void
     */
    public function handleException(Throwable $e)
    {
        self::$reservedMemory = null;

        try {
            $this->getExceptionHandler()->report($e);
        } catch (Exception $e) {
            $exceptionHandlerFailed = true;
        }

        if (static::$app->runningInConsole()) {
            $this->renderForConsole($e);

            if ($exceptionHandlerFailed ?? false) {
                exit(1);
            }
        } else {
            $this->renderHttpResponse($e);
        }
    }

    /**
     * Render an exception to the console.
     *
     * @param  \Throwable  $e
     * @return void
     */
    protected function renderForConsole(Throwable $e)
    {
        $this->getExceptionHandler()->renderForConsole(new ConsoleOutput, $e);
    }

    /**
     * Render an exception as an HTTP response and send it.
     *
     * @param  \Throwable  $e
     * @return void
     */
    protected function renderHttpResponse(Throwable $e)
    {
        $this->getExceptionHandler()->render(static::$app['request'], $e)->send();
    }

    /**
     * Handle the PHP shutdown event.
Repository: laravel/framework
File: tests/Integration/Foundation/Console/AboutCommandTest.php (PHP)

Code before:
<?php

namespace Illuminate\Tests\Integration\Foundation\Console;

use Illuminate\Testing\Assert;
use Orchestra\Testbench\TestCase;

use function Orchestra\Testbench\remote;

class AboutCommandTest extends TestCase
{
    public function testItCanDisplayAboutCommandAsJson()
    {
        $process = remote('about --json', ['APP_ENV' => 'local'])->mustRun();

        tap(json_decode($process->getOutput(), true), function ($output) {
            Assert::assertArraySubset([
                'application_name' => 'Laravel',
                'php_version' => PHP_VERSION,
                'environment' => 'local',
                'debug_mode' => true,
                'url' => 'localhost',
                'maintenance_mode' => false,
            ], $output['environment']);

            Assert::assertArraySubset([
                'config' => false,
                'events' => false,
                'routes' => false,
            ], $output['cache']);

            Assert::assertArraySubset([
                'broadcasting' => 'log',
                'cache' => 'database',
                'database' => 'testing',
                'logs' => ['single'],
                'mail' => 'log',
                'queue' => 'database',
                'session' => 'cookie',
            ], $output['drivers']);
        });
    }
}


Review comment (suggestion):
I don't really like making this test depend on templates from other tests, but also I'm not sure about adding custom fixtures here as compiled views is the main concern of this about console command. I would be glad if you could help with the testing approach here.

Code after:
                'php_version' => PHP_VERSION,
                'environment' => 'local',
                'debug_mode' => true,
                'url' => 'localhost',
                'maintenance_mode' => false,
            ], $output['environment']);

            Assert::assertArraySubset([
                'config' => false,
                'events' => false,
                'routes' => false,
            ], $output['cache']);

            Assert::assertArraySubset([
                'broadcasting' => 'log',
                'cache' => 'database',
                'database' => 'testing',
                'logs' => ['single'],
                'mail' => 'log',
                'queue' => 'database',
                'session' => 'cookie',
            ], $output['drivers']);
        });
    }

    #[WithEnv('VIEW_COMPILED_PATH', __DIR__.'/../../View/templates')]
    public function testItRespectsCustomPathForCompiledViews(): void
    {
        $process = remote('about --json', ['APP_ENV' => 'local'])->mustRun();

        tap(json_decode($process->getOutput(), true), static function (array $output) {
            Assert::assertArraySubset([
                'views' => true,
            ], $output['cache']);
        });
    }
}